Пример #1
0
    def checkEntityIsWriteable(cls,
                               dbEntityInfo,
                               dbUserInfo,
                               adminGroupName=None):
        if dbUserInfo is None:
            raise AuthorizationError('User info has not been provided.')
        if adminGroupName is not None:
            for dbUserGroup in dbUserInfo.userGroupList:
                if dbUserGroup.name == adminGroupName:
                    # User belongs to admin group which can always edit entity
                    return

        if dbEntityInfo is None:
            raise AuthorizationError('Entity info has not been provided.')

        if dbEntityInfo.owner_user_id == dbUserInfo.id:
            # User owns this entity
            return

        if dbEntityInfo.is_group_writeable:
            # Entity is group writeable
            for dbUserGroup in dbUserInfo.userGroupList:
                if dbEntityInfo.owner_user_group_id == dbUserGroup.id:
                    # User belongs to group which can edit entity
                    return
        raise AuthorizationError(
            'User %s is not authorized to modify this entity.' %
            (dbUserInfo.username))
Пример #2
0
 def sendSessionRequest(self, url, method, contentType='html', data={}):
     """ Send authorized session request. """
     sm = self.getSessionManager()
     if not sm.hasSession():
         if self.username == None:
             raise AuthorizationError('Username not supplied.')
         if self.password == None:
             raise AuthorizationError('Password not supplied.')
         wsUrl = self.__getWebServiceUrl(url)
         # establishSession() sets the 'wsUrl' so the explicit call
         # to setHost() is not required
         sm.establishSession(wsUrl, self.username, self.password)
     (response, responseData) = sm.sendSessionRequest(url, method, contentType, data)
     return json.loads(responseData)
Пример #3
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)
Пример #4
0
 def checkCredentials(cls, username, password):
     """ Verifies credentials for username and password."""
     logger = LoggingManager.getInstance().getLogger(
         'LoginController:checkCredentials')
     logger.debug('Checking credential for User: %s' % (username))
     #logger.debug('Checking credential for User: %s, Password: %s' % (username, password))
     logger.debug('Session id: %s' % cherrypy.serving.session.id)
     principal = AuthorizationManager.getInstance(
     ).getAuthorizationPrincipal(username, password)
     logger.debug('Principal: %s' % (principal))
     if principal:
         cherrypy.session[
             LoginController.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(
             LoginController.SESSION_USERNAME_KEY, None)
         if username is not None:
             cherrypy.request.login = None
             cherrypy.session[
                 LoginController.INVALID_CDB_SESSION_KEY] = True
         raise AuthorizationError('Incorrect username or password.')
     cherrypy.session[
         LoginController.SESSION_USER_KEY] = principal.getUserInfo()
     return principal
Пример #5
0
 def parseBasicAuthorizationHeaders(cls):
     try:
         username = None
         password = None
         authorization = cherrypy.request.headers['authorization']
         authorizationHeader = httpauth.parseAuthorization(authorization)
         if authorizationHeader['auth_scheme'] == 'basic':
             username = authorizationHeader['username']
             password = authorizationHeader['password']
         if username and password:
             return (username, password)
         else:
             raise AuthorizationError(
                 'Username and/or password not supplied.')
     except Exception as ex:
         errorMsg = 'Could not extract username/password from authorization header: %s' % ex
         raise AuthorizationError(errorMsg)
Пример #6
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)
Пример #7
0
 def askForPassword(self):
     password = getpass.getpass()
     password = password.strip()
     if not len(password):
         raise AuthorizationError('Empty password provided.')
     return password