summaryrefslogtreecommitdiff
path: root/qvisqve/token.py
blob: edc62fdc99ee872e3272e37dda32d33f9c042581 (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
70
71
72
#!/usr/bin/python3
# Copyright (C) 2017-2018  Lars Wirzenius
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import time


import Crypto.PublicKey.RSA
import jwt


import qvisqve


class TokenGenerator:

    _algorithm = 'RS512'

    def __init__(self):
        self._issuer = None
        self._lifetime = None
        self._key = None

    def set_issuer(self, issuer):
        self._issuer = issuer
        qvisqve.log.log('info', msg_text='Set issuer', issuer=issuer)

    def set_lifetime(self, lifetime):
        self._lifetime = lifetime
        qvisqve.log.log(
            'info', msg_text='Set token lifetime', lifetime=lifetime)

    def set_signing_key(self, key):
        imported_key = Crypto.PublicKey.RSA.importKey(key)
        self._key = imported_key.exportKey('PEM')
        qvisqve.log.log(
            'info', msg_text='Set signing key', key=self._key,
            orig_key=key, imported_key=imported_key)

    def new_token(self, audience, scope, subject_id=None):
        assert self._issuer is not None
        assert self._lifetime is not None
        assert self._key is not None

        now = time.time()
        claims = {
            'iss': self._issuer,
            'sub': subject_id or '',
            'aud': audience,
            'exp': now + self._lifetime,
            'scope': scope,
        }

        token = jwt.encode(
            claims,
            self._key,
            algorithm=self._algorithm)

        return token.decode('ascii')