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 }) {
+ {user?.must_change_password && location.pathname !== '/profile' && ( + + + {t('auth.must_change_banner')} + + )} {children}
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index 9e106db..12ee9cd 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -21,7 +21,8 @@ "change_password": "Change Password", "current_password": "Current Password", "new_password": "New Password", - "ethics_notice": "Authorized security-awareness training only." + "ethics_notice": "Authorized security-awareness training only.", + "must_change_banner": "An administrator reset your password. Choose your own password now in Profile." }, "nav": { "dashboard": "Dashboard", @@ -781,5 +782,22 @@ "discarded": "Discarded", "approve_failed": "Approve failed", "discard_failed": "Discard failed" + }, + "users": { + "reset": { + "title": "Reset password", + "help": "Set a new password for @{{username}}. Every session of this account is signed out. Share the new password through a separate channel.", + "new_password": "New password", + "policy": "Min. 8 characters · one uppercase letter · one number", + "generate": "Generate a strong password", + "show": "Show password", + "hide": "Hide password", + "require_change": "Require the user to choose their own password after signing in", + "submit": "Reset password", + "saving": "Saving...", + "cancel": "Cancel", + "done": "Password for @{{username}} was reset", + "pending_badge": "Must change password" + } } } diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json index 3485f54..0bb15d9 100644 --- a/frontend/src/i18n/locales/id.json +++ b/frontend/src/i18n/locales/id.json @@ -21,7 +21,8 @@ "change_password": "Ubah Kata Sandi", "current_password": "Kata Sandi Saat Ini", "new_password": "Kata Sandi Baru", - "ethics_notice": "Hanya untuk pelatihan kesadaran keamanan yang berizin." + "ethics_notice": "Hanya untuk pelatihan kesadaran keamanan yang berizin.", + "must_change_banner": "Administrator telah me-reset kata sandi Anda. Silakan ganti dengan kata sandi Anda sendiri di Profil." }, "nav": { "dashboard": "Dasbor", @@ -781,5 +782,22 @@ "discarded": "Dibuang", "approve_failed": "Gagal menyetujui", "discard_failed": "Gagal membuang" + }, + "users": { + "reset": { + "title": "Reset kata sandi", + "help": "Atur kata sandi baru untuk @{{username}}. Semua sesi akun ini akan dikeluarkan. Sampaikan kata sandi baru lewat jalur terpisah.", + "new_password": "Kata sandi baru", + "policy": "Min. 8 karakter · satu huruf besar · satu angka", + "generate": "Buat kata sandi kuat", + "show": "Tampilkan kata sandi", + "hide": "Sembunyikan kata sandi", + "require_change": "Wajibkan pengguna mengganti kata sandi sendiri setelah login", + "submit": "Reset kata sandi", + "saving": "Menyimpan...", + "cancel": "Batal", + "done": "Kata sandi @{{username}} berhasil di-reset", + "pending_badge": "Wajib ganti sandi" + } } } diff --git a/frontend/src/pages/ProfilePage.js b/frontend/src/pages/ProfilePage.js index 6be5bba..f0c202d 100644 --- a/frontend/src/pages/ProfilePage.js +++ b/frontend/src/pages/ProfilePage.js @@ -14,6 +14,7 @@ import SectionCard from '../components/SectionCard'; import StatCard from '../components/StatCard'; import { useApi, useMutation } from '../hooks/useApi'; import api from '../services/api'; +import { useAuth } from '../contexts/AuthContext'; // Level thresholds mirror backend gamification.py LEVEL_THRESHOLDS const LEVEL_THRESHOLDS = [0, 100, 300, 600, 1000, 1500, 2200, 3000, 4000, 5500, 7500, 10000]; @@ -65,6 +66,7 @@ function BadgeCard({ badge, earned }) { function PasswordChangeForm({ t }) { const [form, setForm] = useState({ current: '', next: '', confirm: '' }); const { mutate, loading } = useMutation('post', '/auth/change-password'); + const { user, login } = useAuth(); const update = (field) => (e) => setForm((prev) => ({ ...prev, [field]: e.target.value })); @@ -75,7 +77,9 @@ function PasswordChangeForm({ t }) { return; } try { - await mutate({ current_password: form.current, new_password: form.next }); + const res = await mutate({ current_password: form.current, new_password: form.next }); + // Changing the password signs out every other session; keep this one on the fresh token. + if (res?.token) login(res.token, { ...user, must_change_password: false }); toast.success(t('auth.password_changed')); setForm({ current: '', next: '', confirm: '' }); } catch (err) { diff --git a/frontend/src/pages/UsersPage.js b/frontend/src/pages/UsersPage.js index 44f9ed2..cf6242f 100644 --- a/frontend/src/pages/UsersPage.js +++ b/frontend/src/pages/UsersPage.js @@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next'; import { toast } from 'sonner'; import { Users, Search, Shield, User, Flame, Award, ChevronRight, - UserCog, AlertTriangle, CheckCircle2, X, RefreshCw, Plus, Eye, EyeOff + UserCog, AlertTriangle, CheckCircle2, X, RefreshCw, Plus, Eye, EyeOff, KeyRound, Dices } from 'lucide-react'; import { Button } from '../components/ui/button'; import { Input } from '../components/ui/input'; @@ -133,13 +133,100 @@ function CreateUserModal({ onClose, onCreated, isAdmin }) { ); } +// A random password that satisfies the policy (8+ chars, an uppercase letter, a digit). +function generatePassword() { + const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'; + const bytes = new Uint32Array(14); + window.crypto.getRandomValues(bytes); + const body = Array.from(bytes, (b) => chars[b % chars.length]).join(''); + return `${body.slice(0, 6)}-${body.slice(6, 12)}-${'ABCDEFGHJKLMNPQRSTUVWXYZ'[bytes[12] % 24]}${2 + (bytes[13] % 8)}`; +} + +function ResetPasswordModal({ target, onClose }) { + const { t } = useTranslation(); + const [password, setPassword] = useState(''); + const [show, setShow] = useState(false); + const [requireChange, setRequireChange] = useState(true); + const [loading, setLoading] = useState(false); + + const handleSubmit = async (e) => { + e.preventDefault(); + setLoading(true); + try { + await api.post(`/auth/users/${target.id}/reset-password`, { + new_password: password, require_change: requireChange, + }); + toast.success(t('users.reset.done', { username: target.username })); + onClose(); + } catch (err) { + toast.error(err.response?.data?.detail || t('errors.generic')); + } finally { + setLoading(false); + } + }; + + return ( +
+
+
+

