#!/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 . 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')