1 import cherrypy
2 from cherrypy.lib import httpauth
3
4
6 """If an authorization header contains credentials, return True or False.
7 """
8 request = cherrypy.serving.request
9 if 'authorization' in request.headers:
10
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
21 users = users()
22
23 if not isinstance(users, dict):
24 raise ValueError(
25 "Authentication users must be a dictionary")
26
27
28 password = users.get(ah["username"], None)
29 except TypeError:
30
31 password = users(ah["username"])
32 else:
33 if not isinstance(users, dict):
34 raise ValueError("Authentication users must be a dictionary")
35
36
37 password = users.get(ah["username"], None)
38
39
40
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
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
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
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