Changeset 7877
- Timestamp:
- 07/02/11 14:26:05 (10 years ago)
- Location:
- TI12-security/trunk/NDGSecurity/python
- Files:
-
- 1 added
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
TI12-security/trunk/NDGSecurity/python/ndg_security_server/ndg/security/server/attributeauthority.py
r7829 r7877 1 1 """NDG Attribute Authority server side code 2 2 3 handles security user attribute (role) allocation4 5 NERC Data 3 handles security user attribute (role) queries 4 5 NERC DataGrid Project 6 6 """ 7 7 __author__ = "P J Kershaw" … … 27 27 # SAML 2.0 Attribute Query Support - added 20/08/2009 28 28 from uuid import uuid4 29 from datetime import datetime,timedelta29 from datetime import timedelta 30 30 31 31 from ndg.saml.utils import SAMLDateTime … … 38 38 from ndg.security.common.saml_utils.esgf import ESGFSamlNamespaces 39 39 from ndg.security.common.X509 import X500DN 40 from ndg.security.common.utils import TypedList41 40 from ndg.security.common.utils.classfactory import instantiateClass 42 41 from ndg.security.common.utils.factory import importModuleObject … … 696 695 except ImportError: 697 696 pass 698 699 class PostgresAttributeInterface(AttributeInterface):700 """User Roles interface to Postgres database701 702 The SAML getAttributes method is NOT implemented703 704 The configuration file follows the form,705 706 [Connection]707 # name of database708 dbName: user.db709 710 # database host machine711 host: mydbhost.ac.uk712 713 # database account username714 username: mydbaccount715 716 # Password - comment out to prompt from stdin instead717 pwd: mydbpassword718 719 [getRoles]720 query0: select distinct grp from users_table, where user = '%%s'721 defaultRoles = publicRole722 """723 724 CONNECTION_SECTION_NAME = "Connection"725 GETROLES_SECTION_NAME = "getRoles"726 HOST_OPTION_NAME = "host"727 DBNAME_OPTION_NAME = "dbName"728 USERNAME_OPTION_NAME = "username"729 PWD_OPTION_NAME = "pwd"730 QUERYN_OPTION_NAME = "query%d"731 DEFAULT_ROLES_OPTION_NAME = "defaultRoles"732 733 def __init__(self, propertiesFilePath=None):734 """Connect to Postgres database"""735 self.__con = None736 self.__host = None737 self.__dbName = None738 self.__username = None739 self.__pwd = None740 741 if propertiesFilePath is None:742 raise AttributeError("No Configuration file was set")743 744 self.readConfigFile(propertiesFilePath)745 746 def __del__(self):747 """Close database connection"""748 self.close()749 750 def readConfigFile(self, propertiesFilePath):751 """Read the configuration for the database connection752 753 @type propertiesFilePath: string754 @param propertiesFilePath: file path to config file"""755 756 if not isinstance(propertiesFilePath, basestring):757 raise TypeError("Input Properties file path must be a valid "758 "string; got %r" % type(propertiesFilePath))759 760 cfg = SafeConfigParser()761 cfg.read(propertiesFilePath)762 763 self.__host = cfg.get(764 PostgresAttributeInterface.CONNECTION_SECTION_NAME,765 PostgresAttributeInterface.HOST_OPTION_NAME)766 self.__dbName = cfg.get(767 PostgresAttributeInterface.CONNECTION_SECTION_NAME,768 PostgresAttributeInterface.DBNAME_OPTION_NAME)769 self.__username = cfg.get(770 PostgresAttributeInterface.CONNECTION_SECTION_NAME,771 PostgresAttributeInterface.USERNAME_OPTION_NAME)772 self.__pwd = cfg.get(773 PostgresAttributeInterface.CONNECTION_SECTION_NAME,774 PostgresAttributeInterface.PWD_OPTION_NAME)775 776 try:777 self.__getRolesQuery = []778 for i in range(10):779 queryStr = cfg.get(780 PostgresAttributeInterface.GETROLES_SECTION_NAME,781 PostgresAttributeInterface.QUERYN_OPTION_NAME % i)782 self.__getRolesQuery += [queryStr]783 except NoOptionError:784 # Continue until no more query<n> items left785 pass786 787 # This option may be omitted in the config file788 try:789 self.__defaultRoles = cfg.get(790 PostgresAttributeInterface.GETROLES_SECTION_NAME,791 PostgresAttributeInterface.DEFAULT_ROLES_OPTION_NAME).split()792 except NoOptionError:793 self.__defaultRoles = []794 795 def connect(self,796 username=None,797 dbName=None,798 host=None,799 pwd=None,800 prompt="Database password: "):801 """Connect to database802 803 Values for keywords omitted are derived from the config file. If pwd804 is not in the config file it will be prompted for from stdin805 806 @type username: string807 @keyword username: database account username808 @type dbName: string809 @keyword dbName: name of database810 @type host: string811 @keyword host: database host machine812 @type pwd: string813 @keyword pwd: password for database account. If omitted and not in814 the config file it will be prompted for from stdin815 @type prompt: string816 @keyword prompt: override default password prompt"""817 818 if not host:819 host = self.__host820 821 if not dbName:822 dbName = self.__dbName823 824 if not username:825 username = self.__username826 827 if not pwd:828 pwd = self.__pwd829 830 if not pwd:831 import getpass832 pwd = getpass.getpass(prompt=prompt)833 834 try:835 self.__db = connect("host=%s dbname=%s user=%s password=%s" % \836 (host, dbName, username, pwd))837 self.__cursor = self.__db.cursor()838 839 except NameError, e:840 raise AttributeInterfaceError("psycopg2 Postgres package not "841 "installed? %s" % e)842 except Exception, e:843 raise AttributeInterfaceError("Error connecting to database "844 "\"%s\": %s" % (dbName, e))845 846 def close(self):847 """Close database connection"""848 if self.__con:849 self.__con.close()850 851 def getRoles(self, userId):852 """Return valid roles for the given userId853 854 @type userId: basestring855 @param userId: user identity"""856 857 try:858 self.connect()859 860 # Process each query in turn appending role names861 roles = self.__defaultRoles[:]862 for query in self.__getRolesQuery:863 try:864 self.__cursor.execute(query % userId)865 queryRes = self.__cursor.fetchall()866 867 except Exception, e:868 raise AttributeInterfaceError("Query for %s: %s" %869 (userId, e))870 871 roles += [res[0] for res in queryRes if res[0]]872 finally:873 self.close()874 875 return roles876 877 def __getCursor(self):878 """Return a database cursor instance"""879 return self.__cursor880 881 cursor = property(fget=__getCursor, doc="database cursor")882 697 883 698 … … 1250 1065 assertion.issueInstant = response.issueInstant 1251 1066 1252 # Assumes SAML response issuer name set independently -1067 # Assumes SAML response issuer details as set by - 1253 1068 # ndg.security.server.wsgi.saml.SOAPQueryInterfaceMiddleware 1254 1069 assertion.issuer = Issuer() 1255 1070 assertion.issuer.value = response.issuer.value 1256 assertion.issuer.format = Issuer.X509_SUBJECT 1071 1072 if response.issuer.format: 1073 assertion.issuer.format = response.issuer.format 1257 1074 1258 1075 assertion.conditions = Conditions() … … 1338 1155 1339 1156 log.debug('Checking for SAML subject with SQL Query = "%s"', query) 1157 1158 connection = dbEngine.connect() 1159 1340 1160 try: 1341 connection = dbEngine.connect()1342 1161 result = connection.execute(query) 1343 1162 … … 1399 1218 1400 1219 log.debug('Checking for SAML attributes with SQL Query = "%s"', query) 1220 1221 connection = dbEngine.connect() 1401 1222 1402 1223 try: 1403 connection = dbEngine.connect()1404 1224 result = connection.execute(query) 1405 1225 -
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/config/attributeauthority/sitea/attribute-service.ini
r7843 r7877 131 131 132 132 [logger_root] 133 level = INFO134 handlers = console 133 level = DEBUG 134 handlers = console, logfile 135 135 136 136 [logger_ndg] -
TI12-security/trunk/NDGSecurity/python/ndg_security_test/ndg/security/test/config/authorisationservice/authorisation-service.ini
r7842 r7877 159 159 160 160 [logger_root] 161 level = INFO162 handlers = console 161 level = DEBUG 162 handlers = console, logfile 163 163 164 164 [logger_ndg]
Note: See TracChangeset
for help on using the changeset viewer.