#!/usr/bin/env python
#
# Copyright 2012 Red Hat, Inc
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import base64
import urllib2

import authhub

class HTTPBasicAuthHandler(authhub.Handler):
    
    def getTokenInfo(self, params):
        cfg = params.get("config", {})
        url = cfg.get("url", None)
        unm = cfg.get("username", None)
        vnd = cfg.get("vendor", None)
        
        if not isinstance(url, basestring):
            return []
        
        if not isinstance(unm, basestring):
            return []
        
        if vnd is None:
            vnd = "HTTP Basic Authentication"

        return [{"otp-vendor": vnd, "otp-format": authhub.Format.alphanumeric}]
    
    def verifyRequest(self, params):
        cfg = params.get("config", {})
        req = params.get("request", {})
        url = cfg.get("url", None)
        unm = cfg.get("username", None)
        pss = req.get("otp-value", None)
        
        if not isinstance(url, basestring):
            return False
        
        if not isinstance(unm, basestring):
            return False
        
        hdr = {"Authorization": "Basic " + base64.b64encode(unm + ":" + pss)}
        
        try:
            # TODO: add the ability to verify the certificate
            rsp = urllib2.urlopen(urllib2.Request(url, None, hdr))
            rsp.close()
            return True
        except:
            return False

if __name__ == "__main__":
    authhub.ThreadingPlugin(HTTPBasicAuthHandler()).runForever()
        
    

