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
"""
In-process opaque session IDs (browser cookie / Bearer token value).
Single-process only; restarting the server clears every session (empty dict).
"""
from __future__ import annotations
import secrets
import threading
import time
from dataclasses import dataclass
from typing import Literal
_lock = threading.Lock()
AuthMethod = Literal["local", "oauth"]
@dataclass(frozen=True)
class Session:
username: str
created_at: float
subject: str | None = None
email: str | None = None
auth_method: AuthMethod = "local"
_sessions: dict[str, Session] = {}
def create_session(
username: str,
*,
subject: str | None = None,
email: str | None = None,
auth_method: AuthMethod = "local",
) -> str:
sid = secrets.token_urlsafe(32)
with _lock:
_sessions[sid] = Session(
username=username,
created_at=time.time(),
subject=subject,
email=email,
auth_method=auth_method,
)
return sid
def get_session(session_id: str | None) -> Session | None:
if not session_id:
return None
raw = session_id.strip()
if not raw:
return None
with _lock:
return _sessions.get(raw)
def revoke_session(session_id: str | None) -> None:
if not session_id:
return
raw = session_id.strip()
if not raw:
return
with _lock:
_sessions.pop(raw, None)
def clear_all_sessions() -> None:
with _lock:
_sessions.clear()