From e3576b4b3cb0428a6cc738289a66b7951a133320 Mon Sep 17 00:00:00 2001
From: nsfisis <nsfisis@gmail.com>
Date: Mon, 27 Apr 2026 07:10:41 +0900
Subject: fix(auth): redirect to login page on session expiry

Previously when the session expired, the API client cleared tokens but
the UI displayed "Invalid or expired token" instead of redirecting to
the login page. The root cause was that isAuthenticatedAtom was derived
from userAtom only as a re-evaluation trigger, while the actual value
came from apiClient.isAuthenticated(). On page reload userAtom is null,
so setting it to null on session expiry did not trigger a re-render and
ProtectedRoute never redirected.

Make userAtom (persisted via atomWithStorage) the single source of truth
for auth state, derive isAuthenticatedAtom from it, drop the redundant
apiClient.isAuthenticated(), and explicitly navigate to /login on
session expiry. Also trigger session expiry when a 401 comes back with
no refresh token available.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---
 src/client/pages/LoginPage.test.tsx | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

(limited to 'src/client/pages/LoginPage.test.tsx')

diff --git a/src/client/pages/LoginPage.test.tsx b/src/client/pages/LoginPage.test.tsx
index 6ed4011..b559bff 100644
--- a/src/client/pages/LoginPage.test.tsx
+++ b/src/client/pages/LoginPage.test.tsx
@@ -7,14 +7,13 @@ import { createStore, Provider } from "jotai";
 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
 import { Router } from "wouter";
 import { memoryLocation } from "wouter/memory-location";
-import { authLoadingAtom } from "../atoms";
+import { authLoadingAtom, userAtom } from "../atoms";
 import { LoginPage } from "./LoginPage";
 
 vi.mock("../api/client", () => ({
 	apiClient: {
 		login: vi.fn(),
 		logout: vi.fn(),
-		isAuthenticated: vi.fn(),
 		getTokens: vi.fn(),
 		onSessionExpired: vi.fn(() => vi.fn()),
 	},
@@ -49,7 +48,6 @@ describe("LoginPage", () => {
 	beforeEach(() => {
 		vi.clearAllMocks();
 		vi.mocked(apiClient.getTokens).mockReturnValue(null);
-		vi.mocked(apiClient.isAuthenticated).mockReturnValue(false);
 	});
 
 	afterEach(() => {
@@ -147,7 +145,6 @@ describe("LoginPage", () => {
 	});
 
 	it("redirects when already authenticated", async () => {
-		vi.mocked(apiClient.isAuthenticated).mockReturnValue(true);
 		vi.mocked(apiClient.getTokens).mockReturnValue({
 			accessToken: "access-token",
 			refreshToken: "refresh-token",
@@ -162,6 +159,7 @@ describe("LoginPage", () => {
 
 		const store = createStore();
 		store.set(authLoadingAtom, false);
+		store.set(userAtom, { id: "u1", username: "tester" });
 
 		render(
 			<Provider store={store}>
-- 
cgit v1.3-3-g829e

