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/components/ProtectedRoute.test.tsx | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)

(limited to 'src/client/components/ProtectedRoute.test.tsx')

diff --git a/src/client/components/ProtectedRoute.test.tsx b/src/client/components/ProtectedRoute.test.tsx
index 64a0678..0cf97e3 100644
--- a/src/client/components/ProtectedRoute.test.tsx
+++ b/src/client/components/ProtectedRoute.test.tsx
@@ -6,14 +6,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 { ProtectedRoute } from "./ProtectedRoute";
 
 vi.mock("../api/client", () => ({
 	apiClient: {
 		login: vi.fn(),
 		logout: vi.fn(),
-		isAuthenticated: vi.fn(),
 		getTokens: vi.fn(),
 		onSessionExpired: vi.fn(() => vi.fn()),
 	},
@@ -29,20 +28,17 @@ vi.mock("../api/client", () => ({
 	},
 }));
 
-import { apiClient } from "../api/client";
-
 function renderWithProvider(
 	path: string,
 	atomValues: { isAuthenticated: boolean; isLoading: boolean },
 ) {
-	// Mock the apiClient.isAuthenticated to control isAuthenticatedAtom value
-	vi.mocked(apiClient.isAuthenticated).mockReturnValue(
-		atomValues.isAuthenticated,
-	);
-
 	const { hook } = memoryLocation({ path });
 	const store = createStore();
 	store.set(authLoadingAtom, atomValues.isLoading);
+	store.set(
+		userAtom,
+		atomValues.isAuthenticated ? { id: "u1", username: "tester" } : null,
+	);
 
 	return render(
 		<Provider store={store}>
-- 
cgit v1.3-3-g829e