+ {t('users.reset.title')} +

+ +
+

+ {t('users.reset.help', { username: target.username })} +

+
+
+ +
+
+ setPassword(e.target.value)} className="font-mono pr-9" required /> + +
+ +
+

{t('users.reset.policy')}

+
+ +
+ + +
+
+
+
+ ); +} + const ROLE_BADGE = { admin: { label: 'Admin', color: 'text-red-400 border-red-400/30 bg-red-400/5' }, trainer: { label: 'Trainer', color: 'text-yellow-400 border-yellow-400/30 bg-yellow-400/5' }, user: { label: 'User', color: 'text-primary/60 border-primary/20 bg-primary/5' }, }; -function UserRow({ user, onPromote, isAdmin }) { +function UserRow({ user, onPromote, onReset, isAdmin }) { + const { t } = useTranslation(); const badge = ROLE_BADGE[user.role] || ROLE_BADGE.user; return ( @@ -158,6 +245,11 @@ function UserRow({ user, onPromote, isAdmin }) { {badge.label} + {user.must_change_password && ( + + {t('users.reset.pending_badge')} + + )}

@{user.username} @@ -204,6 +296,14 @@ function UserRow({ user, onPromote, isAdmin }) { Revoke Trainer ) : null} + )} @@ -223,6 +323,7 @@ export default function UsersPage() { const [roleFilter, setRoleFilter] = useState('all'); const [refreshKey, setRefreshKey] = useState(0); const [showCreateModal, setShowCreateModal] = useState(false); + const [resetTarget, setResetTarget] = useState(null); const endpoint = `/instructor/users/all${roleFilter !== 'all' ? `?role=${roleFilter}` : ''}`; const { data: usersRaw, loading, refetch } = useApi(endpoint, { deps: [refreshKey, roleFilter] }); @@ -341,6 +442,7 @@ export default function UsersPage() { key={u.id} user={u} onPromote={handlePromote} + onReset={setResetTarget} isAdmin={isAdmin} /> ))} @@ -385,6 +487,12 @@ export default function UsersPage() { + {resetTarget && ( + { setResetTarget(null); setRefreshKey(k => k + 1); }} + /> + )} {showCreateModal && (