diff --git a/backend/models/schemas.py b/backend/models/schemas.py index 875ea9e..6f5822b 100644 --- a/backend/models/schemas.py +++ b/backend/models/schemas.py @@ -20,6 +20,10 @@ class User(BaseModel): avatar_url: str | None = None created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) is_active: bool = True + # Bumped whenever the password changes; tokens carrying an older value are + # rejected, which ends every existing session of this user. + token_version: int = 0 + must_change_password: bool = False # set when an admin resets the password # Gamification xp: int = 0 level: int = 1 @@ -54,6 +58,12 @@ class PasswordChangeRequest(BaseModel): new_password: str +class AdminPasswordResetRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + new_password: str = Field(min_length=1, max_length=128) + require_change: bool = True # user must pick their own password after logging in + + class ProfileUpdateRequest(BaseModel): display_name: str | None = None email: str | None = None diff --git a/backend/routes/auth.py b/backend/routes/auth.py index c8dd826..f18a342 100644 --- a/backend/routes/auth.py +++ b/backend/routes/auth.py @@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends, HTTPException from models.schemas import ( + AdminPasswordResetRequest, LoginRequest, LoginResponse, PasswordChangeRequest, @@ -10,7 +11,14 @@ RegisterRequest, User, ) -from services.auth import create_token, get_current_user, hash_password, verify_password +from services import audit +from services.auth import ( + create_token, + get_current_user, + hash_password, + require_admin, + verify_password, +) from services.database import db from services.gamification import award_xp @@ -91,7 +99,7 @@ async def login(request: LoginRequest): raise HTTPException(status_code=401, detail="Invalid credentials") user = User(**user_doc) - token = create_token(user.id) + token = create_token(user.id, user.token_version) # Update last_active and check streak await award_xp(user.id, 0, check_streak=True) @@ -109,6 +117,7 @@ async def login(request: LoginRequest): "badges": user.badges, "streak_days": user.streak_days, "theme": user.theme, + "must_change_password": user.must_change_password, "created_at": user.created_at.isoformat(), }, ) @@ -129,6 +138,7 @@ async def get_me(current_user: User = Depends(get_current_user)): "streak_days": current_user.streak_days, "theme": current_user.theme, "notifications_enabled": current_user.notifications_enabled, + "must_change_password": current_user.must_change_password, "created_at": current_user.created_at.isoformat(), } @@ -190,9 +200,68 @@ async def change_password( if pw_error: raise HTTPException(status_code=400, detail=pw_error) - new_hash = hash_password(request.new_password) - await db.users.update_one({"id": current_user.id}, {"$set": {"password_hash": new_hash}}) - return {"message": "Password changed successfully"} + if verify_password(request.new_password, current_user.password_hash): + raise HTTPException(status_code=400, detail="New password must differ from the current one") + + # Bumping token_version signs out every other session; this one gets a fresh token. + updated = await db.users.find_one_and_update( + {"id": current_user.id}, + { + "$set": { + "password_hash": hash_password(request.new_password), + "must_change_password": False, + }, + "$inc": {"token_version": 1}, + }, + return_document=True, + projection={"_id": 0, "token_version": 1}, + ) + await audit.record(current_user.id, "auth.password.change", current_user.id) + return { + "message": "Password changed successfully", + "token": create_token(current_user.id, updated["token_version"]), + } + + +@router.post("/users/{user_id}/reset-password") +async def reset_user_password( + user_id: str, + request: AdminPasswordResetRequest, + current_user: User = Depends(require_admin), +): + """Admin sets a new password for another account and signs out its sessions.""" + if user_id == current_user.id: + raise HTTPException(status_code=400, detail="Use change-password for your own account") + target = await db.users.find_one({"id": user_id}, {"_id": 0}) + if not target: + raise HTTPException(status_code=404, detail="User not found") + if target.get("role") == "admin": + raise HTTPException(status_code=403, detail="Cannot reset another admin's password") + + pw_error = validate_password(request.new_password) + if pw_error: + raise HTTPException(status_code=400, detail=pw_error) + + await db.users.update_one( + {"id": user_id}, + { + "$set": { + "password_hash": hash_password(request.new_password), + "must_change_password": request.require_change, + }, + "$inc": {"token_version": 1}, + }, + ) + # The password itself is never logged. + await audit.record( + current_user.id, + "auth.password.reset", + user_id, + {"username": target["username"], "require_change": request.require_change}, + ) + return { + "message": f"Password for '{target['username']}' was reset; their sessions were signed out" + } @router.post("/create-user") diff --git a/backend/services/auth.py b/backend/services/auth.py index f3bed76..595d512 100644 --- a/backend/services/auth.py +++ b/backend/services/auth.py @@ -43,9 +43,9 @@ def verify_password(password: str, password_hash: str) -> bool: return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8")) -def create_token(user_id: str) -> str: +def create_token(user_id: str, token_version: int = 0) -> str: expiration = datetime.now(UTC) + timedelta(hours=JWT_EXPIRATION_HOURS) - payload = {"user_id": user_id, "exp": expiration} + payload = {"user_id": user_id, "tv": token_version, "exp": expiration} return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM) @@ -60,6 +60,10 @@ async def get_current_user( user_doc = await db.users.find_one({"id": user_id}, {"_id": 0}) if not user_doc: raise HTTPException(status_code=401, detail="User not found") + # Tokens issued before the last password change are revoked. Tokens + # minted before token_version existed carry no "tv" and count as 0. + if payload.get("tv", 0) != user_doc.get("token_version", 0): + raise HTTPException(status_code=401, detail="Session revoked, please sign in again") return User(**user_doc) except jwt.ExpiredSignatureError: diff --git a/backend/tests/test_password_reset.py b/backend/tests/test_password_reset.py new file mode 100644 index 0000000..9f691c1 --- /dev/null +++ b/backend/tests/test_password_reset.py @@ -0,0 +1,131 @@ +"""Admin password reset and session revocation via token_version.""" + +from datetime import UTC, datetime, timedelta + +import jwt + +from services.auth import JWT_ALGORITHM, JWT_SECRET +from services.database import db +from tests.conftest import make_user + +NEW = "Fresh-Pass-2026" + + +async def _login(api, username, password): + return await api.post("/api/auth/login", json={"username": username, "password": password}) + + +async def test_admin_resets_password_and_signs_out_sessions(api): + _, admin = await make_user("admin") + target, old_session = await make_user("user") + assert (await api.get("/api/auth/me", headers=old_session)).status_code == 200 + + r = await api.post( + f"/api/auth/users/{target.id}/reset-password", json={"new_password": NEW}, headers=admin + ) + assert r.status_code == 200, r.text + + r = await api.get("/api/auth/me", headers=old_session) + assert r.status_code == 401 and "revoked" in r.json()["detail"] + assert (await _login(api, target.username, "Password123")).status_code == 401 + + r = await _login(api, target.username, NEW) + assert r.status_code == 200 + assert r.json()["user"]["must_change_password"] is True + me = await api.get("/api/auth/me", headers={"Authorization": f"Bearer {r.json()['token']}"}) + assert me.status_code == 200 and me.json()["must_change_password"] is True + + entry = await db.audit_log.find_one({"action": "auth.password.reset", "target": target.id}) + assert entry and entry["details"] == {"username": target.username, "require_change": True} + assert NEW not in str(entry) + + +async def test_reset_without_forced_change(api): + _, admin = await make_user("admin") + target, _ = await make_user("trainer") + r = await api.post( + f"/api/auth/users/{target.id}/reset-password", + json={"new_password": NEW, "require_change": False}, + headers=admin, + ) + assert r.status_code == 200 + assert (await _login(api, target.username, NEW)).json()["user"]["must_change_password"] is False + + +async def test_only_admin_can_reset(api): + target, _ = await make_user("user") + for role in ("user", "trainer"): + _, h = await make_user(role) + r = await api.post( + f"/api/auth/users/{target.id}/reset-password", json={"new_password": NEW}, headers=h + ) + assert r.status_code == 403, role + + +async def test_reset_refuses_admins_self_weak_and_unknown(api): + me, admin = await make_user("admin") + other_admin, _ = await make_user("admin") + + def reset(uid, pw=NEW): + return api.post( + f"/api/auth/users/{uid}/reset-password", json={"new_password": pw}, headers=admin + ) + + assert (await reset(other_admin.id)).status_code == 403 + assert (await reset(me.id)).status_code == 400 + assert (await reset("no-such-user")).status_code == 404 + target, _ = await make_user("user") + r = await reset(target.id, "short") + assert r.status_code == 400 and "8 characters" in r.json()["detail"] + extra = await api.post( + f"/api/auth/users/{target.id}/reset-password", + json={"new_password": NEW, "role": "admin"}, + headers=admin, + ) + assert extra.status_code == 422 + + +async def test_change_password_returns_new_token_and_clears_flag(api): + _, admin = await make_user("admin") + target, _ = await make_user("user") + await api.post( + f"/api/auth/users/{target.id}/reset-password", json={"new_password": NEW}, headers=admin + ) + first = {"Authorization": f"Bearer {(await _login(api, target.username, NEW)).json()['token']}"} + second = { + "Authorization": f"Bearer {(await _login(api, target.username, NEW)).json()['token']}" + } + + same = await api.post( + "/api/auth/change-password", + json={"current_password": NEW, "new_password": NEW}, + headers=first, + ) + assert same.status_code == 400 + + r = await api.post( + "/api/auth/change-password", + json={"current_password": NEW, "new_password": "Mine-Own-2026"}, + headers=first, + ) + assert r.status_code == 200 + fresh = {"Authorization": f"Bearer {r.json()['token']}"} + + me = await api.get("/api/auth/me", headers=fresh) + assert me.status_code == 200 and me.json()["must_change_password"] is False + assert (await api.get("/api/auth/me", headers=first)).status_code == 401 + assert (await api.get("/api/auth/me", headers=second)).status_code == 401 + + +async def test_tokens_from_before_token_version_still_work(api): + user, _ = await make_user("user") + await db.users.update_one( + {"id": user.id}, {"$unset": {"token_version": "", "must_change_password": ""}} + ) + legacy = jwt.encode( + {"user_id": user.id, "exp": datetime.now(UTC) + timedelta(hours=1)}, + JWT_SECRET, + algorithm=JWT_ALGORITHM, + ) + r = await api.get("/api/auth/me", headers={"Authorization": f"Bearer {legacy}"}) + assert r.status_code == 200 and r.json()["must_change_password"] is False diff --git a/docs/api.md b/docs/api.md index ae52f82..ceae019 100644 --- a/docs/api.md +++ b/docs/api.md @@ -14,7 +14,8 @@ Roles: **U** = any authenticated user, **T** = trainer or admin, **A** = admin. | POST | `/login` | – | Returns a token + user | | GET | `/me` | U | Current user | | PUT | `/profile` | U | Update display name/email/theme | -| POST | `/change-password` | U | | +| POST | `/change-password` | U | Returns a fresh token; signs out the user's other sessions | +| POST | `/users/{id}/reset-password` | A | Set another non-admin user's password, sign out their sessions, optionally require a change at next login; audited without the password | | POST | `/promote` | A | Change another user's role | | POST | `/create-user` | T | Trainers create user-role accounts; admins any | diff --git a/frontend/src/components/Layout.js b/frontend/src/components/Layout.js index 773dd79..ccd3a0e 100644 --- a/frontend/src/components/Layout.js +++ b/frontend/src/components/Layout.js @@ -8,7 +8,7 @@ import { Terminal, LayoutDashboard, FileCode, ListChecks, Activity, Settings, LogOut, BookOpen, Trophy, BarChart3, Flag, Pencil, Sun, Moon, User, Globe, Menu, X, Users, ClipboardList, ShieldAlert, Radio, Target, Inbox, MessageSquare, PenLine, - Shield, ShieldCheck, UserCog, History, BookMarked, Share2, + Shield, ShieldCheck, UserCog, History, BookMarked, Share2, KeyRound, } from 'lucide-react'; const LANGUAGES = [ @@ -382,6 +382,13 @@ export default function Layout({ children, onLogout }) {
+ {t('users.reset.help', { username: target.username })} +
+ +
@{user.username}
@@ -204,6 +296,14 @@ function UserRow({ user, onPromote, isAdmin }) {