Package cherrypy :: Package lib :: Module auth
[hide private]
[frames] | no frames]

Source Code for Module cherrypy.lib.auth

 1  import cherrypy 
 2  from cherrypy.lib import httpauth 
 3   
 4   
5 -def check_auth(users, encrypt=None, realm=None):
6 """If an authorization header contains credentials, return True or False. 7 """ 8 request = cherrypy.serving.request 9 if 'authorization' in request.headers: 10 # make sure the provided credentials are correctly set 11 ah = httpauth.parseAuthorization(request.headers['authorization']) 12 if ah is None: 13 raise cherrypy.HTTPError(400, 'Bad Request') 14 15 if not encrypt: 16 encrypt = httpauth.DIGEST_AUTH_ENCODERS[httpauth.MD5] 17 18 if hasattr(users, '__call__'): 19 try: 20 # backward compatibility 21 users = users() # expect it to return a dictionary 22 23 if not isinstance(users, dict): 24 raise ValueError( 25 "Authentication users must be a dictionary") 26 27 # fetch the user password 28 password = users.get(ah["username"], None) 29 except TypeError: 30 # returns a password (encrypted or clear text) 31 password = users(ah["username"]) 32 else: 33 if not isinstance(users, dict): 34 raise ValueError("Authentication users must be a dictionary") 35 36 # fetch the user password 37 password = users.get(ah["username"], None) 38 39 # validate the authorization by re-computing it here 40 # and compare it with what the user-agent provided 41 if httpauth.checkResponse(ah, password, method=request.method, 42 encrypt=encrypt, realm=realm): 43 request.login = ah["username"] 44 return True 45 46 request.login = False 47 return False
48 49
50 -def basic_auth(realm, users, encrypt=None, debug=False):
51 """If auth fails, raise 401 with a basic authentication header. 52 53 realm 54 A string containing the authentication realm. 55 56 users 57 A dict of the form: {username: password} or a callable returning 58 a dict. 59 60 encrypt 61 callable used to encrypt the password returned from the user-agent. 62 if None it defaults to a md5 encryption. 63 64 """ 65 if check_auth(users, encrypt): 66 if debug: 67 cherrypy.log('Auth successful', 'TOOLS.BASIC_AUTH') 68 return 69 70 # inform the user-agent this path is protected 71 cherrypy.serving.response.headers[ 72 'www-authenticate'] = httpauth.basicAuth(realm) 73 74 raise cherrypy.HTTPError( 75 401, "You are not authorized to access that resource")
76 77
78 -def digest_auth(realm, users, debug=False):
79 """If auth fails, raise 401 with a digest authentication header. 80 81 realm 82 A string containing the authentication realm. 83 users 84 A dict of the form: {username: password} or a callable returning 85 a dict. 86 """ 87 if check_auth(users, realm=realm): 88 if debug: 89 cherrypy.log('Auth successful', 'TOOLS.DIGEST_AUTH') 90 return 91 92 # inform the user-agent this path is protected 93 cherrypy.serving.response.headers[ 94 'www-authenticate'] = httpauth.digestAuth(realm) 95 96 raise cherrypy.HTTPError( 97 401, "You are not authorized to access that resource")
98