add password reset via admin-generated one-time code

db.py: reset_codes table (code, handle, created_by, created_at,
expires_at, used_at); create_reset_code() invalidates any prior unused
code for the same handle; use_reset_code() validates handle match,
expiry (24 h), and single-use; change_password() updates the hash.

server.py: POST /api/admin/users/{handle}/reset-password-code (admin)
returns a code; POST /api/auth/reset-password (public) validates the
code + handle and sets the new password.

Admin page: "Reset pwd" button per user — shows the code inline on
click (monospace, click-to-copy).
/reset-password/ page: handle + code + new password form.
Login page: "Forgot password?" link.
This commit is contained in:
Davide Scaini
2026-04-14 21:58:50 +02:00
parent d2ba96c26a
commit 13643479ef
5 changed files with 226 additions and 0 deletions
+69
View File
@@ -45,6 +45,15 @@ CREATE TABLE IF NOT EXISTS invites (
used_at INTEGER
);
CREATE TABLE IF NOT EXISTS reset_codes (
code TEXT PRIMARY KEY,
handle TEXT NOT NULL REFERENCES users(handle) ON DELETE CASCADE,
created_by TEXT NOT NULL REFERENCES users(handle) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
used_at INTEGER
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
@@ -52,10 +61,12 @@ CREATE TABLE IF NOT EXISTS settings (
CREATE INDEX IF NOT EXISTS sessions_handle ON sessions(handle);
CREATE INDEX IF NOT EXISTS invites_created_by ON invites(created_by);
CREATE INDEX IF NOT EXISTS reset_codes_handle ON reset_codes(handle);
"""
_SESSION_DAYS = 30
_INVITE_LENGTH = 8
_RESET_CODE_TTL_S = 24 * 3600 # 24 hours
# ── Data classes ──────────────────────────────────────────────────────────────
@@ -143,6 +154,13 @@ def authenticate(db: sqlite3.Connection, handle: str, password: str) -> Optional
)
def change_password(db: sqlite3.Connection, handle: str, new_password: str) -> None:
"""Replace the password hash for a user."""
new_hash = bcrypt.hashpw(new_password.encode(), bcrypt.gensalt()).decode()
db.execute("UPDATE users SET password_hash = ? WHERE handle = ?", (new_hash, handle))
db.commit()
def list_users(db: sqlite3.Connection) -> list[User]:
rows = db.execute("SELECT * FROM users ORDER BY created_at").fetchall()
return [User(handle=r["handle"], display_name=r["display_name"],
@@ -317,3 +335,54 @@ def get_invite(db: sqlite3.Connection, code: str) -> Optional[Invite]:
created_at=row["created_at"],
used_at=row["used_at"],
)
# ── Password reset codes ──────────────────────────────────────────────────────
def create_reset_code(db: sqlite3.Connection, handle: str, created_by: str) -> str:
"""Generate a password reset code for a user (admin only, out-of-band delivery).
Any previous unused codes for this handle are invalidated first.
Returns the new code.
"""
now = int(time.time())
# Invalidate existing unused codes for this handle
db.execute(
"DELETE FROM reset_codes WHERE handle = ? AND used_at IS NULL",
(handle,),
)
code = secrets.token_urlsafe(_INVITE_LENGTH)[:_INVITE_LENGTH].upper()
db.execute(
"INSERT INTO reset_codes (code, handle, created_by, created_at, expires_at) "
"VALUES (?, ?, ?, ?, ?)",
(code, handle, created_by, now, now + _RESET_CODE_TTL_S),
)
db.commit()
return code
def use_reset_code(db: sqlite3.Connection, code: str, handle: str) -> bool:
"""Validate a reset code for the given handle and mark it used.
Returns False if the code is invalid, already used, expired, or
belongs to a different handle.
"""
now = int(time.time())
row = db.execute(
"SELECT handle, expires_at, used_at FROM reset_codes WHERE code = ?",
(code,),
).fetchone()
if not row:
return False
if row["handle"] != handle:
return False
if row["used_at"] is not None:
return False
if row["expires_at"] < now:
return False
db.execute(
"UPDATE reset_codes SET used_at = ? WHERE code = ?",
(now, code),
)
db.commit()
return True