1 import binascii, hashlib, threading, time
4 class unauthorized(resp.httperror):
5 def __init__(self, challenge, message=None, detail=None):
6 super().__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().handle(req)
16 class forbidden(resp.httperror):
17 def __init__(self, message=None, detail=None):
18 super().__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 data = data.encode("us-ascii")
38 raw = binascii.a2b_base64(data)
39 except binascii.Error:
42 raw = raw.decode("utf-8")
44 raw = raw.decode("latin1")
48 return raw[:p], raw[p + 1:]
50 class basiccache(object):
53 def __init__(self, realm, authfn=None):
54 self._lock = threading.Lock()
57 if authfn is not None:
60 def _obscure(self, nm, pw):
61 dig = hashlib.sha256()
62 dig.update(self.realm.encode("utf-8"))
63 dig.update(nm.encode("utf-8"))
64 dig.update(pw.encode("utf-8"))
68 nm, pw = parsebasic(req)
70 raise unauthorized("Basic Realm=\"%s\"" % self.realm)
71 pwh = self._obscure(nm, pw)
74 if (nm, pwh) in self._cache:
75 lock, atime, res, resob = self._cache[nm, pwh]
76 if now - atime < self.cachetime:
82 lock = threading.Lock()
83 self._cache[nm, pwh] = (lock, now, None, None)
86 ret = self.auth(req, nm, pw)
87 except forbidden as exc:
89 self._cache[nm, pwh] = (lock, now, "f", exc)
94 self._cache[nm, pwh] = (lock, now, "s", ret)
97 def auth(self, req, nm, pw):
98 raise Exception("authentication function neither supplied nor overridden")