From 9276064d18bf42b255aaad2b83144dc178a3b21b Mon Sep 17 00:00:00 2001 From: Atharv1705 Date: Tue, 17 Nov 2026 18:31:45 +0530 Subject: [PATCH] fix(task7): invalidate tokens on password change or reset --- backend/app/core/deps.py | 9 ++ backend/app/core/migrations.py | 5 +- backend/app/core/security.py | 2 + backend/app/models/masters.py | 1 + backend/app/routers/auth.py | 20 +++- backend/app/routers/users.py | 2 + backend/tests/test_task7_token_version.py | 91 +++++++++++++++++++ docs/ASSUMPTIONS.md | 1 + frontend/src/api/auth.ts | 8 +- .../src/components/ChangePasswordModal.tsx | 4 + frontend/src/hooks/useAuth.ts | 6 ++ 11 files changed, 145 insertions(+), 4 deletions(-) create mode 100644 backend/tests/test_task7_token_version.py diff --git a/backend/app/core/deps.py b/backend/app/core/deps.py index 98aeb22..6c6893b 100644 --- a/backend/app/core/deps.py +++ b/backend/app/core/deps.py @@ -31,6 +31,15 @@ def get_current_user( user = db.query(User).filter(User.id == user_id).first() if user is None or not user.is_active: raise credentials_exception + + token_tv = payload.get("tv", 0) + user_tv = getattr(user, "token_version", 0) + if token_tv != user_tv: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Token has been invalidated. Please log in again.", + headers={"WWW-Authenticate": "Bearer"}, + ) return user diff --git a/backend/app/core/migrations.py b/backend/app/core/migrations.py index cd1eb74..f481edc 100644 --- a/backend/app/core/migrations.py +++ b/backend/app/core/migrations.py @@ -38,7 +38,10 @@ def run_sqlite_migrations(engine: Engine) -> None: for col in table.columns: if col.name not in existing_cols: col_type = col.type.compile(engine.dialect) - sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}" + if col.name == "token_version": + sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} INTEGER DEFAULT 0 NOT NULL" + else: + sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}" logger.info("Auto-migrating SQLite: %s", sql) conn.exec_driver_sql(sql) except Exception: diff --git a/backend/app/core/security.py b/backend/app/core/security.py index 5e4acf3..f7878e3 100644 --- a/backend/app/core/security.py +++ b/backend/app/core/security.py @@ -92,6 +92,8 @@ def hash_password(plain: str) -> str: def create_access_token(data: dict, expires_minutes: int | None = None) -> str: to_encode = data.copy() + if "tv" not in to_encode: + to_encode["tv"] = 0 expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES) to_encode["exp"] = expire return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) diff --git a/backend/app/models/masters.py b/backend/app/models/masters.py index 836bd22..b248fa2 100644 --- a/backend/app/models/masters.py +++ b/backend/app/models/masters.py @@ -67,6 +67,7 @@ class User(Base): password_hash: Mapped[str] = mapped_column(String(255), nullable=False) role: Mapped[str] = mapped_column(String(50), nullable=False) department_id: Mapped[Optional[int]] = mapped_column(ForeignKey("departments.id"), nullable=True) + token_version: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False) is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False) diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index f8f06d5..0e16e47 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -83,7 +83,11 @@ def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db) detail="User account is inactive.", ) - token = create_access_token({"sub": str(user.id), "role": user.role}) + token = create_access_token({ + "sub": str(user.id), + "role": user.role, + "tv": user.token_version, + }) return TokenResponse( access_token=token, token_type="bearer", @@ -117,5 +121,17 @@ def change_password( ) validate_password(payload.new_password, email=current_user.email) current_user.password_hash = hash_password(payload.new_password) + current_user.token_version = (current_user.token_version or 0) + 1 db.commit() - return {"message": "Password changed successfully."} + db.refresh(current_user) + + new_token = create_access_token({ + "sub": str(current_user.id), + "role": current_user.role, + "tv": current_user.token_version, + }) + return { + "message": "Password changed successfully.", + "access_token": new_token, + "token_type": "bearer", + } diff --git a/backend/app/routers/users.py b/backend/app/routers/users.py index 783162e..bc40f47 100644 --- a/backend/app/routers/users.py +++ b/backend/app/routers/users.py @@ -180,6 +180,7 @@ def update_user( if password is not None and password != "": validate_password(password, email=data.get("email", user.email)) user.password_hash = hash_password(password) + user.token_version = (user.token_version or 0) + 1 for k, v in data.items(): setattr(user, k, v) @@ -243,5 +244,6 @@ def reset_user_password( raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.") validate_password(payload.new_password, email=user.email) user.password_hash = hash_password(payload.new_password) + user.token_version = (user.token_version or 0) + 1 db.commit() return {"message": f"Password for {user.name} has been reset successfully."} diff --git a/backend/tests/test_task7_token_version.py b/backend/tests/test_task7_token_version.py new file mode 100644 index 0000000..72ddd2f --- /dev/null +++ b/backend/tests/test_task7_token_version.py @@ -0,0 +1,91 @@ +import pytest +from app.models import User +from app.seed.seed import seed_database + + +@pytest.fixture(scope="module", autouse=True) +def seeded_task7_db(db, tmp_path_factory): + upload_dir = tmp_path_factory.mktemp("task7_test_uploads") + seed_database(db, upload_dir=upload_dir) + return upload_dir + + +def test_token_invalidation_on_change_password_and_admin_reset(client, db): + # 1. Login as user and save the initial token + user_email = "bio@poona.demo" + login_res = client.post( + "/api/auth/login", + json={"email": user_email, "password": "Demo@123"}, + ) + assert login_res.status_code == 200 + old_token = login_res.json()["access_token"] + + # Verify initial token works + me_res1 = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {old_token}"}, + ) + assert me_res1.status_code == 200 + assert me_res1.json()["email"] == user_email + + # 2. Call POST /api/auth/change-password + change_res = client.post( + "/api/auth/change-password", + headers={"Authorization": f"Bearer {old_token}"}, + json={"current_password": "Demo@123", "new_password": "NewSecurePass99"}, + ) + assert change_res.status_code == 200, change_res.text + change_data = change_res.json() + assert "access_token" in change_data + assert change_data["token_type"] == "bearer" + new_token = change_data["access_token"] + + # 3. Assert the old token now gets 401 on an authenticated endpoint + old_token_res = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {old_token}"}, + ) + assert old_token_res.status_code == 401 + assert "Token has been invalidated" in old_token_res.json()["detail"] + + # 4. Assert the new token returned by change-password works + new_token_res = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {new_token}"}, + ) + assert new_token_res.status_code == 200 + assert new_token_res.json()["email"] == user_email + + # 5. Login as admin, reset that user's password + admin_login = client.post( + "/api/auth/login", + json={"email": "admin@poona.demo", "password": "Demo@123"}, + ) + assert admin_login.status_code == 200 + admin_token = admin_login.json()["access_token"] + + target_user = db.query(User).filter(User.email == user_email).first() + assert target_user is not None + + reset_res = client.post( + f"/api/users/{target_user.id}/reset-password", + headers={"Authorization": f"Bearer {admin_token}"}, + json={"new_password": "AdminResetPass88"}, + ) + assert reset_res.status_code == 200, reset_res.text + + # 6. Assert the user's token now gets 401 + user_after_reset_res = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {new_token}"}, + ) + assert user_after_reset_res.status_code == 401 + assert "Token has been invalidated" in user_after_reset_res.json()["detail"] + + # 7. Assert the admin's own token is still valid + admin_me_res = client.get( + "/api/auth/me", + headers={"Authorization": f"Bearer {admin_token}"}, + ) + assert admin_me_res.status_code == 200 + assert admin_me_res.json()["role"] == "system_admin" diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index 974a11e..7585f0a 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -51,3 +51,4 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her - Password changes additionally require that the new password is not identical to the current password. 28. **Admin Reset Password Interface (Task 5)**: `frontend/src/api/users.ts` and `frontend/src/pages/MastersPage.tsx` expose an administrator password reset modal for users with role `system_admin`. The dialog features password masking toggles, client-side mismatch validation (`Passwords do not match`), universal password policy helper instructions, and displays backend 422 validation errors inline. Successful resets trigger a notification toast and close the modal without affecting the active administrator session. 29. **Department User Scoping & Empty Scope Resolution (Task 6)**: `backend/app/services/scoping.py` implements `resolve_department_scope(user, requested_dept_id)`. Non-department roles are unconstrained and may optionally filter by `requested_dept_id`. Assigned `department_user` accounts are strictly bound to `user.department_id`, ignoring any client-requested department parameter. Unassigned `department_user` accounts (`department_id=None`) resolve to `is_empty=True`, immediately returning 0 counters on Dashboard summary, empty results on global search, and empty row lists across all accessible report endpoints without running hospital-wide queries. Report key aliases are registered to support both canonical paths and audit identifiers (e.g., `equipment-inventory`, `condemned-equipment`, `pm-schedule`). +30. **Token Versioning & Session Invalidation (Task 7)**: A `token_version` integer column (default 0, not null) is added to `users` and reconciled automatically via `run_sqlite_migrations`. Access tokens encode the user's `token_version` in claim `"tv"`. `get_current_user` rejects tokens with mismatched `"tv"` with HTTP 401 (`Token has been invalidated. Please log in again.`). Password changes and administrator password resets increment `user.token_version`, invalidating previous tokens. `POST /api/auth/change-password` returns a renewed access token, and `ChangePasswordModal.tsx` stores the new token in the active auth store to keep the user's session active without re-login. diff --git a/frontend/src/api/auth.ts b/frontend/src/api/auth.ts index 7aca0a5..67befa1 100644 --- a/frontend/src/api/auth.ts +++ b/frontend/src/api/auth.ts @@ -26,8 +26,14 @@ export function fetchMeApi() { return api.get("/auth/me"); } +export interface ChangePasswordResponse { + message: string; + access_token?: string; + token_type?: string; +} + export function changePasswordApi(current_password: string, new_password: string) { - return api.post<{ message: string }>("/auth/change-password", { + return api.post("/auth/change-password", { current_password, new_password, }); diff --git a/frontend/src/components/ChangePasswordModal.tsx b/frontend/src/components/ChangePasswordModal.tsx index fd700f9..416a03d 100644 --- a/frontend/src/components/ChangePasswordModal.tsx +++ b/frontend/src/components/ChangePasswordModal.tsx @@ -5,6 +5,7 @@ import { ApiError } from "@/api/client"; import { Modal } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { toast } from "@/lib/toast"; +import { useAuthStore } from "@/hooks/useAuth"; interface ChangePasswordModalProps { open: boolean; @@ -55,6 +56,9 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) setLoading(true); try { const res = await changePasswordApi(currentPassword, newPassword); + if (res.access_token) { + useAuthStore.getState().setToken(res.access_token); + } toast.success(res.message || "Password changed successfully."); handleClose(); } catch (err) { diff --git a/frontend/src/hooks/useAuth.ts b/frontend/src/hooks/useAuth.ts index 297af75..bca69a6 100644 --- a/frontend/src/hooks/useAuth.ts +++ b/frontend/src/hooks/useAuth.ts @@ -8,6 +8,7 @@ interface AuthState { demoAsOfDate: string | null; hydrating: boolean; setAuth: (user: UserOut, token: string) => void; + setToken: (token: string) => void; setDemoAsOfDate: (date: string | null) => void; hydrate: () => Promise; logout: () => void; @@ -31,6 +32,11 @@ export const useAuthStore = create((set, get) => ({ }); }, + setToken: (token) => { + sessionStorage.setItem("access_token", token); + set({ token }); + }, + setDemoAsOfDate: (date) => { set((state) => ({ demoAsOfDate: date || null,