feat: enforce single active user session
Deploy Speaking Practice / deploy (push) Successful in 26s

This commit is contained in:
TTlaji committed 2026-06-15 14:40:33 +08:00
1 parent 0cf6f62e23
commit 0c12ce5f33
5 files changed
+109 -1

No files matched your search

+14
View File
@@ -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";
},
+17
View File
@@ -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()
+9
View File
@@ -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"]))
+3 -1
View File
@@ -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);
+66
View File
@@ -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()