-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.py
89 lines (67 loc) · 2.32 KB
/
utils.py
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from flask import Flask
from flask_assets import Bundle, Environment
from datetime import datetime, timedelta, timezone
import uuid
import hashlib
import jwt
from jwt.algorithms import NoneAlgorithm, HMACAlgorithm
from typing import Any
def setup_assets(app : Flask) -> None:
"""Setup the assets pipeline."""
assets = Environment(app)
css = Bundle("dist/main.css")
assets.register("css", css)
def valid_user(username: str, password: str) -> bool:
"""Check if the user credentials are valid."""
# Sample user credentials (in a real application, use a database)
valid_users = {"user1": "password1", "user2": "password2"}
return username in valid_users and valid_users[username] == password
def create_access_token(
identity: str,
key: str,
expires_delta: timedelta = timedelta(minutes=15),
algorithm: str = "HS256",
kid: str | None = None,
) -> str:
"""Create an access token."""
now = datetime.now(timezone.utc)
token_data = {
"iat": now,
"nbf": now,
"exp": now + expires_delta,
"jti": str(uuid.uuid4()),
"type": "access",
"username": identity,
}
headers = None
if kid:
headers = {"kid": kid}
return jwt.encode(
token_data,
key,
algorithm,
headers=headers,
)
class DemoNoneAlgorithm(NoneAlgorithm):
"""An implementation of the None algorithm that always returns True."""
def prepare_key(self, key: str | None) -> None:
return None
def verify(self, msg: bytes, key: None, sig: bytes) -> bool:
return True
class DemoHMACAlgorithm(HMACAlgorithm):
"""An implementation of the HMAC algorithm that allows PEM keys."""
def prepare_key(self, key: str | bytes) -> bytes:
if isinstance(key, str):
return key.encode("utf-8")
return key
# Replace the default algorithms with the demo algorithms
jwt.unregister_algorithm("none")
jwt.register_algorithm("none", DemoNoneAlgorithm())
jwt.unregister_algorithm("HS256")
jwt.register_algorithm("HS256", DemoHMACAlgorithm(hashlib.sha256))
def get_user(token: str, key: str, algs: list[str]) -> str:
"""Get the user from a token."""
if not token:
raise ValueError("invalid token")
payload = jwt.decode(token, key, algorithms=algs)
return str(payload["username"])