Project: pygitweb

8c60507 """
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
4a34d33 from typing import Literal
8c60507
_lock = threading.Lock()
4a34d33 AuthMethod = Literal["local", "oauth"]
8c60507
@dataclass(frozen=True)
class Session:
73c9c30 username: str
created_at: float
subject: str | None = None
email: str | None = None
auth_method: AuthMethod = "local"
8c60507
_sessions: dict[str, Session] = {}
4a34d33 def create_session(
73c9c30 username: str,
*,
subject: str | None = None,
email: str | None = None,
auth_method: AuthMethod = "local",
4a34d33 ) -> str:
73c9c30 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
8c60507
def get_session(session_id: str | None) -> Session | None:
73c9c30 if not session_id:
return None
raw = session_id.strip()
if not raw:
return None
with _lock:
return _sessions.get(raw)
8c60507
def revoke_session(session_id: str | None) -> None:
73c9c30 if not session_id:
return
raw = session_id.strip()
if not raw:
return
with _lock:
_sessions.pop(raw, None)
8c60507
def clear_all_sessions() -> None:
73c9c30 with _lock:
_sessions.clear()