Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

root/tags/cherrypy-3.0.0/cherrypy/lib/auth.py

Revision 1418 (checked in by fumanchu, 2 years ago)

Fix for #596 (svn:eol-style)

Line 
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             return True
30    
31     return False
32
33 def basic_auth(realm, users, encrypt=None):
34     """If auth fails, raise 401 with a basic authentication header.
35     
36     realm: a string containing the authentication realm.
37     users: a dict of the form: {username: password} or a callable returning a dict.
38     encrypt: callable used to encrypt the password returned from the user-agent.
39              if None it defaults to a md5 encryption.
40     """
41     if check_auth(users, encrypt):
42         return
43    
44     # inform the user-agent this path is protected
45     cherrypy.response.headers['www-authenticate'] = httpauth.basicAuth(realm)
46    
47     raise cherrypy.HTTPError(401, "You are not authorized to access that resource")
48
49 def digest_auth(realm, users):
50     """If auth fails, raise 401 with a digest authentication header.
51     
52     realm: a string containing the authentication realm.
53     users: a dict of the form: {username: password} or a callable returning a dict.
54     """
55     if check_auth(users):
56         return
57    
58     # inform the user-agent this path is protected
59     cherrypy.response.headers['www-authenticate'] = httpauth.digestAuth(realm)
60    
61     raise cherrypy.HTTPError(401, "You are not authorized to access that resource")
62  
Note: See TracBrowser for help on using the browser.

Hosted by WebFaction

Log in as guest/cpguest to create tickets