Chris McDonough
2008-03-19 cb5426e52796bec668aa09148fe094fe266b04c0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from zope.interface import implements
 
from repoze.who.interfaces import IAuthenticator
from repoze.who.utils import resolveDotted
 
class HTPasswdPlugin(object):
 
    implements(IAuthenticator)
 
    def __init__(self, filename, check):
        self.filename = filename
        self.check = check
 
    # IAuthenticatorPlugin
    def authenticate(self, environ, identity):
        try:
            login = identity['login']
            password = identity['password']
        except KeyError:
            return None
 
        if hasattr(self.filename, 'seek'):
            # assumed to have a readline
            self.filename.seek(0)
            f = self.filename
        else:
            try:
                f = open(self.filename, 'r')
            except IOError:
                return None
 
        for line in f:
            try:
                username, hashed = line.rstrip().split(':', 1)
            except ValueError:
                continue
            if username == login:
                if self.check(password, hashed):
                    return username
        return None
 
    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, id(self))
 
def crypt_check(password, hashed):
    from crypt import crypt
    salt = hashed[:2]
    return hashed == crypt(password, salt)
 
def make_plugin(who_conf, filename=None, check_fn=None):
    if filename is None:
        raise ValueError('filename must be specified')
    if check_fn is None:
        raise ValueError('check_fn must be specified')
    check = resolveDotted(check_fn)
    return HTPasswdPlugin(filename, check)