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