Skip to content
Snippets Groups Projects
Commit 4eaa4d44 authored by sveseli's avatar sveseli
Browse files

removing old prototype code

parent c34efd24
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 536 deletions
#!/usr/bin/env python
#######################################################################
DM_SESSION_ROLE_HTTP_HEADER = 'Dm-Session-Role'
DM_STATUS_CODE_HTTP_HEADER = 'Dm-Status-Code'
DM_STATUS_MESSAGE_HTTP_HEADER = 'Dm-Status-Message'
DM_EXCEPTION_TYPE_HTTP_HEADER = 'Dm-Exception-Type'
#!/usr/bin/env python
#######################################################################
DM_ADMIN_ROLE = 'admin'
DM_USER_ROLE = 'user'
#!/usr/bin/env python
#######################################################################
DM_SERVICE_PROTOCOL_HTTP = 'http'
DM_SERVICE_PROTOCOL_HTTPS = 'https'
#!/usr/bin/env python
#######################################################################
DM_OK = 0
DM_ERROR = 1
DM_CONFIGURATION_ERROR = 2
DM_INTERNAL_ERROR = 3
DM_INVALID_ARGUMENT_ERROR = 4
DM_INVALID_REQUEST_ERROR = 5
DM_COMMAND_FAILED_ERROR = 6
#!/usr/bin/env python
#
# Command failed exception class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class CommandFailed(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_COMMAND_FAILED_ERROR, **kwargs)
#!/usr/bin/env python
#
# Configuration error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class ConfigurationError(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_CONFIGURATION_ERROR, **kwargs)
#!/usr/bin/env python
#
# Base DM exception class.
#
#######################################################################
import exceptions
import json
from dm.common.constants import dmStatus
#######################################################################
class DmException(exceptions.Exception):
"""
Base DM exception class.
Usage:
DmException(errorMessage, errorCode)
DmException(args=errorMessage)
DmException(exception=exceptionObject)
"""
def __init__(self, error='', code=dmStatus.DM_ERROR, **kwargs):
args = error
if args == '':
args = kwargs.get('args', '')
ex = kwargs.get('exception', None)
if ex != None:
if isinstance(ex, exceptions.Exception):
exArgs = '%s' % (ex)
if args == '':
args = exArgs
else:
args = "%s (%s)" % (args, exArgs)
exceptions.Exception.__init__(self, args)
self._code = code
def getArgs(self):
return self.args
def getErrorCode(self):
return self._code
def getErrorMessage(self):
return '%s' % (self.args)
def getClassName(self):
return '%s' % (self.__class__.__name__)
def getExceptionType(self):
return '%s' % (self.__class__.__name__).split('.')[-1]
def getJsonRep(self):
return json.dumps({
'errorMessage' : self.getErrorMessage(),
'errorCode' : self.getErrorCode(),
'exceptionType' : self.getExceptionType(),
})
#!/usr/bin/env python
#
# DM exception map
#
#######################################################################
from dm.common.constants import dmStatus
exceptionMap = {
dmStatus.DM_ERROR : 'dmException.DmException',
dmStatus.DM_CONFIGURATION_ERROR : 'configurationError.ConfigurationError',
dmStatus.DM_INTERNAL_ERROR : 'internalError.InternalError',
dmStatus.DM_INVALID_ARGUMENT_ERROR : 'invalidArgument.InvalidArgument',
dmStatus.DM_INVALID_REQUEST_ERROR : 'invalidRequest.InvalidRequest',
dmStatus.DM_COMMAND_FAILED_ERROR : 'commandFailed.CommandFailed',
}
#######################################################################
# Testing
if __name__ == '__main__':
for item in exceptionMap.items():
print item
#!/usr/bin/env python
#
# Internal error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InternalError(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INTERNAL_ERROR, **kwargs)
#!/usr/bin/env python
#
# Invalid argument error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InvalidArgument(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INVALID_ARGUMENT_ERROR, **kwargs)
#!/usr/bin/env python
#
# Invalid request error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InvalidRequest(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INVALID_REQUEST_ERROR, **kwargs)
#!/usr/bin/env python
#
# DM Object class.
#
#######################################################################
import UserDict
import UserList
import types
import json
from dm.common.exceptions.invalidArgument import InvalidArgument
from dm.common.utility import loggingManager
class DmObject(UserDict.UserDict):
""" Base dm object class. """
def __init__(self, dict={}):
if isinstance(dict, types.DictType):
UserDict.UserDict.__init__(self, dict)
elif isinstance(dict, UserDict.UserDict):
UserDict.UserDict.__init__(self, dict.data)
else:
raise InvalidArgument('DmObject must be initialized using dictionary.')
self._jsonPreprocessKeyList = []
self._logger = None
def getLogger(self):
if not self._logger:
self._logger = loggingManager.getLogger(self.__class__.__name__)
return self._logger
@classmethod
def getFromDict(cls, dict):
inst = cls()
for key in dict.keys():
inst[key] = dict[key]
return inst
def getDictRep(self):
# Dict representation is dict
dictRep = {}
for (key,obj) in self.data.items():
if isinstance(obj, DmObject):
dictRep[key] = obj.getDictRep()
else:
if obj is not None:
dictRep[key] = obj
return dictRep
def getDictJsonPreprocessedRep(self):
dictRep = self.getDictRep()
# Convert designated keys into string values.
for key in self._jsonPreprocessKeyList:
value = dictRep.get(key)
if value is not None:
dictRep[key] = '%s' % value
return dictRep
def getJsonRep(self):
dictRep = self.getDictJsonPreprocessedRep()
return json.dumps(dictRep)
@classmethod
def fromJsonString(cls, jsonString):
return cls.getFromDict(json.loads(jsonString))
#######################################################################
# Testing.
if __name__ == '__main__':
x = {'name' : 'XYZ', 'one':1, 'two':2 }
o = DmObject(x)
print 'DM Object: ', o
print 'Type of DM object: ', type(o)
print 'JSON Rep: ', o.getJsonRep()
print 'Type of JSON rep: ', type(o.getJsonRep())
j = '{"name" : "XYZ", "one":1, "two":2 }'
print 'String: ', j
x2 = DmObject.fromJsonString(j)
print 'DM Object 2: ', x2
print 'Type of DM object 2: ', type(x2)
#!/usr/bin/env python
#
# Base object manager class.
#
#######################################################################
import threading
from dm.common.utility import loggingManager
#######################################################################
class DmObjectManager:
""" Base object manager class. """
def __init__(self):
self._logger = loggingManager.getLogger(self.__class__.__name__)
self._lock = threading.RLock()
def getLogger(self):
return self._logger
def acquireLock(self):
self._lock.acquire()
def releaseLock(self):
self._lock.release()
#!/usr/bin/env python
#
# Authorization controller class
#
#######################################################################
import cherrypy
import urllib
from cherrypy.lib import httpauth
from dm.common.constants import dmStatus
from dm.common.constants import dmRole
from dm.common.exceptions.dmException import DmException
from dm.common.exceptions.dmHttpError import DmHttpError
from dm.common.exceptions.authorizationError import AuthorizationError
from dm.common.utility import loggingManager
from dm.common.service.dmController import DmController
from dm.common.impl import authManager
import dmSession
#######################################################################
cherrypy.lib.sessions.DmSession = dmSession.DmSession
SESSION_USERNAME_KEY = '_cp_username'
SESSION_ROLE_KEY = 'role'
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[dmSession.INVALID_DM_SESSION_KEY] = True
raise AuthorizationError('Incorrect username or password.')
return principal
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)
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 DmHttpError(dmHttpStatus.DM_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 DmHttpError(dmHttpStatus.DM_HTTP_UNAUTHORIZED, 'User Not Authorized', AuthorizationError(errorMsg))
else:
logger.debug('Username is not supplied')
raise DmHttpError(dmHttpStatus.DM_HTTP_UNAUTHORIZED, 'User Not Authorized', ex)
# Add before_handler for authorization
cherrypy.tools.auth = cherrypy.Tool('before_handler', checkAuth)
#cherrypy.tools.auth = cherrypy.Tool('on_start_resource', checkAuth)
def require(*conditions):
"""
A decorator that appends conditions to the auth.require config variable.
"""
def decorate(f):
if not hasattr(f, '_cp_config'):
f._cp_config = dict()
if 'auth.require' not in f._cp_config:
f._cp_config['auth.require'] = []
f._cp_config['auth.require'].extend(conditions)
return f
return decorate
# Conditions are callables that return True if the user
# fulfills the conditions they define, False otherwise.
# They can access the current username as cherrypy.request.login
def isAdminRole():
return (cherrypy.session.get(SESSION_ROLE_KEY, None) == dmRole.DM_ADMIN_ROLE)
def isUserOrAdminRole():
role = cherrypy.session.get(SESSION_ROLE_KEY, None)
if role == dmRole.DM_ADMIN_ROLE or role == dmRole.DM_USER_ROLE:
return True
return False
def isUser(username):
result = (cherrypy.session.get(SESSION_USERNAME_KEY, None) == username)
return result
def getSessionUser():
return cherrypy.session.get(SESSION_USERNAME_KEY, None)
def memberOf(groupname):
return cherrypy.request.login == 'dm' and groupname == 'admin'
def nameIs(reqd_username):
return lambda: reqd_username == cherrypy.request.login
def anyOf(*conditions):
""" Returns True if any of the conditions match. """
def check():
for c in conditions:
if c():
return True
return False
return check
def allOf(*conditions):
""" Returns True if all of the conditions match. """
def check():
for c in conditions:
if not c():
return False
return True
return check
class AuthController(DmController):
""" Controller to provide login and logout actions. """
_cp_config = {
'tools.sessions.on' : True,
'tools.sessions.storage_type' : 'dm',
'tools.auth.on' : True
}
def __init__(self):
DmController.__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 DmHttpError, ex:
raise
except DmException, ex:
logger.debug('Authorization failed (username %s): %s' % (username, ex))
self.addDmExceptionHeaders(ex)
raise DmHttpError(dmHttpStatus.DM_HTTP_UNAUTHORIZED, 'User Not Authorized', ex)
# Authorization worked.
cherrypy.session[SESSION_USERNAME_KEY] = cherrypy.request.login = username
self.onLogin(username)
self.addDmSessionRoleHeaders(principal.getRole())
self.addDmResponseHeaders()
@cherrypy.expose
def logout(self, fromPage='/'):
sess = cherrypy.session
username = sess.get(SESSION_USERNAME_KEY, None)
if username:
del sess[SESSION_USERNAME_KEY]
cherrypy.request.login = None
self.onLogout(username)
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