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
"""
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
_lock = threading.Lock()
@dataclass(frozen=True)
class Session:
username: str
created_at: float
_sessions: dict[str, Session] = {}
def create_session(username: str) -> str:
sid = secrets.token_urlsafe(32)
with _lock:
_sessions[sid] = Session(username=username, created_at=time.time())
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()