-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
62 lines (48 loc) · 1.57 KB
/
Copy pathauth.py
File metadata and controls
62 lines (48 loc) · 1.57 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
"""JWT session management — stateless cookie-based authentication."""
from datetime import datetime, timedelta, timezone
import jwt
from flask import request
from config import Config
COOKIE_NAME = "idp_session"
def create_jwt(user_dict: dict) -> str:
payload = {
"sub": user_dict["email"],
"display_name": user_dict["display_name"],
"roles": user_dict["roles"],
"iat": datetime.now(timezone.utc),
"exp": datetime.now(timezone.utc)
+ timedelta(minutes=Config.JWT_EXPIRY_MINUTES),
}
return jwt.encode(payload, Config.JWT_SECRET, algorithm=Config.JWT_ALGORITHM)
def verify_jwt(token: str) -> dict | None:
try:
return jwt.decode(
token, Config.JWT_SECRET, algorithms=[Config.JWT_ALGORITHM]
)
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
return None
def get_current_user() -> dict | None:
token = request.cookies.get(COOKIE_NAME)
if not token:
return None
payload = verify_jwt(token)
if payload is None:
return None
return {
"email": payload["sub"],
"display_name": payload["display_name"],
"roles": payload["roles"],
}
def set_session_cookie(response, token: str):
response.set_cookie(
COOKIE_NAME,
token,
httponly=Config.COOKIE_HTTPONLY,
secure=Config.COOKIE_SECURE,
samesite=Config.COOKIE_SAMESITE,
max_age=Config.JWT_EXPIRY_MINUTES * 60,
)
return response
def clear_session_cookie(response):
response.delete_cookie(COOKIE_NAME)
return response