Esempio n. 1
0
    def checkAuthorization(cls, *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.getInstance().getLogger(
            'LoginController:checkAuthorization')
        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.parse.quote(cherrypy.request.request_line.split()[0])
        params = urllib.parse.quote(cherrypy.request.request_line.split()[1])

        if conditions is None:
            logger.debug('No conditions imposed')
            return

        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 sessionId not in sessionCache:
            errorMsg = 'Invalid or expired session id: %s.' % sessionId
            logger.debug(errorMsg)
            raise CdbHttpError(cdbHttpStatus.CDB_HTTP_UNAUTHORIZED,
                               'User Not Authorized', InvalidSession(errorMsg))

        username = cherrypy.session.get(LoginController.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.__name__, username))
                    errorMsg = 'Authorization check %s failed for user %s.' % (
                        condition.__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)
Esempio n. 2
0
    def login(self, username=None, password=None, fromPage='/'):
        self.logger.debug('Attempting login from username %s' % (username))
        try:
            if username is None or password is None:
                self.logger.debug('Parsing auth headers for username %s' %
                                  (username))
                (username,
                 password) = LoginController.parseBasicAuthorizationHeaders()
                self.logger.debug('Retrieving principal for username %s' %
                                  (username))
            principal = LoginController.checkCredentials(username, password)
        except CdbHttpError as ex:
            raise
        except CdbException as ex:
            self.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[
            LoginController.
            SESSION_USERNAME_KEY] = cherrypy.request.login = username
        self.onLogin(username)
        self.addCdbSessionRoleHeaders(principal.getRole())
        self.addCdbResponseHeaders()
Esempio n. 3
0
class AuthController(CdbController):
    """ Controller to provide login and logout actions. """
    _cp_config = {
        'tools.sessions.on': True,
        'tools.sessions.storage_type': 'cdb',
        'tools.auth.on': True
    }

    def __init__(self):
        CdbController.__init__(self)

    def onLogin(self, username):
        """ Called on successful login. """
        return

    def onLogout(self, username):
        """ Called on logout. """
        return

    @cherrypy.expose
    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
        except CdbException, ex:
            logger.debug('Authorization failed (username %s): %s' %
                         (username, ex))
            self.addCdbExceptionHeaders(ex)
            raise CdbHttpError(cdbHttpStatus.CDB_HTTP_UNAUTHORIZED,
                               'User Not Authorized', ex)
    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()
Esempio n. 5
0
        try:
            if username is None or password is None:
                self.logger.debug('Parsing auth headers for username %s' %
                                  (username))
                (username,
                 password) = LoginController.parseBasicAuthorizationHeaders()
                self.logger.debug('Retrieving principal for username %s' %
                                  (username))
            principal = LoginController.checkCredentials(username, password)
        except CdbHttpError, ex:
            raise
        except CdbException, ex:
            self.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[
            LoginController.
            SESSION_USERNAME_KEY] = cherrypy.request.login = username
        self.onLogin(username)
        self.addCdbSessionRoleHeaders(principal.getRole())
        self.addCdbResponseHeaders()

    @cherrypy.expose
    def logout(self, fromPage='/'):
        sess = cherrypy.session
        username = sess.get(LoginController.SESSION_USERNAME_KEY, None)
        if username:
            del sess[LoginController.SESSION_USERNAME_KEY]