feat(вход): TOTP и recovery

This commit is contained in:
anor
2026-11-06 23:14:30 +10:00
parent 6d45cf7c99
commit 4051c9eb3d
7 changed files with 309 additions and 5 deletions
+43 -1
View File
@@ -199,7 +199,8 @@ def init_db():
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")):
("totp_enabled", "INTEGER NOT NULL DEFAULT 0"),
("totp_secret", "TEXT"), ("totp_recovery", "TEXT")):
if _колонки_нет(conn, "users", _col):
conn.execute(f"ALTER TABLE users ADD COLUMN {_col} {_decl}")
# Migration: add blocked column if missing
@@ -1739,6 +1740,47 @@ def drop_idempotency(key: str) -> None:
conn.execute("DELETE FROM admin_idempotency WHERE key = ?", (key,))
def has_totp_admin() -> bool:
with _conn() as conn:
return bool(conn.execute("SELECT 1 FROM users WHERE role='admin' AND totp_enabled=1 "
"AND deleted_at IS NULL LIMIT 1").fetchone())
def set_totp_secret(email: str, secret: str) -> bool:
with _conn() as conn:
return conn.execute("UPDATE users SET totp_secret = ?, totp_enabled = 0 "
"WHERE email = ?", (secret, email.lower().strip())).rowcount > 0
def enable_totp(email: str, recovery_json: str) -> bool:
with _conn() as conn:
cur = conn.execute("UPDATE users SET totp_enabled = 1, totp_recovery = ?, "
"token_version = token_version + 1 WHERE email = ?",
(recovery_json, email.lower().strip()))
return cur.rowcount > 0
def disable_totp(email: str) -> bool:
with _conn() as conn:
cur = conn.execute("UPDATE users SET totp_enabled = 0, totp_secret = NULL, "
"totp_recovery = NULL, token_version = token_version + 1 "
"WHERE email = ?", (email.lower().strip(),))
return cur.rowcount > 0
def consume_recovery(email: str, recovery_json: str) -> None:
with _conn() as conn:
conn.execute("UPDATE users SET totp_recovery = ? WHERE email = ?",
(recovery_json, email.lower().strip()))
def revoke_user_sessions(email: str) -> int:
with _conn() as conn:
return conn.execute("UPDATE auth_sessions SET revoked_at = ? "
"WHERE username = ? AND revoked_at IS NULL",
(time.time(), email.lower().strip())).rowcount
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: