feat(вход): сессии jti/ver и короткий admin-токен

This commit is contained in:
anor
2026-11-06 23:12:44 +10:00
parent b07c2053bb
commit 6d45cf7c99
6 changed files with 206 additions and 27 deletions
+45
View File
@@ -57,6 +57,18 @@ CREATE TABLE IF NOT EXISTS audit_log (
);
CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_log(timestamp);
CREATE TABLE IF NOT EXISTS auth_sessions (
jti TEXT PRIMARY KEY,
username TEXT NOT NULL,
role TEXT NOT NULL,
created_at REAL NOT NULL,
expires_at REAL NOT NULL,
revoked_at REAL,
ip TEXT,
user_agent TEXT,
ver INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_auth_sessions_user ON auth_sessions(username);
CREATE TABLE IF NOT EXISTS feedback (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp REAL NOT NULL,
@@ -186,6 +198,10 @@ def init_db():
("status", "TEXT NOT NULL DEFAULT 'new'")):
if _колонки_нет(conn, "feedback", _col):
conn.execute(f"ALTER TABLE feedback ADD COLUMN {_col} {_decl}")
for _col, _decl in (("token_version", "INTEGER NOT NULL DEFAULT 0"),
("totp_enabled", "INTEGER NOT NULL DEFAULT 0")):
if _колонки_нет(conn, "users", _col):
conn.execute(f"ALTER TABLE users ADD COLUMN {_col} {_decl}")
# Migration: add blocked column if missing
if _колонки_нет(conn, "users", "blocked"):
conn.execute("ALTER TABLE users ADD COLUMN blocked INTEGER NOT NULL DEFAULT 0")
@@ -1723,6 +1739,35 @@ def drop_idempotency(key: str) -> None:
conn.execute("DELETE FROM admin_idempotency WHERE key = ?", (key,))
def create_auth_session(jti: str, username: str, role: str, expires_at: float,
ip: str | None = None, user_agent: str | None = None,
ver: int = 0) -> None:
with _conn() as conn:
conn.execute(
"INSERT INTO auth_sessions (jti, username, role, created_at, expires_at, ip, "
"user_agent, ver) VALUES (?,?,?,?,?,?,?,?)",
(jti, username, role, time.time(), expires_at, ip, user_agent, ver))
def get_auth_session(jti: str) -> dict | None:
with _conn() as conn:
row = conn.execute("SELECT * FROM auth_sessions WHERE jti = ?", (jti,)).fetchone()
return dict(row) if row else None
def revoke_auth_session(jti: str) -> bool:
with _conn() as conn:
return conn.execute("UPDATE auth_sessions SET revoked_at = ? WHERE jti = ? AND revoked_at IS NULL",
(time.time(), jti)).rowcount > 0
def list_auth_sessions(username: str) -> list[dict]:
with _conn() as conn:
rows = conn.execute("SELECT * FROM auth_sessions WHERE username = ? "
"ORDER BY created_at DESC LIMIT 50", (username,)).fetchall()
return [dict(r) for r in rows]
def record_admin_action(actor: str, target: str, action: str,
before: dict, after: dict, now: float | None = None) -> int:
import json as _json