Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions backend/models/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
79 changes: 74 additions & 5 deletions backend/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,22 @@
from fastapi import APIRouter, Depends, HTTPException

from models.schemas import (
AdminPasswordResetRequest,
LoginRequest,
LoginResponse,
PasswordChangeRequest,
ProfileUpdateRequest,
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

Expand Down Expand Up @@ -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)
Expand All @@ -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(),
},
)
Expand All @@ -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(),
}

Expand Down Expand Up @@ -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")
Expand Down
8 changes: 6 additions & 2 deletions backend/services/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand All @@ -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:
Expand Down
131 changes: 131 additions & 0 deletions backend/tests/test_password_reset.py
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
9 changes: 8 additions & 1 deletion frontend/src/components/Layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -382,6 +382,13 @@ export default function Layout({ children, onLogout }) {
<div className="lg:ml-72 min-h-screen relative z-10">
<div className="pt-14 lg:pt-0">
<div className="p-4 md:p-8 max-w-7xl mx-auto">
{user?.must_change_password && location.pathname !== '/profile' && (
<Link to="/profile"
className="mb-4 flex items-center gap-2 border border-amber-400/40 bg-amber-400/10 px-3 py-2 text-sm text-amber-300 hover:bg-amber-400/15">
<KeyRound className="w-4 h-4 flex-shrink-0" />
<span>{t('auth.must_change_banner')}</span>
</Link>
)}
{children}
</div>
</div>
Expand Down
20 changes: 19 additions & 1 deletion frontend/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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"
}
}
}
20 changes: 19 additions & 1 deletion frontend/src/i18n/locales/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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"
}
}
}
Loading
Loading