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
+34
View File
@@ -346,6 +346,25 @@ async def logout(bincio_session: Optional[str] = Cookie(default=None)) -> JSONRe
return resp
@app.post("/api/auth/reset-password")
async def reset_password(request: Request) -> JSONResponse:
"""Validate a reset code and set a new password. Public endpoint."""
from bincio.serve.db import use_reset_code, change_password
body = await request.json()
handle = (body.get("handle") or "").strip().lower()
code = (body.get("code") or "").strip().upper()
new_pw = body.get("password") or ""
if not handle or not code or not new_pw:
raise HTTPException(400, "handle, code, and password are required")
if len(new_pw) < 8:
raise HTTPException(400, "Password must be at least 8 characters")
db = _get_db()
if not use_reset_code(db, code, handle):
raise HTTPException(400, "Invalid or expired reset code")
change_password(db, handle, new_pw)
return JSONResponse({"ok": True})
# ── Registration ──────────────────────────────────────────────────────────────
@app.post("/api/register")
@@ -503,6 +522,21 @@ async def admin_disk(bincio_session: Optional[str] = Cookie(default=None)) -> JS
})
@app.post("/api/admin/users/{handle}/reset-password-code")
async def admin_reset_password_code(
handle: str,
bincio_session: Optional[str] = Cookie(default=None),
) -> JSONResponse:
"""Generate a one-time password reset code for a user. Admin only."""
from bincio.serve.db import create_reset_code
admin = _require_admin(bincio_session)
db = _get_db()
if not get_user(db, handle):
raise HTTPException(404, f"User '{handle}' not found")
code = create_reset_code(db, handle, admin.handle)
return JSONResponse({"ok": True, "code": code, "expires_in_hours": 24})
@app.post("/api/admin/users/{handle}/rebuild")
async def admin_rebuild(
handle: str,
+34
View File
@@ -122,6 +122,11 @@ import Base from '../../layouts/Base.astro';
data-handle="${u.handle}"
title="Re-run merge_all and trigger a site rebuild"
>Rebuild</button>
<button
class="pwreset-btn text-xs px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-400 hover:text-zinc-200 transition-colors"
data-handle="${u.handle}"
title="Generate a one-time password reset code for this user"
>Reset pwd</button>
<button
class="delete-btn text-xs px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-red-900 hover:text-red-300 text-zinc-400 transition-colors"
data-handle="${u.handle}"
@@ -161,6 +166,35 @@ import Base from '../../layouts/Base.astro';
});
});
tbodyEl.querySelectorAll<HTMLButtonElement>('.pwreset-btn').forEach(btn => {
btn.addEventListener('click', async () => {
const h = btn.dataset.handle!;
btn.disabled = true;
btn.textContent = '…';
try {
const r = await fetch(`/api/admin/users/${h}/reset-password-code`, {
method: 'POST',
credentials: 'include',
});
const d = await r.json();
if (r.ok) {
btn.textContent = d.code;
btn.title = `Code for ${h} — valid 24 h. Click to copy.`;
btn.classList.add('text-yellow-300', 'font-mono');
btn.addEventListener('click', () => navigator.clipboard.writeText(d.code), { once: true });
} else {
btn.textContent = 'Error';
btn.classList.add('text-red-400');
btn.disabled = false;
}
} catch {
btn.textContent = 'Error';
btn.classList.add('text-red-400');
btn.disabled = false;
}
});
});
tbodyEl.querySelectorAll<HTMLButtonElement>('.delete-btn').forEach(btn => {
btn.addEventListener('click', () => {
pendingHandle = btn.dataset.handle!;
+3
View File
@@ -33,6 +33,9 @@ const editUrl = import.meta.env.PUBLIC_EDIT_URL ?? '';
<p class="text-center text-zinc-500 text-sm mt-6">
Have an invite? <a href="/register/" class="text-[--accent] hover:underline">Create account</a>
</p>
<p class="text-center text-zinc-600 text-sm mt-2">
<a href="/reset-password/" class="hover:text-zinc-400 transition-colors">Forgot password?</a>
</p>
)}
</div>
</Base>
+86
View File
@@ -0,0 +1,86 @@
---
import Base from '../../layouts/Base.astro';
---
<Base title="Reset password — BincioActivity" public={true}>
<div class="max-w-sm mx-auto mt-16 px-4">
<h1 class="text-2xl font-bold text-white mb-2 text-center">Reset password</h1>
<p class="text-zinc-500 text-sm text-center mb-6">Enter the reset code you received from the admin.</p>
<form id="reset-form" class="space-y-4">
<div>
<label class="block text-sm text-zinc-400 mb-1" for="code">Reset code</label>
<input id="code" name="code" type="text" autocomplete="off"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white font-mono uppercase tracking-widest placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="XXXXXXXX" maxlength="8" required />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="handle">Handle</label>
<input id="handle" name="handle" type="text" autocomplete="username"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="your handle" required />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="password">New password</label>
<input id="password" name="password" type="password" autocomplete="new-password"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white focus:outline-none focus:border-[--accent]"
minlength="8" required />
<p class="text-zinc-600 text-xs mt-1">At least 8 characters</p>
</div>
<p id="reset-error" class="text-red-400 text-sm hidden"></p>
<p id="reset-ok" class="text-green-400 text-sm hidden">Password updated. <a href="/login/" class="underline">Sign in</a></p>
<button type="submit"
class="w-full py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white font-medium transition-opacity">
Set new password
</button>
</form>
<p class="text-center text-zinc-500 text-sm mt-6">
<a href="/login/" class="text-[--accent] hover:underline">Back to sign in</a>
</p>
</div>
</Base>
<script>
// Pre-fill code and handle from query params if provided
const params = new URLSearchParams(window.location.search);
const codeParam = params.get('code');
const handleParam = params.get('handle');
if (codeParam) (document.getElementById('code') as HTMLInputElement).value = codeParam.toUpperCase();
if (handleParam) (document.getElementById('handle') as HTMLInputElement).value = handleParam;
document.getElementById('reset-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const errEl = document.getElementById('reset-error')!;
const okEl = document.getElementById('reset-ok')!;
errEl.classList.add('hidden');
okEl.classList.add('hidden');
const body = {
code: (form.querySelector('#code') as HTMLInputElement).value.trim().toUpperCase(),
handle: (form.querySelector('#handle') as HTMLInputElement).value.trim().toLowerCase(),
password: (form.querySelector('#password') as HTMLInputElement).value,
};
try {
const r = await fetch('/api/auth/reset-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!r.ok) {
const d = await r.json().catch(() => ({}));
errEl.textContent = d.detail ?? 'Reset failed';
errEl.classList.remove('hidden');
return;
}
okEl.classList.remove('hidden');
(e.target as HTMLFormElement).querySelectorAll('input, button').forEach(
el => (el as HTMLInputElement).disabled = true
);
} catch {
errEl.textContent = 'Could not reach server';
errEl.classList.remove('hidden');
}
});
</script>