TheBeege

DBCredentialsChecker

Feb 1st, 2014
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.40 KB | None | 0 0
  1. # http://twistedmatrix.com/documents/current/core/examples/dbcred.py
  2. class DBCredentialsChecker(object):
  3.   implements(ICredentialsChecker)
  4.  
  5.   baseLogger = None
  6.  
  7.   def __init__(self, runQuery,
  8.       query="""
  9.      CALL checkLogin(%s);
  10.      """, customCheckFunc=None, caseSensitivePasswords=True):
  11.     """@param runQuery: This will be called to get the info from the db.
  12.       Generally, you'd want to create a L{twisted.enterprise.abdapi.ConnectionPool}
  13.       and pass its runQuery method here. Otherwise pass a function with the same prototype.
  14.       @type runQuery: C{callable}
  15.  
  16.       @param query: query used to authenticate user.
  17.       @type query: C{str}
  18.  
  19.       @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.
  20.       @type customCheckFunc: C{callable}
  21.  
  22.       @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.
  23.       @type caseSensitivePasswords: C{bool}
  24.    """
  25.  
  26.     self.baseLogger = logging.getLogger('MB-Server.DBCredentialsChecker')
  27.     logger = MBLogAdapter(self.baseLogger, {'file': 'main.py', 'object': 'DBCredentialsChecker', 'method': '__init__'})
  28.     logger.debug('Starting method...')
  29.     logger.debug('runQuery="%s" caseSensitivePasswords="%s" customCheckFunc="%s" query="%s"', str(runQuery), str(caseSensitivePasswords), str(customCheckFunc), str(query))
  30.  
  31.     self.runQuery = runQuery
  32.     self.caseSensitivePasswords = caseSensitivePasswords
  33.     self.customCheckFunc = customCheckFunc
  34.     # We can't support hashed password credentials if we only have a hash in the DB
  35.     if customCheckFunc:
  36.       self.credentialsInterfaces = (IUsernamePassword,)
  37.     else:
  38.       self.credentialInterfaces = (IUsernamePassword, IUsernameHashedPassword,)
  39.  
  40.     self.sql = query
  41.  
  42.   def requestAvatarId(self, credentials):
  43.     """
  44.    Authenticates the kiosk against the database.
  45.    """
  46.     logger = MBLogAdapter(self.baseLogger, {'file': 'main.py', 'object': 'DBCredentialsChecker', 'method': 'requestAvatarId'})
  47.     logger.debug('Starting method...')
  48.     logger.debug('credentials="%s"', str(credentials))
  49.     # Check that the credentials instance implements at least one of our interfaces
  50.     for interface in self.credentialInterfaces:
  51.       if interface.providedBy(credentials):
  52.         break
  53.       else:
  54.         raise credError.UnhandledCredentials()
  55.  
  56.     # Ask the database for the username and password
  57.     dbDeferred = self.runQuery(self.sql, (credentials.username,))
  58.     # Setup our deferred result
  59.     deferred = Deferred()
  60.     dbDeferred.addCallbacks(self._cbAuthenticate, self._ebAuthenticate,
  61.       callbackArgs=(credentials, deferred),
  62.       errbackArgs=(credentials, deferred))
  63.     return deferred
  64.  
  65.   def _cbAuthenticate(self, result, credentials, deferred):
  66.     """
  67.    Checks to see if the authentication was good. Called once the info has been retrieved from the DB.
  68.    """
  69.  
  70.     logger = MBLogAdapter(self.baseLogger, {'file': 'main.py', 'object': 'DBCredentialsChecker', 'method': '_cbAuthenticate'})
  71.     logger.debug('Starting method...')
  72.     logger.debug('result="%s" credentials="%s" deferred="%s"', str(result), str(credentials), str(deferred))
  73.     if len(result) == 0:
  74.       # Username not found in db
  75.       deferred.errback(credError.UnauthorizedLogin('Username unknown'))
  76.     else:
  77.       username, password = result[0]
  78.       if self.customCheckFunc:
  79.         # Let the owner do the checking
  80.         if self.customCheckFunc(
  81.             username, credentials.password, password):
  82.           deferred.callback(credentials.username)
  83.         else:
  84.           deferred.errback(credError.UnauthorizedLogin('Password mismatch'))
  85.       else:
  86.         # It's up to us or the credentials object to do the checking now
  87.         if IUsernameHashedPassword.providedBy(credentials):
  88.           # Let the hashed password checker do the checking
  89.           if credentials.checkPassword(password):
  90.             deferred.callback(credentials.username)
  91.           else:
  92.             deferred.errback(credError.UnauthorizedLogin('Password mismatch'))
  93.         elif IUsernamePassword.providedBy(credentials):
  94.           # Compare the passwords, deciding whether or not to use case sensitivity
  95.           if self.caseSensiivePasswords:
  96.             passOk = (password.lower() == credentials.password.lower())
  97.           else:
  98.             passOk = password == credentials.password
  99.  
  100.           # See if they match
  101.           if passOk:
  102.             deferred.callback(credentials.username)
  103.           else:
  104.             deferred.errback(credError.UnauthorizedLogin('Password mismatch'))
  105.         else:
  106.           # OK, we don't know how to check this
  107.           deferred.errback(credError.UnhandledCredentials())
  108.  
  109.   def _ebAuthenticate(self, message, credentials, deferred):
  110.     """
  111.    The database lookup failed for some reason.
  112.    """
  113.     logger = MBLogAdapter(self.baseLogger, {'file': 'main.py', 'object': 'DBCredentialsChecker', 'method': '_ebAuthenticate'})
  114.     logger.debug('Starting method...')
  115.     logger.debug('message="%s" credentials="%s" deferred="%s"', str(message), str(credentials), str(deferred))
  116.     deferred.errback(credError.LoginFailed(message))
Advertisement
Add Comment
Please, Sign In to add comment