|
| 1 | +import hashlib |
| 2 | +import pathlib |
| 3 | +import sqlite3 |
| 4 | +import time |
| 5 | +from contextlib import contextmanager |
| 6 | +from typing import Iterator |
| 7 | + |
| 8 | +DB_PATH = pathlib.Path.cwd() / "fastapi_ui_auth.db" |
| 9 | +FAILURE_TTL = 3600 # failed-attempt counters reset after 1 hour |
| 10 | + |
| 11 | + |
| 12 | +@contextmanager |
| 13 | +def _connect() -> Iterator[sqlite3.Connection]: |
| 14 | + """Context manager for SQLite connection with WAL mode enabled. |
| 15 | +
|
| 16 | + Yields: |
| 17 | + sqlite3.Connection: The SQLite connection. |
| 18 | + """ |
| 19 | + # autocommit; WAL + busy timeout makes this safe across worker processes |
| 20 | + conn = sqlite3.connect(DB_PATH, timeout=10, isolation_level=None) |
| 21 | + try: |
| 22 | + conn.execute("PRAGMA journal_mode=WAL") |
| 23 | + yield conn |
| 24 | + finally: |
| 25 | + conn.close() |
| 26 | + |
| 27 | + |
| 28 | +def _hash(token: str) -> str: |
| 29 | + """Hash a token using SHA-256. |
| 30 | +
|
| 31 | + Args: |
| 32 | + token: The token to hash. |
| 33 | +
|
| 34 | + Returns: |
| 35 | + str: |
| 36 | + The hashed token. |
| 37 | + """ |
| 38 | + # tokens are stored hashed, so a leaked DB file doesn't leak live sessions |
| 39 | + return hashlib.sha256(token.encode("utf-8")).hexdigest() |
| 40 | + |
| 41 | + |
| 42 | +def init() -> None: |
| 43 | + """Create tables (idempotent, safe to call from every worker).""" |
| 44 | + with _connect() as conn: |
| 45 | + conn.execute( |
| 46 | + "CREATE TABLE IF NOT EXISTS sessions " |
| 47 | + "(token TEXT PRIMARY KEY, expires_at REAL NOT NULL)" |
| 48 | + ) |
| 49 | + conn.execute( |
| 50 | + "CREATE TABLE IF NOT EXISTS failures " |
| 51 | + "(key TEXT PRIMARY KEY, count INTEGER NOT NULL, updated_at REAL NOT NULL)" |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +def purge() -> None: |
| 56 | + """Purge expired sessions and old failure records.""" |
| 57 | + now = time.time() |
| 58 | + with _connect() as conn: |
| 59 | + conn.execute("DELETE FROM sessions WHERE expires_at < ?", (now,)) |
| 60 | + conn.execute("DELETE FROM failures WHERE updated_at < ?", (now - FAILURE_TTL,)) |
| 61 | + |
| 62 | + |
| 63 | +def add_session(token: str, ttl: int) -> None: |
| 64 | + """Add a session with a time-to-live (TTL). |
| 65 | +
|
| 66 | + Args: |
| 67 | + token: The session token to add. |
| 68 | + ttl: Time-to-live in seconds. |
| 69 | + """ |
| 70 | + purge() |
| 71 | + with _connect() as conn: |
| 72 | + conn.execute( |
| 73 | + "INSERT OR REPLACE INTO sessions (token, expires_at) VALUES (?, ?)", |
| 74 | + (_hash(token), time.time() + ttl), |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +def session_valid(token: str) -> bool: |
| 79 | + """Check if a session token is valid (exists and not expired). |
| 80 | +
|
| 81 | + Args: |
| 82 | + token: The session token to check. |
| 83 | +
|
| 84 | + Returns: |
| 85 | + bool: True if the session token is valid, False otherwise. |
| 86 | + """ |
| 87 | + with _connect() as conn: |
| 88 | + row = conn.execute( |
| 89 | + "SELECT expires_at FROM sessions WHERE token = ?", (_hash(token),) |
| 90 | + ).fetchone() |
| 91 | + return bool(row and row[0] > time.time()) |
| 92 | + |
| 93 | + |
| 94 | +def delete_session(token: str) -> None: |
| 95 | + """Delete a session token. |
| 96 | +
|
| 97 | + Args: |
| 98 | + token: The session token to delete. |
| 99 | + """ |
| 100 | + with _connect() as conn: |
| 101 | + conn.execute("DELETE FROM sessions WHERE token = ?", (_hash(token),)) |
| 102 | + |
| 103 | + |
| 104 | +def record_failure(key: str) -> int: |
| 105 | + """Record a failed attempt and return the current count. |
| 106 | +
|
| 107 | + Args: |
| 108 | + key: The key for which to record the failure. |
| 109 | +
|
| 110 | + Returns: |
| 111 | + int: |
| 112 | + The current failure count for the given key. |
| 113 | + """ |
| 114 | + now = time.time() |
| 115 | + with _connect() as conn: |
| 116 | + conn.execute( |
| 117 | + "DELETE FROM failures WHERE key = ? AND updated_at < ?", |
| 118 | + (key, now - FAILURE_TTL), |
| 119 | + ) |
| 120 | + conn.execute( |
| 121 | + "INSERT INTO failures (key, count, updated_at) VALUES (?, 1, ?) " |
| 122 | + "ON CONFLICT(key) DO UPDATE SET count = count + 1, updated_at = excluded.updated_at", |
| 123 | + (key, now), |
| 124 | + ) |
| 125 | + return conn.execute( |
| 126 | + "SELECT count FROM failures WHERE key = ?", (key,) |
| 127 | + ).fetchone()[0] |
| 128 | + |
| 129 | + |
| 130 | +def reset_failures(key: str) -> None: |
| 131 | + """Reset the failure count for a given key. |
| 132 | +
|
| 133 | + Args: |
| 134 | + key: The key for which to reset the failure count. |
| 135 | + """ |
| 136 | + with _connect() as conn: |
| 137 | + conn.execute("DELETE FROM failures WHERE key = ?", (key,)) |
0 commit comments