From 0c12ce5f332f6cee1813ed9fedc9f635196815a2 Mon Sep 17 00:00:00 2001 From: TTlaji Date: Mon, 15 Jun 2026 14:40:33 +0800 Subject: [PATCH] feat: enforce single active user session --- auth.js | 14 ++++++++ backend/db.py | 17 +++++++++ backend/main.py | 9 +++++ tests/auth-ui-helpers.test.mjs | 4 ++- tests/auth_routes_test.py | 66 ++++++++++++++++++++++++++++++++++ 5 files changed, 109 insertions(+), 1 deletion(-) diff --git a/auth.js b/auth.js index 31f3781..51a49c2 100644 --- a/auth.js +++ b/auth.js @@ -32,6 +32,15 @@ return `./login.html?next=${encodeURIComponent(current)}`; } + function isUnauthorizedStatus(status) { + return Number(status) === 401; + } + + function redirectToLogin() { + clearSession(); + window.location.href = getLoginUrl(); + } + async function apiRequest(path, options = {}) { const headers = new Headers(options.headers || {}); if (options.body && !(options.body instanceof FormData) && !headers.has("Content-Type")) { @@ -49,6 +58,9 @@ } catch { message = response.statusText || message; } + if (isUnauthorizedStatus(response.status)) { + redirectToLogin(); + } throw new Error(message); } return response.json(); @@ -106,6 +118,7 @@ getLoginUrl, getStoredUser, getToken, + isUnauthorizedStatus, login, logout, register, @@ -119,6 +132,7 @@ getLoginUrlForPath(path) { return `./login.html?next=${encodeURIComponent(path)}`; }, + isUnauthorizedStatus, shouldShowAdminEntry(user) { return user?.role === "admin"; }, diff --git a/backend/db.py b/backend/db.py index 6d5f253..1968f48 100644 --- a/backend/db.py +++ b/backend/db.py @@ -91,6 +91,8 @@ def initialize_database() -> None: connection.execute("ALTER TABLE users ADD COLUMN is_active INTEGER NOT NULL DEFAULT 1") if "last_login_at" not in user_columns: connection.execute("ALTER TABLE users ADD COLUMN last_login_at TEXT") + if "session_token" not in user_columns: + connection.execute("ALTER TABLE users ADD COLUMN session_token TEXT") interaction_columns = { row["name"] for row in connection.execute("PRAGMA table_info(user_interactions)").fetchall() @@ -148,6 +150,7 @@ def row_to_user(row: sqlite3.Row) -> dict[str, object]: "createdAt": row["created_at"], "updatedAt": row["updated_at"], "lastLoginAt": row["last_login_at"] or "", + "sessionToken": row["session_token"] or "", } @@ -391,6 +394,20 @@ def mark_user_login(user_id: int) -> None: ) +def rotate_user_session_token(user_id: int, session_token: str) -> None: + with get_connection() as connection: + connection.execute( + """ + UPDATE users + SET session_token = ?, + last_login_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + """, + (session_token, user_id), + ) + + def register_user_with_activation(*, username: str, password_hash: str, activation_code: str) -> dict[str, object]: clean_username = repair_mojibake_text(username) clean_code = activation_code.strip().upper() diff --git a/backend/main.py b/backend/main.py index abf0662..b811533 100644 --- a/backend/main.py +++ b/backend/main.py @@ -34,6 +34,7 @@ from .db import ( mark_user_login, parse_tags, register_user_with_activation, + rotate_user_session_token, save_user_learning_state, table_names, get_video, @@ -237,11 +238,15 @@ def build_user_response(username: str, role: str, user_id: int | None = None) -> def create_session_payload(username: str, role: str, user_id: int | None = None) -> dict[str, object]: + session_token = secrets.token_urlsafe(32) if user_id else "" + if user_id: + rotate_user_session_token(user_id, session_token) token = create_auth_token( { "username": username, "role": role, "userId": user_id, + "sessionToken": session_token, }, get_token_secret(), ) @@ -262,11 +267,15 @@ def validate_bearer_session(token: str) -> dict[str, object] | None: return build_user_response(username, "admin", None) user_id = int(payload.get("userId") or 0) + session_token = str(payload.get("sessionToken") or "") user = get_user_by_id(user_id) if user_id else None if not user or not user["isActive"]: return None if user["username"] != username: return None + current_session_token = str(user.get("sessionToken") or "") + if current_session_token and current_session_token != session_token: + return None return build_user_response(str(user["username"]), str(user["role"]), int(user["id"])) diff --git a/tests/auth-ui-helpers.test.mjs b/tests/auth-ui-helpers.test.mjs index d1e0d85..485bf79 100644 --- a/tests/auth-ui-helpers.test.mjs +++ b/tests/auth-ui-helpers.test.mjs @@ -1,9 +1,11 @@ import assert from "node:assert/strict"; import authHelpers from "../auth.js"; -const { getLoginUrlForPath, shouldShowAdminEntry } = authHelpers; +const { getLoginUrlForPath, isUnauthorizedStatus, shouldShowAdminEntry } = authHelpers; assert.equal(getLoginUrlForPath("/study.html?video=2"), "./login.html?next=%2Fstudy.html%3Fvideo%3D2"); +assert.equal(isUnauthorizedStatus(401), true); +assert.equal(isUnauthorizedStatus(403), false); assert.equal(shouldShowAdminEntry({ role: "admin" }), true); assert.equal(shouldShowAdminEntry({ role: "user" }), false); assert.equal(shouldShowAdminEntry(null), false); diff --git a/tests/auth_routes_test.py b/tests/auth_routes_test.py index 658ce0b..741b4fb 100644 --- a/tests/auth_routes_test.py +++ b/tests/auth_routes_test.py @@ -105,6 +105,66 @@ def test_activation_registration_login_and_reuse_rejection(monkeypatch): raise AssertionError("used activation code should be rejected") +def test_new_user_login_invalidates_previous_bearer_token(monkeypatch): + configure_admin(monkeypatch) + + with TempDatabase(): + db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin") + main.api_auth_register(main.RegisterRequest( + activationCode="SL-ABC123-DEF456-GHI789", + username="student", + password="secret123", + )) + + first_login = main.api_auth_login(main.LoginRequest(username="student", password="secret123")) + first_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=first_login["token"]) + assert main.api_auth_session(main.require_session(first_bearer))["user"]["username"] == "student" + + second_login = main.api_auth_login(main.LoginRequest(username="student", password="secret123")) + second_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=second_login["token"]) + assert main.api_auth_session(main.require_session(second_bearer))["user"]["username"] == "student" + + try: + main.require_session(first_bearer) + except HTTPException as error: + assert error.status_code == 401 + else: + raise AssertionError("old bearer token should be invalid after a newer login") + + +def test_legacy_bearer_token_works_until_user_logs_in_again(monkeypatch): + configure_admin(monkeypatch) + + with TempDatabase(): + db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin") + registered = main.api_auth_register(main.RegisterRequest( + activationCode="SL-ABC123-DEF456-GHI789", + username="student", + password="secret123", + )) + legacy_token = main.create_auth_token( + {"username": "student", "role": "user", "userId": registered["user"]["id"]}, + main.get_token_secret(), + ) + with db.get_connection() as connection: + connection.execute( + "UPDATE users SET session_token = NULL WHERE id = ?", + (registered["user"]["id"],), + ) + + legacy_bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=legacy_token) + assert main.api_auth_session(main.require_session(legacy_bearer))["user"]["username"] == "student" + + main.api_auth_login(main.LoginRequest(username="student", password="secret123")) + + try: + main.require_session(legacy_bearer) + except HTTPException as error: + assert error.status_code == 401 + else: + raise AssertionError("legacy token should expire after the account logs in again") + + def test_normal_user_cannot_use_admin_dependency(monkeypatch): configure_admin(monkeypatch) @@ -137,6 +197,12 @@ if __name__ == "__main__": test_activation_registration_login_and_reuse_rejection(patch) patch.restore() configure_admin(patch) + test_new_user_login_invalidates_previous_bearer_token(patch) + patch.restore() + configure_admin(patch) + test_legacy_bearer_token_works_until_user_logs_in_again(patch) + patch.restore() + configure_admin(patch) test_normal_user_cannot_use_admin_dependency(patch) finally: patch.restore()