summaryrefslogtreecommitdiff
path: root/src/leap/soledad/client/auth.py
blob: 78e9bf1b55778b95978f533434f4adf4b8dbdee0 (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
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
# auth.py
# Copyright (C) 2013 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Methods for token-based authentication.

These methods have to be included in all classes that extend HTTPClient so
they can do token-based auth requests to the Soledad server.
"""
import base64

from leap.soledad.common.l2db import errors


class TokenBasedAuth(object):
    """
    Encapsulate token-auth methods for classes that inherit from
    u1db.remote.http_client.HTTPClient.
    """

    def set_token_credentials(self, uuid, token):
        """
        Store given credentials so we can sign the request later.

        :param uuid: The user's uuid.
        :type uuid: str
        :param token: The authentication token.
        :type token: str
        """
        self._creds = {'token': (uuid, token)}

    def _sign_request(self, method, url_query, params):
        """
        Return an authorization header to be included in the HTTP request, in
        the form:

            [('Authorization', 'Token <(base64 encoded) uuid:token>')]

        :param method: The HTTP method.
        :type method: str
        :param url_query: The URL query string.
        :type url_query: str
        :param params: A list with encoded query parameters.
        :type param: list

        :return: The Authorization header.
        :rtype: list of tuple
        """
        if 'token' in self._creds:
            uuid, token = self._creds['token']
            auth = '%s:%s' % (uuid, token)
            b64_token = base64.b64encode(auth)
            return [('Authorization', 'Token %s' % b64_token)]
        else:
            raise errors.UnknownAuthMethod(
                'Wrong credentials: %s' % self._creds)