This repository was archived by the owner on Jun 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathentities.py
More file actions
73 lines (56 loc) · 1.75 KB
/
entities.py
File metadata and controls
73 lines (56 loc) · 1.75 KB
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
73
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional
import jwt
from .exceptions import InvalidPastaportoError
from .tokens import decode_pastaporto
class Credential(str, Enum):
AUTHENTICATED = "authenticated"
STAFF = "staff"
def __str__(self) -> str:
return str.__str__(self)
class RequestAuth:
scopes: list[Credential]
pastaporto: Pastaporto
def __init__(self, pastaporto: Pastaporto):
self.scopes = pastaporto.credentials
self.pastaporto = pastaporto
@dataclass
class PastaportoUserInfo:
id: int
email: str
is_staff: bool
@classmethod
def from_data(cls, data: dict[str, Any]):
return cls(id=int(data["id"]), email=data["email"], is_staff=data["is_staff"])
@dataclass
class Pastaporto:
user_info: Optional[PastaportoUserInfo] = None
credentials: list[Credential] = field(default_factory=list)
@property
def is_authenticated(self):
return self.user_info is not None
@classmethod
def from_token(cls, token: str, secret: str):
try:
decoded_token = decode_pastaporto(token, secret)
except (
ValueError,
UnicodeDecodeError,
jwt.ExpiredSignatureError,
jwt.DecodeError,
jwt.InvalidAudienceError,
):
raise InvalidPastaportoError()
user_info = decoded_token.get("user_info")
return cls(
user_info=(
PastaportoUserInfo.from_data(user_info)
if user_info
else None
),
credentials=[
Credential(credential) for credential in decoded_token["credentials"]
],
)