Skip to content
Snippets Groups Projects
Commit 1c6d5a29 authored by sveseli's avatar sveseli
Browse files

merge common code from auth framework branch

parent 47091d89
No related branches found
No related tags found
No related merge requests found
Showing
with 205 additions and 43 deletions
......@@ -2,7 +2,23 @@
#######################################################################
DM_ADMIN_ROLE = 'Administrator'
DM_USER_ROLE = 'User'
# Sessions can have either admin or user role
DM_ADMIN_SESSION_ROLE = 'Admin'
DM_USER_SESSION_ROLE = 'User'
# System and experiment roles are used for fine grained authorization
# - "DM ADMIN" system role corresponds to "DM ADMIN" session role
# - all other system/experiment roles correspond to "DM USER" session role
DM_ADMIN_SYSTEM_ROLE = 'Administrator'
DM_ADMIN_SYSTEM_ROLE_ID = 1
DM_MANAGER_SYSTEM_ROLE = 'Manager'
DM_MANAGER_SYSTEM_ROLE_ID = 2
DM_PI_EXPERIMENT_ROLE = 'PI'
DM_PI_EXPERIMENT_ROLE_ID = 1
DM_USER_EXPERIMENT_ROLE = 'User'
DM_USER_EXPERIMENT_ROLE_ID = 2
#!/usr/bin/env python
from dmObject import DmObject
class AllowedExperimentStationExperimentType(DmObject):
DEFAULT_KEY_LIST = [ 'experimentStationId', 'experimentTypeId' ]
def __init__(self, dict):
DmObject.__init__(self, dict)
......@@ -22,14 +22,27 @@ class AuthorizationPrincipal(DmObject):
def getToken(self):
return self.get('token')
def setRole(self, role):
self['role'] = role
def setSessionRole(self, role):
self['sessionRole'] = role
def getRole(self):
return self.get('role')
def getSessionRole(self):
return self.get('sessionRole')
def setUserInfo(self, userInfo):
self['userInfo'] = userInfo
def getUserInfo(self):
return self.get('userInfo')
def setUserSystemRoleDict(self, userSystemRoleDict):
self['userSystemRoleDict'] = userSystemRoleDict
def getUserSystemRoleDict(self):
return self.get('userSystemRoleDict')
def setUserExperimentRoleDict(self, userExperimentRoleDict):
self['userExperimentRoleDict'] = userExperimentRoleDict
def getUserExperimentRoleDict(self):
return self.get('userExperimentRoleDict')
#!/usr/bin/env python
import time
from dmObject import DmObject
class DataFolder(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description', 'storageId', 'experimentId', 'dataPath' ]
def __init__(self, dict={}):
DmObject.__init__(self, dict)
####################################################################
# Testing
if __name__ == '__main__':
pass
#!/usr/bin/env python
import time
from dmObject import DmObject
class Endpoint(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description', 'storageId', 'accessUrl' ]
def __init__(self, dict={}):
DmObject.__init__(self, dict)
####################################################################
# Testing
if __name__ == '__main__':
pass
......@@ -5,7 +5,7 @@ from dmObject import DmObject
class Experiment(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'dataDirectory', 'startDate', 'endDate', 'daqStartTime', 'daqEndTime' ]
DEFAULT_KEY_LIST = [ 'id', 'name', 'experimentTypeId', 'experimentStationId', 'dataDirectory', 'startDate', 'endDate', 'daqStartTime', 'daqEndTime' ]
def __init__(self, dict={}):
DmObject.__init__(self, dict)
......
#!/usr/bin/env python
from dmObject import DmObject
class ExperimentRoleType(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description' ]
def __init__(self, dict):
DmObject.__init__(self, dict)
#!/usr/bin/env python
import time
from dmObject import DmObject
class ExperimentStation(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description' ]
def __init__(self, dict={}):
DmObject.__init__(self, dict)
####################################################################
# Testing
if __name__ == '__main__':
pass
......@@ -5,7 +5,7 @@ from dmObject import DmObject
class ExperimentType(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description`', 'rootDataPath' ]
DEFAULT_KEY_LIST = [ 'id', 'name', 'description' ]
def __init__(self, dict={}):
DmObject.__init__(self, dict)
......
#!/usr/bin/env python
import time
from dmObject import DmObject
class Storage(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description', 'defaultScheme' ]
def __init__(self, dict={}):
DmObject.__init__(self, dict)
####################################################################
# Testing
if __name__ == '__main__':
pass
#!/usr/bin/env python
from dmObject import DmObject
class SystemRoleType(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description' ]
def __init__(self, dict):
DmObject.__init__(self, dict)
......@@ -4,7 +4,7 @@ from dmObject import DmObject
class UserExperimentRole(DmObject):
DEFAULT_KEY_LIST = [ 'user_id', 'experiment_id', 'role_type_id' ]
DEFAULT_KEY_LIST = [ 'userId', 'experimentId', 'roleTypeId' ]
def __init__(self, dict):
DmObject.__init__(self, dict)
......
......@@ -4,7 +4,7 @@ from dmObject import DmObject
class UserSystemRole(DmObject):
DEFAULT_KEY_LIST = [ 'user_id', 'role_type_id' ]
DEFAULT_KEY_LIST = [ 'userId', 'experimentStationId', 'roleTypeId' ]
def __init__(self, dict):
DmObject.__init__(self, dict)
......
......@@ -16,7 +16,6 @@ class AuthorizationPrincipalManager(DmObjectManager, Singleton):
DEFAULT_CACHE_OBJECT_LIFETIME = 3600 # seconds
CONFIG_SECTION_NAME = 'AuthorizationPrincipalManager'
ADMIN_ROLE_NAME_KEY = 'adminrolename'
PRINCIPAL_RETRIEVER_KEY = 'principalretriever'
PRINCIPAL_AUTHENTICATOR_KEY = 'principalauthenticator'
......@@ -45,15 +44,12 @@ class AuthorizationPrincipalManager(DmObjectManager, Singleton):
def configure(self):
configItems = self.configurationManager.getConfigItems(AuthorizationPrincipalManager.CONFIG_SECTION_NAME)
self.logger.debug('Got config items: %s' % configItems)
adminRoleName = self.configurationManager.getConfigOption(AuthorizationPrincipalManager.CONFIG_SECTION_NAME, AuthorizationPrincipalManager.ADMIN_ROLE_NAME_KEY)
# Create principal retriever
principalRetriever = self.configurationManager.getConfigOption(AuthorizationPrincipalManager.CONFIG_SECTION_NAME, AuthorizationPrincipalManager.PRINCIPAL_RETRIEVER_KEY)
(moduleName,className,constructor) = self.configurationManager.getModuleClassConstructorTuple(principalRetriever, AuthorizationPrincipalManager)
self.logger.debug('Creating principal retriever class: %s' % className)
self.principalRetriever = ObjectUtility.createObjectInstance(moduleName, className, constructor)
if adminRoleName is not None:
self.principalRetriever.setAdminRoleName(adminRoleName)
self.logger.debug('Authorization principal retriever: %s' % (self.principalRetriever))
# Create principal authenticators
......
......@@ -6,28 +6,24 @@ from dm.common.utility.loggingManager import LoggingManager
class AuthorizationPrincipalRetriever:
def __init__(self, name=None):
self.adminRoleName = dmRole.DM_ADMIN_ROLE
self.name = name
self.logger = LoggingManager.getInstance().getLogger(self.__class__.__name__)
def getName(self):
return self.name
def setAdminRoleName(self, adminRoleName):
self.adminRoleName = adminRoleName
def getAuthorizationPrincipal(self, username):
return None
def checkAutorizationPrincipalRole(self, principal):
if principal is None or self.adminRoleName is None:
return
userInfo = principal.getUserInfo()
if userInfo is None:
def setAuthorizationPrincipalSessionRole(self, principal):
if principal is None:
return
for userSystemRoleName in userInfo.get('userSystemRoleNameList', []):
if userSystemRoleName == self.adminRoleName:
principal.setRole(dmRole.DM_ADMIN_ROLE)
for userSystemRoleId in principal.get('userSystemRoleDict', {}).keys():
if userSystemRoleId == dmRole.DM_ADMIN_SYSTEM_ROLE_ID:
principal.setSessionRole(dmRole.DM_ADMIN_SESSION_ROLE)
return
principal.setSessionRole(dmRole.DM_USER_SESSION_ROLE)
#######################################################################
# Testing.
......
......@@ -16,9 +16,9 @@ class DbPrincipalRetriever(AuthorizationPrincipalRetriever):
try:
user = self.dbApi.getUserWithPasswordByUsername(username)
principal = AuthorizationPrincipal(name=username, token=user.get('password'))
principal.setRole(dmRole.DM_USER_ROLE)
principal.setUserInfo(user)
self.checkAutorizationPrincipalRole(principal)
principal.setUserSystemRoleDict(user.get('userSystemRoleDict', {}))
principal.setUserExperimentRoleDict(user.get('userExperimentRoleDict', {}))
self.setAuthorizationPrincipalSessionRole(principal)
except Exception, ex:
self.logger.debug(ex)
return principal
......
......@@ -14,9 +14,7 @@ class NoOpPrincipalRetriever(AuthorizationPrincipalRetriever):
# Set password to be the same as username
noOpPassword = CryptUtility.cryptPasswordWithPbkdf2(username)
principal = AuthorizationPrincipal(name=username, token=noOpPassword)
principal.setRole(dmRole.DM_USER_ROLE)
if self.adminRoleName is not None:
principal.setRole(dmRole.DM_ADMIN_ROLE)
self.setAuthorizationPrincipalSessionRole(principal)
return principal
#######################################################################
......
......@@ -25,7 +25,7 @@ class DmRestWebServiceBase:
DEFAULT_SERVER_SOCKET_TIMEOUT = 30
CONFIG_SECTION_NAME = 'WebService'
CONFIG_OPTION_NAME_LIST = [ 'serviceHost', 'servicePort',
'sslCertFile', 'sslKeyFile', 'sslCaCertFile' ]
'sslCertFile', 'sslKeyFile', 'sslCaCertFile', 'stationName' ]
class SignalHandler:
def __init__(self, signal, oldSignalHandler):
......
......@@ -6,6 +6,7 @@
import cherrypy
from dm.common.constants import dmRole
from dm.common.utility.configurationManager import ConfigurationManager
from dm.common.service.dmController import DmController
from dm.common.service.loginController import LoginController
......@@ -72,7 +73,43 @@ class DmSessionController(DmController):
@classmethod
def isAdministrator(cls):
def userIsAdministrator():
result = (cherrypy.session.get(LoginController.SESSION_ROLE_KEY, None) == dmRole.DM_ADMIN_ROLE)
result = (cherrypy.session.get(LoginController.SESSION_ROLE_KEY, None) == dmRole.DM_ADMIN_SESSION_ROLE)
return result
return userIsAdministrator
@classmethod
def hasAdministratorRole(cls):
sessionRole = cherrypy.session.get(LoginController.SESSION_ROLE_KEY, None)
return (sessionRole == dmRole.DM_ADMIN_SESSION_ROLE)
@classmethod
def hasManagerRole(cls, experimentStationIdOrName):
systemRoleDict = cherrypy.session.get(LoginController.SESSION_SYSTEM_ROLE_DICT_KEY, None)
experimentStationIdOrNameList = systemRoleDict.get(dmRole.DM_MANAGER_SYSTEM_ROLE_ID, [])
if not experimentStationIdOrNameList:
# Remote sessions may come with string key
experimentStationIdOrNameList = systemRoleDict.get(str(dmRole.DM_MANAGER_SYSTEM_ROLE_ID), [])
return (experimentStationIdOrNameList.count(experimentStationIdOrName) > 0)
@classmethod
def hasPiRole(cls, experimentIdOrName):
experimentRoleDict = cherrypy.session.get(LoginController.SESSION_EXPERIMENT_ROLE_DICT_KEY, None)
experimentIdOrNameList = experimentRoleDict.get(dmRole.DM_PI_EXPERIMENT_ROLE_ID, [])
return (experimentIdOrNameList.count(experimentIdOrName) > 0)
@classmethod
def hasUserRole(cls, experimentIdOrName):
experimentRoleDict = cherrypy.session.get(LoginController.SESSION_EXPERIMENT_ROLE_DICT_KEY, None)
experimentIdOrNameList = experimentRoleDict.get(dmRole.DM_USER_EXPERIMENT_ROLE_ID, [])
return (experimentIdOrNameList.count(experimentIdOrName) > 0)
@classmethod
def canManageStation(cls):
def userCanManageStation():
if cls.hasAdministratorRole():
return True
stationName = ConfigurationManager.getInstance().getStationName()
return cls.hasManagerRole(stationName)
return userCanManageStation
......@@ -21,8 +21,9 @@ class LoginController(DmController):
""" Controller to provide login and logout actions. """
SESSION_USERNAME_KEY = '_cp_username'
SESSION_USER_KEY = 'user'
SESSION_ROLE_KEY = 'role'
SESSION_ROLE_KEY = 'sessionRole'
SESSION_SYSTEM_ROLE_DICT_KEY = 'systemRoleDict'
SESSION_EXPERIMENT_ROLE_DICT_KEY = 'experimentRoleDict'
ORIGINAL_SESSION_ID_KEY = 'originalid'
INVALID_SESSION_KEY = 'invalidSession'
......@@ -96,16 +97,19 @@ class LoginController(DmController):
#logger.debug('Checking credential for User: %s, Password: %s' % (username, password))
logger.debug('Session id: %s' % cherrypy.serving.session.id)
principal = AuthorizationPrincipalManager.getInstance().getAuthenticatedAuthorizationPrincipal(username, password)
#logger.debug('Principal: %s' % (principal))
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()))
cherrypy.session[LoginController.SESSION_ROLE_KEY] = principal.getSessionRole()
cherrypy.session[LoginController.SESSION_SYSTEM_ROLE_DICT_KEY] = principal['userSystemRoleDict']
cherrypy.session[LoginController.SESSION_EXPERIMENT_ROLE_DICT_KEY] = principal['userExperimentRoleDict']
logger.debug('Successful login from user: %s (role: %s)' % (username, principal.getSessionRole()))
# Try adding to SingleSignOnManager
sessionId = cherrypy.serving.session.id
sessionCache = cherrypy.session.cache
sessionInfo = {LoginController.SESSION_ROLE_KEY : principal.getRole()}
sessionInfo[LoginController.SESSION_USER_KEY] = principal.getUserInfo()
sessionInfo = {LoginController.SESSION_ROLE_KEY : principal.getSessionRole()}
sessionInfo[LoginController.SESSION_USERNAME_KEY] = username
sessionInfo[LoginController.SESSION_SYSTEM_ROLE_DICT_KEY] = principal.get('userSystemRoleDict', {})
sessionInfo[LoginController.SESSION_EXPERIMENT_ROLE_DICT_KEY] = principal.get('userExperimentRoleDict', {})
ssoManager = SingleSignOnManager.getInstance()
ssoManager.addSession(sessionId, sessionInfo)
else:
......@@ -115,7 +119,6 @@ class LoginController(DmController):
cherrypy.request.login = None
cherrypy.session[LoginController.INVALID_DM_SESSION_KEY] = True
raise AuthorizationError('Incorrect username or password.')
cherrypy.session[LoginController.SESSION_USER_KEY] = principal.getUserInfo()
return principal
@classmethod
......@@ -176,6 +179,8 @@ class LoginController(DmController):
raise DmHttpError(dmHttpStatus.DM_HTTP_UNAUTHORIZED, 'User Not Authorized', InvalidSession(errorMsg))
cherrypy.session[LoginController.SESSION_ROLE_KEY] = sessionInfo[LoginController.SESSION_ROLE_KEY]
cherrypy.session[LoginController.SESSION_SYSTEM_ROLE_DICT_KEY] = sessionInfo[LoginController.SESSION_SYSTEM_ROLE_DICT_KEY]
cherrypy.session[LoginController.SESSION_EXPERIMENT_ROLE_DICT_KEY] = sessionInfo[LoginController.SESSION_EXPERIMENT_ROLE_DICT_KEY]
logger.debug('Session id %s is valid (username: %s)' % (sessionId, username))
cherrypy.request.login = username
for condition in conditions:
......@@ -205,7 +210,7 @@ class LoginController(DmController):
# Authorization worked.
cherrypy.session[LoginController.SESSION_USERNAME_KEY] = cherrypy.request.login = username
self.onLogin(username)
self.addDmSessionRoleHeaders(principal.getRole())
self.addDmSessionRoleHeaders(principal.getSessionRole())
self.addDmResponseHeaders()
@cherrypy.expose
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment