|
| 1 | +import re |
| 2 | +from time import time |
| 3 | +from jwt import encode |
| 4 | +from uuid import uuid4 |
| 5 | +from typing import Union |
| 6 | + |
| 7 | + |
| 8 | +class JwtClient: |
| 9 | + """Object used to pass in an application ID and private key to generate JWT methods.""" |
| 10 | + |
| 11 | + def __init__(self, application_id: str, private_key: str): |
| 12 | + self._application_id = application_id |
| 13 | + |
| 14 | + try: |
| 15 | + self._set_private_key(private_key) |
| 16 | + except Exception as err: |
| 17 | + raise VonageJwtError(err) |
| 18 | + |
| 19 | + if self._application_id is None or self._private_key is None: |
| 20 | + raise VonageJwtError( |
| 21 | + 'Both of "application_id" and "private_key" are required.' |
| 22 | + ) |
| 23 | + |
| 24 | + def generate_application_jwt(self, jwt_options: dict = {}): |
| 25 | + """ |
| 26 | + Generates a JWT for the specified Vonage application. |
| 27 | + You can override values for application_id and private_key on the JWTClient object by |
| 28 | + specifying them in the `jwt_options` dict if required. |
| 29 | + """ |
| 30 | + |
| 31 | + iat = int(time()) |
| 32 | + |
| 33 | + payload = jwt_options |
| 34 | + payload["application_id"] = self._application_id |
| 35 | + payload.setdefault("iat", iat) |
| 36 | + payload.setdefault("jti", str(uuid4())) |
| 37 | + payload.setdefault("exp", iat + (15 * 60)) |
| 38 | + |
| 39 | + headers = {'alg': 'RS256', 'typ': 'JWT'} |
| 40 | + |
| 41 | + token = encode(payload, self._private_key, algorithm='RS256', headers=headers) |
| 42 | + return bytes(token, 'utf-8') |
| 43 | + |
| 44 | + def _set_private_key(self, key: Union[str, bytes]): |
| 45 | + if isinstance(key, (str, bytes)) and re.search("[.][a-zA-Z0-9_]+$", key): |
| 46 | + with open(key, "rb") as key_file: |
| 47 | + self._private_key = key_file.read() |
| 48 | + elif isinstance(key, str) and '-----BEGIN PRIVATE KEY-----' not in key: |
| 49 | + raise VonageJwtError( |
| 50 | + "If passing the private key directly as a string, it must be formatted correctly with newlines." |
| 51 | + ) |
| 52 | + else: |
| 53 | + self._private_key = key |
| 54 | + |
| 55 | + |
| 56 | +class VonageJwtError(Exception): |
| 57 | + """An error relating to the Vonage JWT Generator.""" |
0 commit comments