source: TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/classfactory.py @ 5148

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/classfactory.py@5148
Revision 5148, 4.5 KB checked in by pjkersha, 12 years ago (diff)

Added capability to pass Session Manager URI over OpenID Attribute Exchange Interface:

  • Added AXInterface interface class to OpenID Provider to set custom AX response
  • Refactored ndg.security.server.wsgi.authn to handle setting of Session Manager URI passed via AuthKit? cookie from OpenID Relying Party
  • AuthKit? cookie user data is deleted once its handed to the NDG Security session management to minimize exposure as plain text in AuthKit? cookie.
Line 
1"""
2Generic parsers to use when reading in configuration data
3- methods available to deal with both XML and INI (flat text key/val) formats
4"""
5__author__ = "C Byrom - Tessella"
6__date__ = "28/08/08"
7__copyright__ = "(C) 2009 Science and Technology Facilities Council"
8__license__ = "BSD - see LICENSE file in top-level directory"
9__contact__ = "Philip.Kershaw@stfc.ac.uk"
10__revision__ = '$Id$'
11
12import logging, os, sys
13log = logging.getLogger(__name__)
14
15class ClassFactoryError(Exception):
16    """Exception handling for NDG classfactory module."""
17    def __init__(self, msg):
18        log.error(msg)
19        Exception.__init__(self, msg)
20
21def importClass(moduleName, className=None):
22    '''Import a class from a string module name and class name.
23   
24    @param moduleName: Name of module containing the class
25    @type moduleName: str
26    @param className: Name of the class to import.  If none is given, the
27    class name will be assumed to be the last component of modulePath
28    @type className: str
29    @rtype: class object
30    @return: imported class'''
31   
32    if className is None:
33        _moduleName, className = moduleName.rsplit('.', 1)
34    else:
35        _moduleName = moduleName
36           
37    module = __import__(_moduleName)
38    components = _moduleName.split('.')
39    for component in components[1:]:
40        module = getattr(module, component)
41
42    importedClass = getattr(module, className)
43    return importedClass
44   
45
46def instantiateClass(moduleName, className, moduleFilePath=None, 
47                     objectType=None, classArgs=(), classProperties={}):
48    '''
49    Create and return an instance of the specified class
50    @param moduleName: Name of module containing the class
51    @type moduleName: str
52    @param className: Name of the class to instantiate
53    @type className: str
54    @keyword moduleFilePath: Path to the module - if unset, assume module on
55    system path already
56    @type moduleFilePath: str
57    @keyword classProperties: dict of properties to use when instantiating the
58    class
59    @type classProperties: dict
60    @keyword objectType: expected type for the object to instantiate - to
61    enforce use of specific interfaces
62    @type objectType: object
63    @return: object - instance of the class specified
64    '''
65
66    log.debug("Instantiating class '%s'" % className)
67   
68    # ensure that classproperties is a dict - NB, it may be passed in as a null
69    # value which can override the default val
70    if not classProperties:
71        classProperties = {}
72
73    # variable to store original state of the system path
74    sysPathBak = None
75    try:
76        try:
77            # Module file path may be None if the new module to be loaded
78            # can be found in the existing system path           
79            if moduleFilePath:
80                if not os.path.exists(moduleFilePath):
81                    raise IOError("Module file path '%s' doesn't exist" % 
82                                  moduleFilePath)
83                         
84                # Temporarily extend system path ready for import
85                sysPathBak = sys.path
86                         
87                sys.path.append(moduleFilePath)
88
89           
90            # Import module name specified in properties file
91            importedClass = importClass(moduleName, className=className)
92        finally:
93            # revert back to original sys path, if necessary
94            # NB, python requires the use of a try/finally OR a try/except
95            # block - not both combined
96            if sysPathBak:
97                sys.path = sysPathBak
98                           
99    except Exception, e:
100        log.error('%s module import raised %s type exception: %s' % 
101                  (moduleName, e.__class__, e))
102        raise 
103
104    # Check class inherits from AAproxy abstract base class
105    if objectType and not issubclass(importedClass, objectType):
106        raise ClassFactoryError("Specified class %s must be derived from %s" %
107                                (className, objectType))
108
109    # Instantiate class
110    try:
111        if classArgs:
112            object = importedClass(*classArgs, **classProperties)
113        else:
114            object = importedClass(**classProperties)
115           
116        log.info('Instantiated "%s" class from module, "%s"' % (className,
117                                                                moduleName))
118        return object
119
120    except Exception, e:
121        log.error("Instantiating class, %s: %s" % (importedClass.__name__, e))
122        raise
123           
124                 
Note: See TracBrowser for help on using the repository browser.