1 import binascii, hashlib, threading, time
4 class unauthorized(resp.httperror):
5 def __init__(self, challenge, message=None, detail=None):
6 super(unauthorized, self).__init__(401, message, detail)
7 if isinstance(challenge, str):
8 challenge = [challenge]
9 self.challenge = challenge
11 def handle(self, req):
12 for challenge in self.challenge:
13 req.ohead.add("WWW-Authenticate", challenge)
14 return super(unauthorized, self).handle(req)
16 class forbidden(resp.httperror):
17 def __init__(self, message=None, detail=None):
18 super(forbidden, self).__init__(403, message, detail)
21 h = req.ihead.get("Authorization", None)
27 return h[:p].strip().lower(), h[p + 1:].strip()
30 mech, data = parsemech(req)
34 raw = binascii.a2b_base64(data)
35 except binascii.Error:
40 return raw[:p], raw[p + 1:]
42 class basiccache(object):
45 def __init__(self, realm, authfn=None):
46 self._lock = threading.Lock()
49 if authfn is not None:
52 def _obscure(self, nm, pw):
53 dig = hashlib.sha256()
54 dig.update(self.realm)
60 nm, pw = parsebasic(req)
62 raise unauthorized("Basic Realm=\"%s\"" % self.realm)
63 pwh = self._obscure(nm, pw)
66 if (nm, pwh) in self._cache:
67 lock, atime, res, resob = self._cache[nm, pwh]
68 if now - atime < self.cachetime:
74 lock = threading.Lock()
75 self._cache[nm, pwh] = (lock, now, None, None)
78 ret = self.auth(req, nm, pw)
79 except forbidden, exc:
81 self._cache[nm, pwh] = (lock, now, "f", exc)
86 self._cache[nm, pwh] = (lock, now, "s", ret)
89 def auth(self, req, nm, pw):
90 raise Exception("authentication function neither supplied nor overridden")