|
| 1 | +from dataclasses import dataclass, field |
| 2 | +from datetime import UTC, datetime |
| 3 | +from time import time |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +import jwt as pyjwt |
| 7 | + |
| 8 | + |
| 9 | +@dataclass(frozen=True, kw_only=True) |
| 10 | +class JWT: |
| 11 | + issuer: str |
| 12 | + subject: str |
| 13 | + audience: str |
| 14 | + requesting_device: str |
| 15 | + requesting_organization: str |
| 16 | + requesting_practitioner: str |
| 17 | + |
| 18 | + # Time fields |
| 19 | + issued_at: int = field(default_factory=lambda: int(time())) |
| 20 | + expiration: int = field(default_factory=lambda: int(time()) + 300) |
| 21 | + |
| 22 | + # These are here for future proofing but are not expected ever to be changed |
| 23 | + algorithm: str | None = None |
| 24 | + type: str = "JWT" |
| 25 | + reason_for_request: str = "directcare" |
| 26 | + requested_scope: str = "patient/*.read" |
| 27 | + |
| 28 | + @property |
| 29 | + def issue_time(self) -> str: |
| 30 | + return datetime.fromtimestamp(self.issued_at, tz=UTC).isoformat() |
| 31 | + |
| 32 | + @property |
| 33 | + def exp_time(self) -> str: |
| 34 | + return datetime.fromtimestamp(self.expiration, tz=UTC).isoformat() |
| 35 | + |
| 36 | + def encode(self) -> str: |
| 37 | + return pyjwt.encode( |
| 38 | + self.payload(), |
| 39 | + key=None, |
| 40 | + algorithm=self.algorithm, |
| 41 | + headers={"typ": self.type}, |
| 42 | + ) |
| 43 | + |
| 44 | + @staticmethod |
| 45 | + def decode(token: str) -> "JWT": |
| 46 | + token_dict = pyjwt.decode( |
| 47 | + token, |
| 48 | + options={"verify_signature": False}, # NOSONAR S5659 (not signed) |
| 49 | + ) |
| 50 | + |
| 51 | + return JWT( |
| 52 | + issuer=token_dict["iss"], |
| 53 | + subject=token_dict["sub"], |
| 54 | + audience=token_dict["aud"], |
| 55 | + expiration=token_dict["exp"], |
| 56 | + issued_at=token_dict["iat"], |
| 57 | + requesting_device=token_dict["requesting_device"], |
| 58 | + requesting_organization=token_dict["requesting_organization"], |
| 59 | + requesting_practitioner=token_dict["requesting_practitioner"], |
| 60 | + ) |
| 61 | + |
| 62 | + def payload(self) -> dict[str, Any]: |
| 63 | + return { |
| 64 | + "iss": self.issuer, |
| 65 | + "sub": self.subject, |
| 66 | + "aud": self.audience, |
| 67 | + "exp": self.expiration, |
| 68 | + "iat": self.issued_at, |
| 69 | + "requesting_device": self.requesting_device, |
| 70 | + "requesting_organization": self.requesting_organization, |
| 71 | + "requesting_practitioner": self.requesting_practitioner, |
| 72 | + "reason_for_request": self.reason_for_request, |
| 73 | + "requested_scope": self.requested_scope, |
| 74 | + } |
| 75 | + |
| 76 | + def __str__(self) -> str: |
| 77 | + return self.encode() |
0 commit comments