source file: /Library/Python/2.3/site-packages/CherryPy-3.0.1-py2.3.egg/cherrypy/lib/auth.py
file stats: 29 lines, 5 executed: 17.2% covered
   1. import cherrypy
   2. from cherrypy.lib import httpauth
   3. 
   4. 
   5. def check_auth(users, encrypt=None):
   6.     """If an authorization header contains credentials, return True, else False."""
   7.     if 'authorization' in cherrypy.request.headers:
   8.         # make sure the provided credentials are correctly set
   9.         ah = httpauth.parseAuthorization(cherrypy.request.headers['authorization'])
  10.         if ah is None:
  11.             raise cherrypy.HTTPError(400, 'Bad Request')
  12. 
  13.         if not encrypt:
  14.             encrypt = httpauth.DIGEST_AUTH_ENCODERS[httpauth.MD5]
  15. 
  16.         if callable(users):
  17.             users = users() # expect it to return a dictionary
  18. 
  19.         if not isinstance(users, dict):
  20.             raise ValueError, "Authentication users must be a dictionary"
  21. 
  22.         # fetch the user password
  23.         password = users.get(ah["username"], None)
  24. 
  25.         # validate the authorization by re-computing it here
  26.         # and compare it with what the user-agent provided
  27.         if httpauth.checkResponse(ah, password, method=cherrypy.request.method,
  28.                                   encrypt=encrypt):
  29.             cherrypy.request.login = ah["username"]
  30.             return True
  31. 
  32.         cherrypy.request.login = False
  33.     return False
  34. 
  35. def basic_auth(realm, users, encrypt=None):
  36.     """If auth fails, raise 401 with a basic authentication header.
  37. 
  38.     realm: a string containing the authentication realm.
  39.     users: a dict of the form: {username: password} or a callable returning a dict.
  40.     encrypt: callable used to encrypt the password returned from the user-agent.
  41.              if None it defaults to a md5 encryption.
  42.     """
  43.     if check_auth(users, encrypt):
  44.         return
  45. 
  46.     # inform the user-agent this path is protected
  47.     cherrypy.response.headers['www-authenticate'] = httpauth.basicAuth(realm)
  48. 
  49.     raise cherrypy.HTTPError(401, "You are not authorized to access that resource")
  50. 
  51. def digest_auth(realm, users):
  52.     """If auth fails, raise 401 with a digest authentication header.
  53. 
  54.     realm: a string containing the authentication realm.
  55.     users: a dict of the form: {username: password} or a callable returning a dict.
  56.     """
  57.     if check_auth(users):
  58.         return
  59. 
  60.     # inform the user-agent this path is protected
  61.     cherrypy.response.headers['www-authenticate'] = httpauth.digestAuth(realm)
  62. 
  63.     raise cherrypy.HTTPError(401, "You are not authorized to access that resource")
  64.