Tres Seaver
2012-03-18 330d9573ecb2430127fa67d0f5f8602b6f30869f
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
59
60
61
62
63
64
65
66
67
68
69
70
71
import binascii
 
from webob.exc import HTTPUnauthorized
from zope.interface import implementer
 
from repoze.who.interfaces import IIdentifier
from repoze.who.interfaces import IChallenger
from repoze.who._compat import AUTHORIZATION
from repoze.who._compat import decodebytes
from repoze.who._compat import must_decode
 
@implementer(IIdentifier, IChallenger)
class BasicAuthPlugin(object):
 
    def __init__(self, realm):
        self.realm = realm
 
    # IIdentifier
    def identify(self, environ):
        authorization = AUTHORIZATION(environ)
        if type(authorization) != type(b''):
            # this header *must* be base64-encoded ASCII
            authorization = authorization.encode('ascii')
        try:
            authmeth, auth = authorization.split(b' ', 1)
        except ValueError: # not enough values to unpack
            return None
        if authmeth.lower() == b'basic':
            try:
                auth = auth.strip()
                auth = decodebytes(auth)
            except binascii.Error: # can't decode
                return None
            try:
                login, password = auth.split(b':', 1)
            except ValueError: # not enough values to unpack
                return None
            auth = {'login': must_decode(login),
                    'password': must_decode(password)}
            return auth
 
        return None
 
    # IIdentifier
    def remember(self, environ, identity):
        # we need to do nothing here; the browser remembers the basic
        # auth info as a result of the user typing it in.
        pass
 
    def _get_wwwauth(self):
        head = [('WWW-Authenticate', 'Basic realm="%s"' % self.realm)]
        return head
 
    # IIdentifier
    def forget(self, environ, identity):
        return self._get_wwwauth()
 
    # IChallenger
    def challenge(self, environ, status, app_headers, forget_headers):
        head = self._get_wwwauth()
        if head[0] not in forget_headers:
            head = head + forget_headers
        return HTTPUnauthorized(headers=head)
 
    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__,
                            id(self)) #pragma NO COVERAGE
 
def make_plugin(realm='basic'):
    plugin = BasicAuthPlugin(realm)
    return plugin