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'])
12 raise cherrypy
.HTTPError(400, 'Bad Request')
15 encrypt
= httpauth
.DIGEST_AUTH_ENCODERS
[httpauth
.MD5
]
17 if hasattr(users
, '__call__'):
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)
28 # returns a password (encrypted or clear text)
29 password
= users(ah
["username"])
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"]
47 def basic_auth(realm
, users
, encrypt
=None, debug
=False):
48 """If auth fails, raise 401 with a basic authentication header.
51 A string containing the authentication realm.
54 A dict of the form: {username: password} or a callable returning a dict.
57 callable used to encrypt the password returned from the user-agent.
58 if None it defaults to a md5 encryption.
61 if check_auth(users
, encrypt
):
63 cherrypy
.log('Auth successful', 'TOOLS.BASIC_AUTH')
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.
75 A string containing the authentication realm.
77 A dict of the form: {username: password} or a callable returning a dict.
79 if check_auth(users
, realm
=realm
):
81 cherrypy
.log('Auth successful', 'TOOLS.DIGEST_AUTH')
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")