<s> import itertools <EOL> import logging <EOL> import os <EOL> import time <EOL> import urllib , urllib2 <EOL> import xml <EOL> from conary import conarycfg , versions <EOL> from conary . deps import deps <EOL> from conary . repository import errors <EOL> from conary . lib import digestlib , sha1helper , tracelog <EOL> from conary . dbstore import sqlerrors <EOL> from conary . server . schema import resetTable <EOL> from . import items , accessmap , geoip <EOL> from . auth_tokens import AuthToken , ValidUser , ValidPasswordToken <EOL> log = logging . getLogger ( __name__ ) <EOL> MAX_ENTITLEMENT_LENGTH = <NUM_LIT:255> <EOL> nameCharacterSet = '<STR_LIT>' <EOL> class UserAuthorization : <EOL> pwCache = { } <EOL> def __init__ ( self , db , pwCheckUrl = None , cacheTimeout = None ) : <EOL> self . db = db <EOL> self . pwCheckUrl = pwCheckUrl <EOL> self . cacheTimeout = cacheTimeout <EOL> def addUserByMD5 ( self , cu , user , salt , password ) : <EOL> for letter in user : <EOL> if letter not in nameCharacterSet : <EOL> raise errors . InvalidName ( user ) <EOL> try : <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , <EOL> ( user , salt . encode ( '<STR_LIT>' ) , password ) ) <EOL> uid = cu . lastrowid <EOL> except sqlerrors . ColumnNotUnique : <EOL> raise errors . UserAlreadyExists , '<STR_LIT>' % user <EOL> cu . execute ( "<STR_LIT>" , <EOL> user ) <EOL> if len ( cu . fetchall ( ) ) > <NUM_LIT:1> : <EOL> raise errors . UserAlreadyExists , '<STR_LIT>' % user <EOL> return uid <EOL> def changePassword ( self , cu , user , salt , password ) : <EOL> if self . pwCheckUrl : <EOL> raise errors . CannotChangePassword <EOL> cu . execute ( "<STR_LIT>" , <EOL> password , salt . encode ( '<STR_LIT>' ) , user ) <EOL> def _checkPassword ( self , user , salt , password , challenge , remoteIp = None ) : <EOL> if challenge is ValidPasswordToken : <EOL> return True <EOL> if self . cacheTimeout : <EOL> cacheEntry = sha1helper . sha1String ( "<STR_LIT>" % ( user , challenge ) ) <EOL> timeout = self . pwCache . get ( cacheEntry , None ) <EOL> if timeout is not None and time . time ( ) < timeout : <EOL> return True <EOL> if self . pwCheckUrl : <EOL> try : <EOL> url = "<STR_LIT>" % ( self . pwCheckUrl , urllib . quote ( user ) , <EOL> urllib . quote ( challenge ) ) <EOL> if remoteIp is not None : <EOL> url += '<STR_LIT>' % urllib . quote ( remoteIp ) <EOL> f = urllib2 . urlopen ( url ) <EOL> xmlResponse = f . read ( ) <EOL> except : <EOL> return False <EOL> p = PasswordCheckParser ( ) <EOL> p . parse ( xmlResponse ) <EOL> isValid = p . validPassword ( ) <EOL> else : <EOL> m = digestlib . md5 ( ) <EOL> m . update ( salt ) <EOL> m . update ( challenge ) <EOL> isValid = m . hexdigest ( ) == password <EOL> if isValid and self . cacheTimeout : <EOL> self . pwCache [ cacheEntry ] = time . time ( ) + self . cacheTimeout <EOL> return isValid <EOL> def deleteUser ( self , cu , user ) : <EOL> userId = self . getUserIdByName ( user ) <EOL> sql = "<STR_LIT>" <EOL> cu . execute ( sql , userId ) <EOL> sql = "<STR_LIT>" <EOL> cu . execute ( sql , userId ) <EOL> def _rolesFromNames ( self , cu , roleList ) : <EOL> if not roleList : <EOL> return { } <EOL> where = [ ] <EOL> args = [ ] <EOL> if '<STR_LIT:*>' in roleList : <EOL> where . append ( '<STR_LIT:true>' ) <EOL> else : <EOL> ids = set ( [ x for x in roleList if isinstance ( x , int ) ] ) <EOL> names = set ( [ x for x in roleList if not isinstance ( x , int ) ] ) <EOL> if ids : <EOL> places = '<STR_LIT:U+002CU+0020>' . join ( '<STR_LIT:?>' for x in ids ) <EOL> where . append ( '<STR_LIT>' % ( places , ) ) <EOL> args . extend ( ids ) <EOL> if names : <EOL> places = '<STR_LIT:U+002CU+0020>' . join ( '<STR_LIT:?>' for x in names ) <EOL> where . append ( '<STR_LIT>' % ( places , ) ) <EOL> args . extend ( names ) <EOL> if not where : <EOL> return { } <EOL> where = '<STR_LIT>' . join ( where ) <EOL> query = ( "<STR_LIT>" <EOL> "<STR_LIT>" % where ) <EOL> cu . execute ( query , args ) <EOL> return dict ( ( x [ <NUM_LIT:0> ] , deps . ThawFlavor ( x [ <NUM_LIT:1> ] ) ) for x in cu ) <EOL> def getAuthorizedRoles ( self , cu , user , password , allowAnonymous = True , <EOL> remoteIp = None ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( user , ValidUser ) : <EOL> return self . _rolesFromNames ( cu , user . roles ) <EOL> cu . execute ( """<STR_LIT>""" , user ) <EOL> result = cu . fetchall ( ) <EOL> if not result : <EOL> return { } <EOL> canMirror = ( sum ( x [ <NUM_LIT:4> ] for x in result ) > <NUM_LIT:0> ) <EOL> userPasswords = [ x for x in result if x [ <NUM_LIT:3> ] != '<STR_LIT>' ] <EOL> if userPasswords and canMirror : <EOL> allowAnonymous = False <EOL> if not allowAnonymous : <EOL> result = userPasswords <EOL> if userPasswords and not self . _checkPassword ( <EOL> user , <EOL> userPasswords [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] . decode ( '<STR_LIT>' ) , <EOL> userPasswords [ <NUM_LIT:0> ] [ <NUM_LIT:1> ] , <EOL> password , remoteIp ) : <EOL> result = [ x for x in result if x [ <NUM_LIT:3> ] == '<STR_LIT>' ] <EOL> return dict ( ( x [ <NUM_LIT:2> ] , deps . ThawFlavor ( x [ <NUM_LIT:5> ] ) ) for x in result ) <EOL> def getRolesByUser ( self , user ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( """<STR_LIT>""" , user ) <EOL> return [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> def getUserIdByName ( self , userName ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" , userName ) <EOL> ret = cu . fetchall ( ) <EOL> if len ( ret ) : <EOL> return ret [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> raise errors . UserNotFound ( userName ) <EOL> def getUserList ( self ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" ) <EOL> return [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> class EntitlementAuthorization : <EOL> cache = { } <EOL> def __init__ ( self , entCheckUrl = None , cacheTimeout = None ) : <EOL> self . entCheckUrl = entCheckUrl <EOL> self . cacheTimeout = cacheTimeout <EOL> def getAuthorizedRoles ( self , cu , serverName , remoteIp , <EOL> entitlementClass , entitlement ) : <EOL> """<STR_LIT>""" <EOL> cacheEntry = sha1helper . sha1String ( "<STR_LIT>" % ( <EOL> serverName , entitlementClass , entitlement ) ) <EOL> roleIds , timeout , autoRetry = self . cache . get ( cacheEntry , ( None , None , None ) ) <EOL> if ( timeout is not None ) and time . time ( ) < timeout : <EOL> return roleIds <EOL> elif ( timeout is not None ) : <EOL> del self . cache [ cacheEntry ] <EOL> if autoRetry is not True : <EOL> raise errors . EntitlementTimeout ( [ entitlement ] ) <EOL> if self . entCheckUrl : <EOL> if entitlementClass is not None : <EOL> url = "<STR_LIT>" % ( self . entCheckUrl , urllib . quote ( serverName ) , <EOL> urllib . quote ( entitlementClass ) , <EOL> urllib . quote ( entitlement ) ) <EOL> else : <EOL> url = "<STR_LIT>" % ( self . entCheckUrl , urllib . quote ( serverName ) , <EOL> urllib . quote ( entitlement ) ) <EOL> if remoteIp is not None : <EOL> url += '<STR_LIT>' % urllib . quote ( remoteIp ) <EOL> try : <EOL> f = urllib2 . urlopen ( url ) <EOL> xmlResponse = f . read ( ) <EOL> except Exception : <EOL> return set ( ) <EOL> p = conarycfg . EntitlementParser ( ) <EOL> try : <EOL> p . parse ( xmlResponse ) <EOL> except : <EOL> return set ( ) <EOL> if p [ '<STR_LIT>' ] != serverName : <EOL> return set ( ) <EOL> entitlementClass = p [ '<STR_LIT:class>' ] <EOL> entitlement = p [ '<STR_LIT:key>' ] <EOL> entitlementRetry = p [ '<STR_LIT>' ] <EOL> if p [ '<STR_LIT>' ] is None : <EOL> entitlementTimeout = self . cacheTimeout <EOL> else : <EOL> entitlementTimeout = p [ '<STR_LIT>' ] <EOL> if entitlementTimeout is None : <EOL> entitlementTimeout = - <NUM_LIT:1> <EOL> cu . execute ( """<STR_LIT>""" , entitlement ) <EOL> roleIds = dict ( ( x [ <NUM_LIT:0> ] , deps . ThawFlavor ( x [ <NUM_LIT:1> ] ) ) for x in cu ) <EOL> if self . entCheckUrl : <EOL> self . cache [ cacheEntry ] = ( roleIds , <EOL> time . time ( ) + entitlementTimeout , <EOL> entitlementRetry ) <EOL> return roleIds <EOL> class NetworkAuthorization : <EOL> def __init__ ( self , db , serverNameList , cacheTimeout = None , log = None , <EOL> passwordURL = None , entCheckURL = None , geoIpFiles = None ) : <EOL> """<STR_LIT>""" <EOL> self . serverNameList = serverNameList <EOL> self . db = db <EOL> self . log = log or tracelog . getLog ( None ) <EOL> self . userAuth = UserAuthorization ( <EOL> self . db , passwordURL , cacheTimeout = cacheTimeout ) <EOL> self . entitlementAuth = EntitlementAuthorization ( <EOL> cacheTimeout = cacheTimeout , entCheckUrl = entCheckURL ) <EOL> self . items = items . Items ( db ) <EOL> self . ri = accessmap . RoleInstances ( db ) <EOL> self . geoIp = geoip . GeoIPLookup ( geoIpFiles or [ ] ) <EOL> def getAuthRoles ( self , cu , authToken , allowAnonymous = True ) : <EOL> """<STR_LIT>""" <EOL> self . log ( <NUM_LIT:4> , authToken [ <NUM_LIT:0> ] , authToken [ <NUM_LIT:2> ] ) <EOL> if not isinstance ( authToken , AuthToken ) : <EOL> authToken = AuthToken ( * authToken ) <EOL> roleSet = self . userAuth . getAuthorizedRoles ( <EOL> cu , authToken . user , authToken . password , <EOL> allowAnonymous = allowAnonymous , <EOL> remoteIp = authToken . remote_ip ) <EOL> timedOut = [ ] <EOL> for entClass , entKey in authToken . entitlements : <EOL> try : <EOL> rolesFromEntitlement = self . entitlementAuth . getAuthorizedRoles ( <EOL> cu , self . serverNameList [ <NUM_LIT:0> ] , authToken . remote_ip , <EOL> entClass , entKey ) <EOL> roleSet . update ( rolesFromEntitlement ) <EOL> except errors . EntitlementTimeout , e : <EOL> timedOut += e . getEntitlements ( ) <EOL> if timedOut : <EOL> raise errors . EntitlementTimeout ( timedOut ) <EOL> for roleId , acceptFlags in roleSet . items ( ) : <EOL> if authToken . flags is None : <EOL> authToken . flags = self . _getFlags ( authToken ) <EOL> if not authToken . flags . satisfies ( acceptFlags ) : <EOL> log . error ( "<STR_LIT>" <EOL> "<STR_LIT>" , <EOL> authToken . remote_ip , roleId , <EOL> authToken . flags , acceptFlags ) <EOL> raise errors . InsufficientPermission <EOL> return set ( roleSet ) <EOL> def _getFlags ( self , authToken ) : <EOL> flags = deps . Flavor ( ) <EOL> for addr in authToken . getAllIps ( ) : <EOL> if not addr : <EOL> continue <EOL> try : <EOL> flags . union ( self . geoIp . getFlags ( addr ) ) <EOL> except : <EOL> continue <EOL> return flags <EOL> def batchCheck ( self , authToken , troveList , write = False , cu = None ) : <EOL> """<STR_LIT>""" <EOL> self . log ( <NUM_LIT:3> , authToken [ <NUM_LIT:0> ] , "<STR_LIT>" % ( authToken [ <NUM_LIT:2> ] , int ( bool ( write ) ) ) , <EOL> troveList ) <EOL> checkList = [ ] <EOL> for i , ( n , v , f ) in enumerate ( troveList ) : <EOL> h = versions . VersionFromString ( v ) . getHost ( ) <EOL> if h not in self . serverNameList : <EOL> raise errors . RepositoryMismatch ( self . serverNameList , h ) <EOL> checkList . append ( ( i , n , v , f ) ) <EOL> retlist = [ False ] * len ( checkList ) <EOL> if not authToken [ <NUM_LIT:0> ] : <EOL> return retlist <EOL> if cu is None : <EOL> cu = self . db . cursor ( ) <EOL> try : <EOL> groupIds = self . getAuthRoles ( cu , authToken ) <EOL> except errors . InsufficientPermission : <EOL> return retlist <EOL> if not len ( groupIds ) : <EOL> return retlist <EOL> resetTable ( cu , "<STR_LIT>" ) <EOL> self . db . bulkload ( "<STR_LIT>" , checkList , [ "<STR_LIT>" , "<STR_LIT:name>" , "<STR_LIT:version>" , "<STR_LIT>" ] , <EOL> start_transaction = False ) <EOL> self . db . analyze ( "<STR_LIT>" ) <EOL> writeCheck = '<STR_LIT>' <EOL> if write : <EOL> writeCheck = "<STR_LIT>" <EOL> cu . execute ( """<STR_LIT>""" % ( "<STR_LIT:U+002C>" . join ( "<STR_LIT>" % x for x in groupIds ) , writeCheck ) ) <EOL> for i , instanceId in cu : <EOL> retlist [ i ] = True <EOL> return retlist <EOL> def commitCheck ( self , authToken , nameVersionList ) : <EOL> """<STR_LIT>""" <EOL> self . log ( <NUM_LIT:3> , authToken [ <NUM_LIT:0> ] , "<STR_LIT>" % ( authToken [ <NUM_LIT:2> ] , ) , nameVersionList ) <EOL> checkDict = { } <EOL> troveList = [ ] <EOL> for i , ( n , v ) in enumerate ( nameVersionList ) : <EOL> label = v . branch ( ) . label ( ) <EOL> if label . getHost ( ) not in self . serverNameList : <EOL> raise errors . RepositoryMismatch ( self . serverNameList , label . getHost ( ) ) <EOL> l = checkDict . setdefault ( label . asString ( ) , set ( ) ) <EOL> troveList . append ( n ) <EOL> l . add ( i ) <EOL> retlist = [ False ] * len ( troveList ) <EOL> if not authToken [ <NUM_LIT:0> ] : <EOL> return retlist <EOL> cu = self . db . cursor ( ) <EOL> try : <EOL> groupIds = self . getAuthRoles ( cu , authToken ) <EOL> except errors . InsufficientPermission : <EOL> return retlist <EOL> if not len ( groupIds ) : <EOL> return retlist <EOL> stmt = """<STR_LIT>""" <EOL> where = [ "<STR_LIT>" ] <EOL> where . append ( "<STR_LIT>" % <EOL> "<STR_LIT:U+002C>" . join ( "<STR_LIT>" % x for x in groupIds ) ) <EOL> if len ( checkDict ) : <EOL> where . append ( """<STR_LIT>""" ) <EOL> stmt += "<STR_LIT>" + "<STR_LIT>" . join ( where ) <EOL> for label in checkDict . iterkeys ( ) : <EOL> cu . execute ( stmt , label ) <EOL> patterns = [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> for i in checkDict [ label ] : <EOL> for pattern in patterns : <EOL> if self . checkTrove ( pattern , troveList [ i ] ) : <EOL> retlist [ i ] = True <EOL> break <EOL> return retlist <EOL> def authCheck ( self , authToken , admin = False , mirror = False ) : <EOL> self . log ( <NUM_LIT:3> , authToken [ <NUM_LIT:0> ] , <EOL> "<STR_LIT>" % ( <EOL> authToken [ <NUM_LIT:2> ] , int ( bool ( admin ) ) , int ( bool ( mirror ) ) ) ) <EOL> if not authToken [ <NUM_LIT:0> ] : <EOL> return False <EOL> cu = self . db . cursor ( ) <EOL> try : <EOL> groupIds = self . getAuthRoles ( cu , authToken ) <EOL> except errors . InsufficientPermission : <EOL> return False <EOL> if len ( groupIds ) < <NUM_LIT:1> : <EOL> return False <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" % ( <EOL> "<STR_LIT:U+002C>" . join ( "<STR_LIT>" % x for x in groupIds ) ) ) <EOL> hasAdmin = False <EOL> hasMirror = False <EOL> for mirrorBit , adminBit in cu . fetchall ( ) : <EOL> if admin and adminBit : <EOL> hasAdmin = True <EOL> if mirror and ( mirrorBit or adminBit ) : <EOL> hasMirror = True <EOL> admin = ( not admin ) or ( admin and hasAdmin ) <EOL> mirror = ( not mirror ) or ( mirror and hasMirror ) <EOL> return admin and mirror <EOL> def checkPassword ( self , authToken ) : <EOL> cu = self . db . cursor ( ) <EOL> user = authToken [ <NUM_LIT:0> ] <EOL> password = authToken [ <NUM_LIT:1> ] <EOL> cu . execute ( '<STR_LIT>' , user ) <EOL> rows = cu . fetchall ( ) <EOL> if not len ( rows ) : <EOL> return False <EOL> salt , challenge = rows [ <NUM_LIT:0> ] <EOL> salt = salt . decode ( '<STR_LIT>' ) <EOL> return self . userAuth . _checkPassword ( user , salt , challenge , password ) <EOL> def check ( self , authToken , write = False , label = None , <EOL> trove = None , remove = False , allowAnonymous = True ) : <EOL> self . log ( <NUM_LIT:3> , authToken [ <NUM_LIT:0> ] , <EOL> "<STR_LIT>" % ( <EOL> authToken [ <NUM_LIT:2> ] , int ( bool ( write ) ) , label , trove , int ( bool ( remove ) ) ) ) <EOL> if label and label . getHost ( ) not in self . serverNameList : <EOL> raise errors . RepositoryMismatch ( self . serverNameList , label . getHost ( ) ) <EOL> if not authToken [ <NUM_LIT:0> ] : <EOL> return False <EOL> cu = self . db . cursor ( ) <EOL> try : <EOL> groupIds = self . getAuthRoles ( cu , authToken , <EOL> allowAnonymous = allowAnonymous ) <EOL> except errors . InsufficientPermission : <EOL> return False <EOL> if len ( groupIds ) < <NUM_LIT:1> : <EOL> return False <EOL> elif not label and not trove and not remove and not write : <EOL> return True <EOL> stmt = """<STR_LIT>""" <EOL> params = [ ] <EOL> where = [ ] <EOL> if len ( groupIds ) : <EOL> where . append ( "<STR_LIT>" % <EOL> "<STR_LIT:U+002C>" . join ( "<STR_LIT>" % x for x in groupIds ) ) <EOL> if label : <EOL> where . append ( """<STR_LIT>""" ) <EOL> params . append ( label . asString ( ) ) <EOL> if write : <EOL> where . append ( "<STR_LIT>" ) <EOL> if remove : <EOL> where . append ( "<STR_LIT>" ) <EOL> if where : <EOL> stmt += "<STR_LIT>" + "<STR_LIT>" . join ( where ) <EOL> self . log ( <NUM_LIT:4> , stmt , params ) <EOL> cu . execute ( stmt , params ) <EOL> for ( pattern , ) in cu : <EOL> if self . checkTrove ( pattern , trove ) : <EOL> return True <EOL> return False <EOL> def checkTrove ( self , pattern , trove ) : <EOL> return items . checkTrove ( pattern , trove ) <EOL> def addAcl ( self , role , trovePattern , label , write = False , <EOL> remove = False ) : <EOL> self . log ( <NUM_LIT:3> , role , trovePattern , label , write , remove ) <EOL> cu = self . db . cursor ( ) <EOL> write = int ( bool ( write ) ) <EOL> remove = int ( bool ( remove ) ) <EOL> if trovePattern : <EOL> itemId = self . items . getOrAddId ( trovePattern ) <EOL> else : <EOL> itemId = <NUM_LIT:0> <EOL> if label : <EOL> cu . execute ( "<STR_LIT>" , label ) <EOL> labelId = cu . fetchone ( ) <EOL> if labelId : <EOL> labelId = labelId [ <NUM_LIT:0> ] <EOL> else : <EOL> cu . execute ( "<STR_LIT>" , label ) <EOL> labelId = cu . lastrowid <EOL> else : <EOL> labelId = <NUM_LIT:0> <EOL> roleId = self . _getRoleIdByName ( role ) <EOL> try : <EOL> cu . execute ( """<STR_LIT>""" , ( <EOL> roleId , labelId , itemId , write , remove ) ) <EOL> permissionId = cu . lastrowid <EOL> except sqlerrors . ColumnNotUnique : <EOL> self . db . rollback ( ) <EOL> raise errors . PermissionAlreadyExists , "<STR_LIT>" % ( <EOL> labelId , itemId ) <EOL> self . ri . addPermissionId ( permissionId , roleId ) <EOL> self . db . commit ( ) <EOL> def editAcl ( self , role , oldTroveId , oldLabelId , troveId , labelId , <EOL> write = False , canRemove = False ) : <EOL> self . log ( <NUM_LIT:3> , role , ( oldTroveId , oldLabelId ) , ( troveId , labelId ) , <EOL> write , canRemove ) <EOL> cu = self . db . cursor ( ) <EOL> roleId = self . _getRoleIdByName ( role ) <EOL> write = int ( bool ( write ) ) <EOL> canRemove = int ( bool ( canRemove ) ) <EOL> cu . execute ( """<STR_LIT>""" , <EOL> ( roleId , oldLabelId , oldTroveId ) ) <EOL> ret = cu . fetchall ( ) <EOL> if not ret : <EOL> return <EOL> permissionId = ret [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> try : <EOL> cu . execute ( """<STR_LIT>""" , ( labelId , troveId , write , canRemove , permissionId ) ) <EOL> except sqlerrors . ColumnNotUnique : <EOL> self . db . rollback ( ) <EOL> raise errors . PermissionAlreadyExists , "<STR_LIT>" % ( <EOL> labelId , troveId ) <EOL> if oldLabelId != labelId or oldTroveId != troveId : <EOL> self . ri . updatePermissionId ( permissionId , roleId ) <EOL> else : <EOL> self . ri . updateCanWrite ( permissionId , roleId ) <EOL> self . db . commit ( ) <EOL> def deleteAcl ( self , role , label , item ) : <EOL> self . log ( <NUM_LIT:3> , role , label , item ) <EOL> roleId = self . _getRoleIdByName ( role ) <EOL> if item is None : item = '<STR_LIT>' <EOL> if label is None : label = '<STR_LIT>' <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( """<STR_LIT>""" , ( roleId , label , item ) ) <EOL> cu . execute ( """<STR_LIT>""" , ( roleId , label , item ) ) <EOL> for permissionId , in cu . fetchall ( ) : <EOL> self . ri . deletePermissionId ( permissionId , roleId ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> permissionId ) <EOL> self . db . commit ( ) <EOL> def addUser ( self , user , password ) : <EOL> self . log ( <NUM_LIT:3> , user ) <EOL> salt = os . urandom ( <NUM_LIT:4> ) <EOL> m = digestlib . md5 ( ) <EOL> m . update ( salt ) <EOL> m . update ( password ) <EOL> self . addUserByMD5 ( user , salt , m . hexdigest ( ) ) <EOL> def roleIsAdmin ( self , role ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> role ) <EOL> ret = cu . fetchall ( ) <EOL> if len ( ret ) : <EOL> return ret [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> raise errors . RoleNotFound <EOL> def roleCanMirror ( self , role ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> role ) <EOL> ret = cu . fetchall ( ) <EOL> if len ( ret ) : <EOL> return ret [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> raise errors . RoleNotFound <EOL> def setAdmin ( self , role , admin ) : <EOL> self . log ( <NUM_LIT:3> , role , admin ) <EOL> cu = self . db . transaction ( ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> ( int ( bool ( admin ) ) , role ) ) <EOL> self . db . commit ( ) <EOL> def setUserRoles ( self , userName , roleList ) : <EOL> cu = self . db . cursor ( ) <EOL> userId = self . userAuth . getUserIdByName ( userName ) <EOL> cu . execute ( """<STR_LIT>""" , userId ) <EOL> for role in roleList : <EOL> self . addRoleMember ( role , userName , commit = False ) <EOL> self . db . commit ( ) <EOL> def setMirror ( self , role , canMirror ) : <EOL> self . log ( <NUM_LIT:3> , role , canMirror ) <EOL> cu = self . db . transaction ( ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> ( int ( bool ( canMirror ) ) , role ) ) <EOL> self . db . commit ( ) <EOL> def _checkValidName ( self , name ) : <EOL> for letter in name : <EOL> if letter not in nameCharacterSet : <EOL> raise errors . InvalidName ( name ) <EOL> def addUserByMD5 ( self , user , salt , password ) : <EOL> self . log ( <NUM_LIT:3> , user ) <EOL> self . _checkValidName ( user ) <EOL> cu = self . db . transaction ( ) <EOL> try : <EOL> uid = self . userAuth . addUserByMD5 ( cu , user , salt , password ) <EOL> except : <EOL> self . db . rollback ( ) <EOL> raise <EOL> else : <EOL> self . db . commit ( ) <EOL> return uid <EOL> def deleteUserByName ( self , user , deleteRole = True ) : <EOL> self . log ( <NUM_LIT:3> , user ) <EOL> cu = self . db . cursor ( ) <EOL> if deleteRole : <EOL> cu . execute ( """<STR_LIT>""" , { "<STR_LIT:user>" : user } ) <EOL> if cu . fetchone ( ) [ <NUM_LIT:0> ] == <NUM_LIT:0> : <EOL> try : <EOL> self . deleteRole ( user , False ) <EOL> except errors . RoleNotFound : <EOL> pass <EOL> self . userAuth . deleteUser ( cu , user ) <EOL> self . db . commit ( ) <EOL> def changePassword ( self , user , newPassword ) : <EOL> self . log ( <NUM_LIT:3> , user ) <EOL> salt = os . urandom ( <NUM_LIT:4> ) <EOL> m = digestlib . md5 ( ) <EOL> m . update ( salt ) <EOL> m . update ( newPassword ) <EOL> cu = self . db . cursor ( ) <EOL> self . userAuth . changePassword ( cu , user , salt , m . hexdigest ( ) ) <EOL> self . db . commit ( ) <EOL> def getRoles ( self , user ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( """<STR_LIT>""" , user ) <EOL> return [ row [ <NUM_LIT:0> ] for row in cu ] <EOL> def getRoleList ( self ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" ) <EOL> return [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> def getRoleMembers ( self , role ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( """<STR_LIT>""" , role ) <EOL> return [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> def _queryPermsByRole ( self , role ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( """<STR_LIT>""" , role ) <EOL> return cu <EOL> def iterPermsByRole ( self , role ) : <EOL> cu = self . _queryPermsByRole ( role ) <EOL> for row in cu : <EOL> yield row <EOL> def getPermsByRole ( self , roleName ) : <EOL> cu = self . _queryPermsByRole ( roleName ) <EOL> results = cu . fetchall ( ) <EOL> l = [ ] <EOL> for result in results : <EOL> d = { } <EOL> for key in ( '<STR_LIT:label>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> d [ key ] = result [ key ] <EOL> l . append ( d ) <EOL> return l <EOL> def _getRoleIdByName ( self , role ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> role ) <EOL> ret = cu . fetchall ( ) <EOL> if len ( ret ) : <EOL> return ret [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> raise errors . RoleNotFound <EOL> def _checkDuplicates ( self , cu , role ) : <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , role ) <EOL> if len ( cu . fetchall ( ) ) > <NUM_LIT:1> : <EOL> self . db . rollback ( ) <EOL> raise errors . RoleAlreadyExists ( '<STR_LIT>' % role ) <EOL> def addRole ( self , role ) : <EOL> self . log ( <NUM_LIT:3> , role ) <EOL> self . _checkValidName ( role ) <EOL> cu = self . db . transaction ( ) <EOL> try : <EOL> cu . execute ( "<STR_LIT>" , role ) <EOL> ugid = cu . lastrowid <EOL> except sqlerrors . ColumnNotUnique : <EOL> self . db . rollback ( ) <EOL> raise errors . RoleAlreadyExists , "<STR_LIT>" % role <EOL> self . _checkDuplicates ( cu , role ) <EOL> self . db . commit ( ) <EOL> return ugid <EOL> def renameRole ( self , oldRole , newRole ) : <EOL> cu = self . db . cursor ( ) <EOL> if oldRole == newRole : <EOL> return True <EOL> try : <EOL> cu . execute ( "<STR_LIT>" , <EOL> ( newRole , oldRole ) ) <EOL> except sqlerrors . ColumnNotUnique : <EOL> self . db . rollback ( ) <EOL> raise errors . RoleAlreadyExists ( "<STR_LIT>" % newRole ) <EOL> self . _checkDuplicates ( cu , newRole ) <EOL> self . db . commit ( ) <EOL> return True <EOL> def updateRoleMembers ( self , role , members ) : <EOL> cu = self . db . cursor ( ) <EOL> roleId = self . _getRoleIdByName ( role ) <EOL> cu . execute ( "<STR_LIT>" , roleId ) <EOL> for userName in members : <EOL> self . addRoleMember ( role , userName , commit = False ) <EOL> self . db . commit ( ) <EOL> def addRoleMember ( self , role , userName , commit = True ) : <EOL> cu = self . db . cursor ( ) <EOL> roleId = self . _getRoleIdByName ( role ) <EOL> userId = self . userAuth . getUserIdByName ( userName ) <EOL> cu . execute ( """<STR_LIT>""" , roleId , userId ) <EOL> if commit : <EOL> self . db . commit ( ) <EOL> def deleteRole ( self , role , commit = True ) : <EOL> self . deleteRoleById ( self . _getRoleIdByName ( role ) , commit ) <EOL> def deleteRoleById ( self , roleId , commit = True ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> roleId ) <EOL> cu . execute ( "<STR_LIT>" , roleId ) <EOL> cu . execute ( "<STR_LIT>" , roleId ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> roleId ) <EOL> cu . execute ( "<STR_LIT>" , roleId ) <EOL> cu . execute ( "<STR_LIT>" , roleId ) <EOL> cu . execute ( "<STR_LIT>" , roleId ) <EOL> if commit : <EOL> self . db . commit ( ) <EOL> def getItemList ( self ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" ) <EOL> return [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> def getLabelList ( self ) : <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( "<STR_LIT>" ) <EOL> return [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> def __checkEntitlementOwner ( self , cu , roleIds , entClass ) : <EOL> """<STR_LIT>""" <EOL> if not roleIds : <EOL> raise errors . InsufficientPermission <EOL> cu . execute ( """<STR_LIT>""" % "<STR_LIT:U+002C>" . join ( str ( x ) for x in roleIds ) , entClass ) <EOL> entClassIdList = [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> if entClassIdList : <EOL> assert ( max ( entClassIdList ) == min ( entClassIdList ) ) <EOL> return entClassIdList [ <NUM_LIT:0> ] <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" % "<STR_LIT:U+002C>" . join ( [ str ( x ) for x in roleIds ] ) ) <EOL> if not len ( cu . fetchall ( ) ) : <EOL> raise errors . InsufficientPermission <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , entClass ) <EOL> entClassIds = [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> if len ( entClassIds ) == <NUM_LIT:1> : <EOL> entClassId = entClassIds [ <NUM_LIT:0> ] <EOL> else : <EOL> assert ( not entClassIds ) <EOL> entClassId = - <NUM_LIT:1> <EOL> return entClassId <EOL> def deleteEntitlementClass ( self , authToken , entClass ) : <EOL> cu = self . db . cursor ( ) <EOL> if not self . authCheck ( authToken , admin = True ) : <EOL> raise errors . InsufficientPermission <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , entClass ) <EOL> ret = cu . fetchall ( ) <EOL> if not len ( ret ) : <EOL> raise errors . UnknownEntitlementClass <EOL> entClassId = ret [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> cu . execute ( "<STR_LIT>" , <EOL> entClassId ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> entClassId ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> entClassId ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> entClassId ) <EOL> self . db . commit ( ) <EOL> def addEntitlementKey ( self , authToken , entClass , entKey ) : <EOL> cu = self . db . cursor ( ) <EOL> roleIds = self . getAuthRoles ( cu , authToken ) <EOL> self . log ( <NUM_LIT:2> , "<STR_LIT>" % ( entClass , entKey ) ) <EOL> if len ( entKey ) > MAX_ENTITLEMENT_LENGTH : <EOL> raise errors . InvalidEntitlement <EOL> entClassId = self . __checkEntitlementOwner ( cu , roleIds , entClass ) <EOL> if entClassId == - <NUM_LIT:1> : <EOL> raise errors . UnknownEntitlementClass <EOL> cu . execute ( "<STR_LIT>" , <EOL> ( entClassId , entKey ) ) <EOL> if len ( cu . fetchall ( ) ) : <EOL> raise errors . EntitlementKeyAlreadyExists <EOL> cu . execute ( "<STR_LIT>" , <EOL> ( entClassId , entKey ) ) <EOL> self . db . commit ( ) <EOL> def deleteEntitlementKey ( self , authToken , entClass , entKey ) : <EOL> cu = self . db . cursor ( ) <EOL> roleIds = self . getAuthRoles ( cu , authToken ) <EOL> self . log ( <NUM_LIT:2> , "<STR_LIT>" % ( entClass , entKey ) ) <EOL> if len ( entKey ) > MAX_ENTITLEMENT_LENGTH : <EOL> raise errors . InvalidEntitlement <EOL> entClassId = self . __checkEntitlementOwner ( cu , roleIds , entClass ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> ( entClassId , entKey ) ) <EOL> if not len ( cu . fetchall ( ) ) : <EOL> raise errors . InvalidEntitlement <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , ( entClassId , entKey ) ) <EOL> self . db . commit ( ) <EOL> def addEntitlementClass ( self , authToken , entClass , role ) : <EOL> """<STR_LIT>""" <EOL> cu = self . db . cursor ( ) <EOL> if not self . authCheck ( authToken , admin = True ) : <EOL> raise errors . InsufficientPermission <EOL> self . log ( <NUM_LIT:2> , "<STR_LIT>" % ( entClass , role ) ) <EOL> cu . execute ( "<STR_LIT>" , <EOL> entClass ) <EOL> if len ( cu . fetchall ( ) ) : <EOL> raise errors . EntitlementClassAlreadyExists <EOL> roleId = self . _getRoleIdByName ( role ) <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , entClass ) <EOL> entClassId = cu . lastrowid <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , entClassId , roleId ) <EOL> self . db . commit ( ) <EOL> def getEntitlementClassOwner ( self , authToken , entClass ) : <EOL> """<STR_LIT>""" <EOL> if not self . authCheck ( authToken , admin = True ) : <EOL> raise errors . InsufficientPermission <EOL> cu = self . db . cursor ( ) <EOL> cu . execute ( """<STR_LIT>""" , entClass ) <EOL> ret = cu . fetchall ( ) <EOL> if len ( ret ) : <EOL> return ret [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> return None <EOL> def _getIds ( self , cu , entClass , role ) : <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , entClass ) <EOL> ent = cu . fetchall ( ) <EOL> if not len ( ent ) : <EOL> raise errors . UnknownEntitlementClass <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , role ) <EOL> user = cu . fetchall ( ) <EOL> if not len ( user ) : <EOL> raise errors . RoleNotFound <EOL> return ent [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , user [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] <EOL> def addEntitlementClassOwner ( self , authToken , role , entClass ) : <EOL> """<STR_LIT>""" <EOL> if not self . authCheck ( authToken , admin = True ) : <EOL> raise errors . InsufficientPermission <EOL> self . log ( <NUM_LIT:2> , "<STR_LIT>" % ( role , entClass ) ) <EOL> cu = self . db . cursor ( ) <EOL> entClassId , roleId = self . _getIds ( cu , entClass , role ) <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , <EOL> ( entClassId , roleId ) ) <EOL> self . db . commit ( ) <EOL> def deleteEntitlementClassOwner ( self , authToken , role , entClass ) : <EOL> if not self . authCheck ( authToken , admin = True ) : <EOL> raise errors . InsufficientPermission <EOL> self . log ( <NUM_LIT:2> , "<STR_LIT>" % ( role , entClass ) ) <EOL> cu = self . db . cursor ( ) <EOL> entClassId , roleId = self . _getIds ( cu , entClass , role ) <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , <EOL> entClassId , roleId ) <EOL> self . db . commit ( ) <EOL> def iterEntitlementKeys ( self , authToken , entClass ) : <EOL> cu = self . db . cursor ( ) <EOL> roleIds = self . getAuthRoles ( cu , authToken ) <EOL> entClassId = self . __checkEntitlementOwner ( cu , roleIds , entClass ) <EOL> cu . execute ( "<STR_LIT>" <EOL> "<STR_LIT>" , entClassId ) <EOL> return [ cu . frombinary ( x [ <NUM_LIT:0> ] ) for x in cu ] <EOL> def listEntitlementClasses ( self , authToken ) : <EOL> cu = self . db . cursor ( ) <EOL> if self . authCheck ( authToken , admin = True ) : <EOL> cu . execute ( "<STR_LIT>" ) <EOL> else : <EOL> roleIds = self . getAuthRoles ( cu , authToken ) <EOL> if not roleIds : <EOL> return [ ] <EOL> cu . execute ( """<STR_LIT>""" % <EOL> "<STR_LIT:U+002C>" . join ( [ "<STR_LIT>" % x for x in roleIds ] ) ) <EOL> return [ x [ <NUM_LIT:0> ] for x in cu ] <EOL> def getEntitlementClassesRoles ( self , authToken , classList ) : <EOL> if not self . authCheck ( authToken , admin = True ) : <EOL> raise errors . InsufficientPermission <EOL> cu = self . db . cursor ( ) <EOL> placeholders = '<STR_LIT:U+002C>' . join ( [ '<STR_LIT:?>' for x in classList ] ) <EOL> names = classList <EOL> cu . execute ( """<STR_LIT>""" <EOL> % ( placeholders , ) , names ) <EOL> d = { } <EOL> for entClass , role in cu : <EOL> l = d . setdefault ( entClass , [ ] ) <EOL> if role is not None : <EOL> l . append ( role ) <EOL> if len ( d ) != len ( classList ) : <EOL> raise errors . RoleNotFound <EOL> return d <EOL> def setEntitlementClassesRoles ( self , authToken , classInfo ) : <EOL> """<STR_LIT>""" <EOL> if not self . authCheck ( authToken , admin = True ) : <EOL> raise errors . InsufficientPermission <EOL> cu = self . db . cursor ( ) <EOL> placeholders = '<STR_LIT:U+002C>' . join ( [ '<STR_LIT:?>' for x in classInfo ] ) <EOL> names = classInfo . keys ( ) <EOL> cu . execute ( """<STR_LIT>""" % <EOL> ( placeholders , ) , names ) <EOL> entClassMap = dict ( cu ) <EOL> if len ( entClassMap ) != len ( classInfo ) : <EOL> raise errors . RoleNotFound <EOL> rolesNeeded = list ( set ( itertools . chain ( * classInfo . itervalues ( ) ) ) ) <EOL> if rolesNeeded : <EOL> placeholders = '<STR_LIT:U+002C>' . join ( [ '<STR_LIT:?>' for x in rolesNeeded ] ) <EOL> cu . execute ( """<STR_LIT>""" % <EOL> ( placeholders , ) , rolesNeeded ) <EOL> roleMap = dict ( cu ) <EOL> else : <EOL> roleMap = { } <EOL> if len ( roleMap ) != len ( rolesNeeded ) : <EOL> raise errors . RoleNotFound <EOL> entClassIds = '<STR_LIT:U+002C>' . join ( [ '<STR_LIT>' % x for x in entClassMap . itervalues ( ) ] ) <EOL> cu . execute ( """<STR_LIT>""" % <EOL> ( entClassIds , ) ) <EOL> for entClass , roles in classInfo . iteritems ( ) : <EOL> for role in roles : <EOL> cu . execute ( """<STR_LIT>""" , <EOL> entClassMap [ entClass ] , roleMap [ role ] ) <EOL> self . db . commit ( ) <EOL> def getRoleFilters ( self , roles ) : <EOL> cu = self . db . cursor ( ) <EOL> placeholders = '<STR_LIT:U+002C>' . join ( '<STR_LIT:?>' for x in roles ) <EOL> query = ( """<STR_LIT>""" % placeholders ) <EOL> cu . execute ( query , list ( roles ) ) <EOL> return dict ( ( x [ <NUM_LIT:0> ] , ( deps . ThawFlavor ( x [ <NUM_LIT:1> ] ) , deps . ThawFlavor ( x [ <NUM_LIT:2> ] ) ) ) <EOL> for x in cu ) <EOL> def setRoleFilters ( self , roleFiltersMap ) : <EOL> cu = self . db . cursor ( ) <EOL> for role , flags in roleFiltersMap . iteritems ( ) : <EOL> args = [ ] <EOL> for flag in flags : <EOL> if flag is not None : <EOL> flag = flag . freeze ( ) <EOL> if flag == '<STR_LIT>' : <EOL> flag = None <EOL> args . append ( flag ) <EOL> args . append ( role ) <EOL> cu . execute ( """<STR_LIT>""" , args ) <EOL> self . db . commit ( ) <EOL> class PasswordCheckParser ( dict ) : <EOL> def StartElementHandler ( self , name , attrs ) : <EOL> if name not in [ '<STR_LIT>' ] : <EOL> raise SyntaxError <EOL> val = attrs . get ( '<STR_LIT>' , None ) <EOL> self . valid = ( val == '<STR_LIT:1>' or str ( val ) . lower ( ) == '<STR_LIT:true>' ) <EOL> def EndElementHandler ( self , name ) : <EOL> pass <EOL> def CharacterDataHandler ( self , data ) : <EOL> if data . strip ( ) : <EOL> self . valid = False <EOL> def parse ( self , s ) : <EOL> return self . p . Parse ( s ) <EOL> def validPassword ( self ) : <EOL> return self . valid <EOL> def __init__ ( self ) : <EOL> self . p = xml . parsers . expat . ParserCreate ( ) <EOL> self . p . StartElementHandler = self . StartElementHandler <EOL> self . p . EndElementHandler = self . EndElementHandler <EOL> self . p . CharacterDataHandler = self . CharacterDataHandler <EOL> self . valid = False <EOL> dict . __init__ ( self ) </s>
