"""Parse the ``Authorization`` header."""
__docformat__ = "restructuredtext"
# Created: Wed Jul 20 10:56:16 PDT 2005
# Author: Shannon -jj Behrens, David Veach
# Email: jjinux@users.sourceforge.net
#
# Copyright (c) Shannon -jj Behrens, David Veach. All rights reserved.
import base64
from crypt import crypt
import re
def isHTTPAuthenticated(header, getPasswordCallback):
"""Is a user HTTP authenticated?
header
This is the value of the ``Authorization`` header or None (e.g.
``ctx.wsa.getCgiEnv().get("HTTP_AUTHORIZATION")``).
getPasswordCallback
This is a callback that takes a username and returns the encrypted
password for that username. You may raise a KeyError if that user
doesn't exist.
Note, only ``basic`` authentication is supported at this time.
If a user isn't HTTP authenticated, you'll probably want to do something
like::
ctx.iLib.forward("not_authorized",
auth='BASIC realm="My Web Site"')
If they are not authenticated, return False. Otherwise, return a tuple of
``(username, password)``.
"""
if not header:
return False
try:
match = re.match(r"^s*basic\s+(.*)$", header, re.I)
credentials = base64.decodestring(match.group(1))
(username, password) = credentials.split(':', 1)
enc_password = getPasswordCallback(username)
if crypt(password, enc_password) != enc_password:
raise ValueError
return (username, password)
except (KeyError, AttributeError, ValueError):
return False
|