aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/web/_auth/basic.py
blob: 8b588fb47e141571910ccfe829d9f0a88c99a0e9 (plain)
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
# -*- test-case-name: twisted.web.test.test_httpauth -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
HTTP BASIC authentication.

@see: U{http://tools.ietf.org/html/rfc1945}
@see: U{http://tools.ietf.org/html/rfc2616}
@see: U{http://tools.ietf.org/html/rfc2617}
"""

import binascii

from zope.interface import implements

from twisted.cred import credentials, error
from twisted.web.iweb import ICredentialFactory


class BasicCredentialFactory(object):
    """
    Credential Factory for HTTP Basic Authentication

    @type authenticationRealm: C{str}
    @ivar authenticationRealm: The HTTP authentication realm which will be issued in
        challenges.
    """
    implements(ICredentialFactory)

    scheme = 'basic'

    def __init__(self, authenticationRealm):
        self.authenticationRealm = authenticationRealm


    def getChallenge(self, request):
        """
        Return a challenge including the HTTP authentication realm with which
        this factory was created.
        """
        return {'realm': self.authenticationRealm}


    def decode(self, response, request):
        """
        Parse the base64-encoded, colon-separated username and password into a
        L{credentials.UsernamePassword} instance.
        """
        try:
            creds = binascii.a2b_base64(response + '===')
        except binascii.Error:
            raise error.LoginFailed('Invalid credentials')

        creds = creds.split(':', 1)
        if len(creds) == 2:
            return credentials.UsernamePassword(*creds)
        else:
            raise error.LoginFailed('Invalid credentials')