import cherrypy
import logging
import md5, base64

log = logging.getLogger("turbogears.authentication")

class AuthMD5:
    def __init__(self, auth={}):
        self.auth = {}
        for username, password in auth.items(): 
            self.setAuth(username, password)
                                       
    def setAuth(self, username, password, encrypted=False):
        if not encrypted:
            password = md5.new(password).digest()
        self.auth[username] = password
                                                      
    def checkAuth(self, username, password):
        if not self.auth:
            return 1
        if not self.auth.has_key(username):
            return
        return self.auth[username] == md5.new(password).digest()

class Authentication:
    def __init__(self, authCheck, realm="Authentication", error=None):   
        self.authCheck = authCheck
        self.realm = realm
        if not error:   
            self.getError = self._getError
        else:
            self.getError = error
        self.username = ""
        self.password = ""
      
    def _check(self):
        if cherrypy.request.headerMap.has_key("Authorization"):
            auth = cherrypy.request.headerMap["Authorization"].split()[1]
            self.username, self.password = base64.decodestring(auth).split(":")
            if self.authCheck(self.username, self.password):
                return 1

        log.debug("Authentication response")
        cherrypy.response.status = "401 Authorization"
        cherrypy.response.headerMap["WWW-Authenticate"] = 'Basic realm="%s"' % self.realm
        
    def _getError(self):
        return "Authentication failed"

__all__ = ["AuthMD5", "Authentication"]
