| 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 |
|
|---|
| 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() |
|---|
| 18 |
|
|---|
| 19 |
if not isinstance(users, dict): |
|---|
| 20 |
raise ValueError, "Authentication users must be a dictionary" |
|---|
| 21 |
|
|---|
| 22 |
|
|---|
| 23 |
password = users.get(ah["username"], None) |
|---|
| 24 |
|
|---|
| 25 |
|
|---|
| 26 |
|
|---|
| 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 |
|
|---|
| 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 |
|
|---|
| 59 |
cherrypy.response.headers['www-authenticate'] = httpauth.digestAuth(realm) |
|---|
| 60 |
|
|---|
| 61 |
raise cherrypy.HTTPError(401, "You are not authorized to access that resource") |
|---|
| 62 |
|
|---|