Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://twistedmatrix.com/documents/current/core/examples/dbcred.py
- class DBCredentialsChecker(object):
- implements(ICredentialsChecker)
- baseLogger = None
- def __init__(self, runQuery,
- query="""
- CALL checkLogin(%s);
- """, customCheckFunc=None, caseSensitivePasswords=True):
- """@param runQuery: This will be called to get the info from the db.
- Generally, you'd want to create a L{twisted.enterprise.abdapi.ConnectionPool}
- and pass its runQuery method here. Otherwise pass a function with the same prototype.
- @type runQuery: C{callable}
- @param query: query used to authenticate user.
- @type query: C{str}
- @param customCheckFunc: Use this if the passwords in the db are stored as hashed. We'll just call this, so you can do the checking yourself. It takes the following params: (username, suppliedPass, dbPass) and must return a boolean.
- @type customCheckFunc: C{callable}
- @param caseSensitivePasswords: If true requires that every letter in C{credentials.password} is exactly the same case as its counterpart character in the database. This is only relevant if C{customCheckFunc} is not used.
- @type caseSensitivePasswords: C{bool}
- """
- self.baseLogger = logging.getLogger('MB-Server.DBCredentialsChecker')
- logger = MBLogAdapter(self.baseLogger, {'file': 'main.py', 'object': 'DBCredentialsChecker', 'method': '__init__'})
- logger.debug('Starting method...')
- logger.debug('runQuery="%s" caseSensitivePasswords="%s" customCheckFunc="%s" query="%s"', str(runQuery), str(caseSensitivePasswords), str(customCheckFunc), str(query))
- self.runQuery = runQuery
- self.caseSensitivePasswords = caseSensitivePasswords
- self.customCheckFunc = customCheckFunc
- # We can't support hashed password credentials if we only have a hash in the DB
- if customCheckFunc:
- self.credentialsInterfaces = (IUsernamePassword,)
- else:
- self.credentialInterfaces = (IUsernamePassword, IUsernameHashedPassword,)
- self.sql = query
- def requestAvatarId(self, credentials):
- """
- Authenticates the kiosk against the database.
- """
- logger = MBLogAdapter(self.baseLogger, {'file': 'main.py', 'object': 'DBCredentialsChecker', 'method': 'requestAvatarId'})
- logger.debug('Starting method...')
- logger.debug('credentials="%s"', str(credentials))
- # Check that the credentials instance implements at least one of our interfaces
- for interface in self.credentialInterfaces:
- if interface.providedBy(credentials):
- break
- else:
- raise credError.UnhandledCredentials()
- # Ask the database for the username and password
- dbDeferred = self.runQuery(self.sql, (credentials.username,))
- # Setup our deferred result
- deferred = Deferred()
- dbDeferred.addCallbacks(self._cbAuthenticate, self._ebAuthenticate,
- callbackArgs=(credentials, deferred),
- errbackArgs=(credentials, deferred))
- return deferred
- def _cbAuthenticate(self, result, credentials, deferred):
- """
- Checks to see if the authentication was good. Called once the info has been retrieved from the DB.
- """
- logger = MBLogAdapter(self.baseLogger, {'file': 'main.py', 'object': 'DBCredentialsChecker', 'method': '_cbAuthenticate'})
- logger.debug('Starting method...')
- logger.debug('result="%s" credentials="%s" deferred="%s"', str(result), str(credentials), str(deferred))
- if len(result) == 0:
- # Username not found in db
- deferred.errback(credError.UnauthorizedLogin('Username unknown'))
- else:
- username, password = result[0]
- if self.customCheckFunc:
- # Let the owner do the checking
- if self.customCheckFunc(
- username, credentials.password, password):
- deferred.callback(credentials.username)
- else:
- deferred.errback(credError.UnauthorizedLogin('Password mismatch'))
- else:
- # It's up to us or the credentials object to do the checking now
- if IUsernameHashedPassword.providedBy(credentials):
- # Let the hashed password checker do the checking
- if credentials.checkPassword(password):
- deferred.callback(credentials.username)
- else:
- deferred.errback(credError.UnauthorizedLogin('Password mismatch'))
- elif IUsernamePassword.providedBy(credentials):
- # Compare the passwords, deciding whether or not to use case sensitivity
- if self.caseSensiivePasswords:
- passOk = (password.lower() == credentials.password.lower())
- else:
- passOk = password == credentials.password
- # See if they match
- if passOk:
- deferred.callback(credentials.username)
- else:
- deferred.errback(credError.UnauthorizedLogin('Password mismatch'))
- else:
- # OK, we don't know how to check this
- deferred.errback(credError.UnhandledCredentials())
- def _ebAuthenticate(self, message, credentials, deferred):
- """
- The database lookup failed for some reason.
- """
- logger = MBLogAdapter(self.baseLogger, {'file': 'main.py', 'object': 'DBCredentialsChecker', 'method': '_ebAuthenticate'})
- logger.debug('Starting method...')
- logger.debug('message="%s" credentials="%s" deferred="%s"', str(message), str(credentials), str(deferred))
- deferred.errback(credError.LoginFailed(message))
Advertisement
Add Comment
Please, Sign In to add comment