예제 #1
0
 def login(self, username=None, password=None, fromPage='/'):
     logger = loggingManager.getLogger('login')
     try:
         if username is None or password is None:
             (username, password) = parseBasicAuthorizationHeaders()
         principal = checkCredentials(username, password)
     except CdbHttpError, ex:
         raise
예제 #2
0
def checkAuth(*args, **kwargs):
    """ 
    A tool that looks in config for 'auth.require'. If found and it
    is not None, a login is required and the entry is evaluated as a list of
    conditions that the user must fulfill.
    """
    logger = loggingManager.getLogger('checkAuth')
    conditions = cherrypy.request.config.get('auth.require', None)
    logger.debug('Headers: %s' % (cherrypy.request.headers))
    logger.debug('Request params: %s' % (cherrypy.request.params))
    logger.debug('Request query string: %s' % (cherrypy.request.query_string))

    method = urllib.quote(cherrypy.request.request_line.split()[0])
    params = urllib.quote(cherrypy.request.request_line.split()[1])
    logger.debug('Session: %s' % ((cherrypy.session.__dict__)))
    if conditions is not None:
        sessionId = cherrypy.serving.session.id
        sessionCache = cherrypy.session.cache
        logger.debug('Session: %s' % ((cherrypy.session.__dict__)))
        logger.debug('Session cache length: %s' % (len(sessionCache)))
        logger.debug('Session cache: %s' % (sessionCache))
        # Check session.
        if not sessionCache.has_key(sessionId):
            errorMsg = 'Invalid or expired session id: %s.' % sessionId
            logger.debug(errorMsg)
            raise CdbHttpError(cdbHttpStatus.CDB_HTTP_UNAUTHORIZED,
                               'User Not Authorized',
                               AuthorizationError(errorMsg))

        username = cherrypy.session.get(SESSION_USERNAME_KEY)
        logger.debug('Session id %s is valid (username: %s)' %
                     (sessionId, username))
        if username:
            cherrypy.request.login = username
            for condition in conditions:
                # A condition is just a callable that returns true or false
                if not condition():
                    logger.debug(
                        'Authorization check %s failed for username %s' %
                        (condition.func_name, username))
                    errorMsg = 'Authorization check %s failed for user %s.' % (
                        condition.func_name, username)
                    raise CdbHttpError(cdbHttpStatus.CDB_HTTP_UNAUTHORIZED,
                                       'User Not Authorized',
                                       AuthorizationError(errorMsg))
        else:
            logger.debug('Username is not supplied')
            raise CdbHttpError(cdbHttpStatus.CDB_HTTP_UNAUTHORIZED,
                               'User Not Authorized', ex)
예제 #3
0
def parseBasicAuthorizationHeaders():
    try:
        logger = loggingManager.getLogger('parseBasicAuthorizationHeader')
        username = None
        password = None
        authorization = cherrypy.request.headers['authorization']
        authorizationHeader = httpauth.parseAuthorization(authorization)
        logger.debug('Authorization header: %s' % authorizationHeader)
        if authorizationHeader['auth_scheme'] == 'basic':
            username = authorizationHeader['username']
            password = authorizationHeader['password']
            logger.debug('Got username/password from headers: %s/%s' %
                         (username, password))
        if username and password:
            return (username, password)
        else:
            raise AuthorizationError('Username and/or password not supplied.')
    except Exception, ex:
        errorMsg = 'Could not extract username/password from authorization header: %s' % ex
        raise AuthorizationError(errorMsg)
예제 #4
0
def checkCredentials(username, password):
    """ Verifies credentials for username and password."""
    logger = loggingManager.getLogger('checkCredentials')
    logger.debug('Checking credential for User: %s, Password: %s' %
                 (username, password))
    logger.debug('Session id: %s' % cherrypy.serving.session.id)
    principal = authManager.getInstance().getAuthPrincipal(username, password)
    logger.debug('Principal: %s' % (principal))
    if principal:
        cherrypy.session[SESSION_ROLE_KEY] = principal.getRole()
        logger.debug('Successful login from user: %s (role: %s)' %
                     (username, principal.getRole()))
    else:
        logger.debug('Login denied for user: %s' % username)
    username = cherrypy.session.get(SESSION_USERNAME_KEY, None)

    if username is not None:
        cherrypy.request.login = None
        cherrypy.session[cdbSession.INVALID_CDB_SESSION_KEY] = True
        raise AuthorizationError('Incorrect username or password.')
    return principal
    def login(self, username=None, password=None, fromPage='/'):
        logger = loggingManager.getLogger('login')
        try:
            if username is None or password is None:
                (username, password) = parseBasicAuthorizationHeaders()
            principal = checkCredentials(username, password)
        except CdbHttpError as ex:
            raise
        except CdbException as ex:
            logger.debug('Authorization failed (username %s): %s' %
                         (username, ex))
            self.addCdbExceptionHeaders(ex)
            raise CdbHttpError(cdbHttpStatus.CDB_HTTP_UNAUTHORIZED,
                               'User Not Authorized', ex)

        # Authorization worked.
        cherrypy.session[
            SESSION_USERNAME_KEY] = cherrypy.request.login = username
        self.onLogin(username)
        self.addCdbSessionRoleHeaders(principal.getRole())
        self.addCdbResponseHeaders()
예제 #6
0
 def getLogger(self):
     if not self.logger:
         self.logger = loggingManager.getLogger(self._class__.__name__)
     return self.logger