319 lines
11 KiB
Python
319 lines
11 KiB
Python
"""Shared account/session persistence and password helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import secrets
|
|
import threading
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timedelta
|
|
|
|
import asyncpg
|
|
import bcrypt
|
|
|
|
from .postgres import Database
|
|
|
|
_SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS auth_users (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
username TEXT NOT NULL UNIQUE,
|
|
email TEXT NOT NULL DEFAULT '',
|
|
password_hash TEXT NOT NULL,
|
|
role TEXT NOT NULL DEFAULT 'user',
|
|
totp_secret TEXT NOT NULL DEFAULT '',
|
|
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
|
UPDATE auth_users SET role = 'superadmin'
|
|
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
|
|
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
|
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
|
ON auth_users (lower(email)) WHERE email <> '';
|
|
CREATE TABLE IF NOT EXISTS auth_sessions (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
|
|
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
|
"""
|
|
|
|
RESET_CODE_TTL = timedelta(minutes=5)
|
|
|
|
ROLE_SUPERADMIN = "superadmin"
|
|
ROLE_ADMIN = "admin"
|
|
ROLE_USER = "user"
|
|
|
|
|
|
def normalize_role(value: str | None) -> str:
|
|
normalized = str(value or "").strip().lower()
|
|
return normalized if normalized in {ROLE_SUPERADMIN, ROLE_ADMIN} else ROLE_USER
|
|
|
|
|
|
def can_manage_users(role: str | None) -> bool:
|
|
return normalize_role(role) in {ROLE_SUPERADMIN, ROLE_ADMIN}
|
|
|
|
|
|
def can_assign_role(actor_role: str | None, target_role: str | None) -> bool:
|
|
return (
|
|
normalize_role(actor_role) == ROLE_SUPERADMIN
|
|
and normalize_role(target_role) != ROLE_SUPERADMIN
|
|
)
|
|
|
|
|
|
class ResetManager:
|
|
"""Creates and validates the short-lived, one-time admin reset code."""
|
|
|
|
def __init__(self, *, ttl: timedelta = RESET_CODE_TTL, log=print) -> None:
|
|
self._ttl = ttl
|
|
self._log = log
|
|
self._code: str | None = None
|
|
self._expires_at: datetime | None = None
|
|
self._lock = threading.Lock()
|
|
|
|
def request(self) -> str:
|
|
code = secrets.token_hex(4).upper()
|
|
with self._lock:
|
|
self._code = code
|
|
self._expires_at = datetime.now().astimezone() + self._ttl
|
|
self._log(
|
|
f"\n{'=' * 50}\nADMIN RESET CODE: {code}\n"
|
|
f"Expires in 5 minutes. Enter it on the login page.\n{'=' * 50}\n"
|
|
)
|
|
return code
|
|
|
|
def confirm(self, candidate: str) -> bool:
|
|
with self._lock:
|
|
if self._code is None or self._expires_at is None:
|
|
return False
|
|
if datetime.now().astimezone() > self._expires_at:
|
|
self._code = None
|
|
self._expires_at = None
|
|
return False
|
|
valid = secrets.compare_digest(self._code, str(candidate or "").strip().upper())
|
|
if valid:
|
|
self._code = None
|
|
self._expires_at = None
|
|
return valid
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class AuthUser:
|
|
id: int
|
|
username: str
|
|
email: str
|
|
password_hash: str
|
|
role: str = ROLE_USER
|
|
created_at: datetime | None = None
|
|
updated_at: datetime | None = None
|
|
|
|
|
|
class UserExistsError(Exception):
|
|
"""Raised when a user violates a unique or single-user constraint."""
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
if len(password) < 8:
|
|
raise ValueError("Password must be at least 8 characters")
|
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
|
|
|
|
|
def verify_password(password: str, stored_hash: str) -> bool:
|
|
try:
|
|
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
|
|
except (ValueError, TypeError):
|
|
return False
|
|
|
|
|
|
class AuthStore:
|
|
def __init__(self, database: Database, *, single_user: bool = True) -> None:
|
|
self.database = database
|
|
self.single_user = single_user
|
|
|
|
async def ensure_schema(self) -> None:
|
|
await self.database.execute(_SCHEMA)
|
|
if self.single_user:
|
|
await self.database.execute(
|
|
"CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))"
|
|
)
|
|
else:
|
|
await self.database.execute("DROP INDEX IF EXISTS auth_users_singleton_idx")
|
|
|
|
async def count_users(self) -> int:
|
|
return int(await self.database.fetchval("SELECT count(*) FROM auth_users"))
|
|
|
|
async def create_user(self, username: str, email: str, password_hash: str) -> AuthUser:
|
|
try:
|
|
row = await self.database.fetchrow(
|
|
"""
|
|
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
|
VALUES ($1, $2, $3,
|
|
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user'
|
|
ELSE 'superadmin' END,
|
|
now())
|
|
RETURNING id, username, email, password_hash, role, created_at, updated_at
|
|
""",
|
|
username,
|
|
email,
|
|
password_hash,
|
|
)
|
|
except asyncpg.UniqueViolationError as exc:
|
|
raise UserExistsError from exc
|
|
assert row is not None
|
|
return AuthUser(**dict(row))
|
|
|
|
async def find_by_identifier(self, identifier: str) -> AuthUser | None:
|
|
row = await self.database.fetchrow(
|
|
"""
|
|
SELECT id, username, email, password_hash, role, created_at, updated_at
|
|
FROM auth_users
|
|
WHERE username = $1 OR lower(email) = lower($1)
|
|
""",
|
|
identifier,
|
|
)
|
|
return AuthUser(**dict(row)) if row else None
|
|
|
|
async def update_credentials(
|
|
self, user_id: int, username: str, email: str, password_hash: str
|
|
) -> None:
|
|
await self.database.execute(
|
|
"""
|
|
UPDATE auth_users
|
|
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
|
WHERE id = $4
|
|
""",
|
|
username,
|
|
email,
|
|
password_hash,
|
|
user_id,
|
|
)
|
|
|
|
async def create_session(self, user_id: int, token_hash: str, expires_at: datetime) -> None:
|
|
await self.database.execute(
|
|
"INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3)",
|
|
user_id,
|
|
token_hash,
|
|
expires_at,
|
|
)
|
|
|
|
async def find_session_user(self, token_hash: str) -> AuthUser | None:
|
|
row = await self.database.fetchrow(
|
|
"""
|
|
SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at
|
|
FROM auth_sessions s
|
|
JOIN auth_users u ON u.id = s.user_id
|
|
WHERE s.token_hash = $1 AND s.expires_at > now()
|
|
""",
|
|
token_hash,
|
|
)
|
|
return AuthUser(**dict(row)) if row else None
|
|
|
|
async def delete_session(self, token_hash: str) -> None:
|
|
await self.database.execute("DELETE FROM auth_sessions WHERE token_hash = $1", token_hash)
|
|
|
|
async def delete_sessions_for_user(self, user_id: int) -> None:
|
|
await self.database.execute("DELETE FROM auth_sessions WHERE user_id = $1", user_id)
|
|
|
|
async def list_users(self) -> list[AuthUser]:
|
|
rows = await self.database.fetch(
|
|
"SELECT id, username, email, role, password_hash, created_at, updated_at "
|
|
"FROM auth_users ORDER BY created_at, id"
|
|
)
|
|
return [AuthUser(**dict(row)) for row in rows]
|
|
|
|
async def create_managed_user(
|
|
self, username: str, email: str, password_hash: str, role: str = ROLE_USER
|
|
) -> AuthUser:
|
|
try:
|
|
row = await self.database.fetchrow(
|
|
"""
|
|
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
|
VALUES ($1, $2, $3, $4, now())
|
|
RETURNING id, username, email, password_hash, role, created_at, updated_at
|
|
""",
|
|
username,
|
|
email,
|
|
password_hash,
|
|
normalize_role(role),
|
|
)
|
|
except asyncpg.UniqueViolationError as exc:
|
|
raise UserExistsError from exc
|
|
assert row is not None
|
|
return AuthUser(**dict(row))
|
|
|
|
async def update_user(
|
|
self,
|
|
user_id: int,
|
|
*,
|
|
username: str | None = None,
|
|
email: str | None = None,
|
|
password_hash: str | None = None,
|
|
role: str | None = None,
|
|
) -> None:
|
|
fields: list[str] = []
|
|
values: list[object] = []
|
|
for column, value in (
|
|
("username", username),
|
|
("email", email),
|
|
("password_hash", password_hash),
|
|
("role", normalize_role(role) if role is not None else None),
|
|
):
|
|
if value is not None:
|
|
fields.append(f"{column} = ${len(values) + 1}")
|
|
values.append(value)
|
|
if not fields:
|
|
return
|
|
values.append(user_id)
|
|
query = (
|
|
f"UPDATE auth_users SET {', '.join(fields)}, "
|
|
f"updated_at = now() WHERE id = ${len(values)}"
|
|
)
|
|
await self.database.execute(query, *values)
|
|
|
|
async def delete_user(self, user_id: int) -> None:
|
|
await self.database.execute("DELETE FROM auth_users WHERE id = $1", user_id)
|
|
|
|
async def delete_all_users(self) -> None:
|
|
await self.database.execute("DELETE FROM auth_users")
|
|
|
|
async def get_totp_state(self, user_id: int) -> dict[str, object]:
|
|
row = await self.database.fetchrow(
|
|
"SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled "
|
|
"FROM auth_users WHERE id = $1",
|
|
user_id,
|
|
)
|
|
return dict(row) if row else {"secret": "", "enabled": False}
|
|
|
|
async def set_totp_secret(self, user_id: int, secret: str) -> None:
|
|
await self.database.execute(
|
|
"UPDATE auth_users SET totp_secret = $1, totp_enabled = false, "
|
|
"updated_at = now() WHERE id = $2",
|
|
secret,
|
|
user_id,
|
|
)
|
|
|
|
async def enable_totp(self, user_id: int) -> None:
|
|
await self.database.execute(
|
|
"UPDATE auth_users SET totp_enabled = true, updated_at = now() "
|
|
"WHERE id = $1 AND totp_secret <> ''",
|
|
user_id,
|
|
)
|
|
|
|
async def disable_totp(self, user_id: int) -> None:
|
|
await self.database.execute(
|
|
"UPDATE auth_users SET totp_secret = '', totp_enabled = false, "
|
|
"updated_at = now() WHERE id = $1",
|
|
user_id,
|
|
)
|
|
|
|
async def prune_expired_sessions(self) -> None:
|
|
await self.database.execute("DELETE FROM auth_sessions WHERE expires_at < now()")
|