Mercurial > hg > bitsyblog
comparison bitsyblog/auth_factory.py @ 62:4038c2a052da
add http-basic authenticator middleware filter
author | ejucovy@socialplanning |
---|---|
date | Tue, 19 Jan 2010 14:50:44 -0500 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
61:04866e5abb5a | 62:4038c2a052da |
---|---|
1 from webob import Request | |
2 | |
3 import os | |
4 | |
5 def getpw(basedir, user): | |
6 file = os.path.join(basedir, user, '.password') | |
7 | |
8 try: | |
9 fp = open(file) | |
10 except IOError: | |
11 return None | |
12 | |
13 pw = fp.read().strip() | |
14 fp.close() | |
15 return pw | |
16 | |
17 # from paste.auth.digest | |
18 try: | |
19 from hashlib import md5 | |
20 except ImportError: | |
21 from md5 import md5 | |
22 def hash(user, pw, realm): | |
23 return md5("%s:%s:%s" % (user, realm, pw)).hexdigest() | |
24 | |
25 class BitsyblogFilespaceAuth(object): | |
26 def __init__(self, realm, basedir): | |
27 self.realm = realm | |
28 self.basedir = basedir | |
29 def __call__(self, user, pw): | |
30 stored = getpw(self.basedir, user) | |
31 if stored is None: | |
32 return False | |
33 return hash(user, pw, self.realm) == stored | |
34 | |
35 def filter_factory(global_conf, realm=None, basedir=None): | |
36 #from paste.util.import_string import eval_import | |
37 #authfunc = eval_import(authfunc) | |
38 | |
39 authfunc = BitsyblogFilespaceAuth(realm, basedir) | |
40 | |
41 def filter(app): | |
42 return BasicAuthMiddleware(app, realm, authfunc) | |
43 return filter | |
44 | |
45 class BasicAuthMiddleware(object): | |
46 def __init__(self, app, realm, auth_checker): | |
47 self.app = app | |
48 self.realm = realm | |
49 self.auth_checker = auth_checker | |
50 | |
51 def __call__(self, environ, start_response): | |
52 req = Request(environ) | |
53 | |
54 header = req.authorization | |
55 if not header: | |
56 return self.app(environ, start_response) | |
57 | |
58 (method, auth) = header.split(' ', 1) | |
59 if method.lower() != 'basic': | |
60 return self.app(environ, start_response) | |
61 | |
62 auth = auth.strip().decode('base64') | |
63 | |
64 username, password = auth.split(':', 1) | |
65 | |
66 if self.auth_checker(username, password): | |
67 environ['REMOTE_USER'] = username | |
68 | |
69 return self.app(environ, start_response) |