SurfSense/surfsense_web/lib/auth-utils.ts
Claude 1a83d6a3ef
Extract AUTH_TOKEN_KEY constant to improve maintainability
- Create lib/constants.ts with AUTH_TOKEN_KEY
- Update auth-utils.ts to use constant
- Update use-user.ts, use-chats.ts, use-search-space.ts
- Update base-api.service.ts

This prevents typos and makes future updates simpler
across the application per PR review feedback.
2025-11-18 21:49:56 +00:00

44 lines
1.4 KiB
TypeScript

/**
* Authentication utility functions for session management
*/
import { baseApiService } from "./apis/base-api.service";
import { AUTH_TOKEN_KEY } from "./constants";
/**
* Handle session expiration by clearing tokens and redirecting to login
* This centralizes the 401 handling logic to avoid code duplication
*/
export function handleSessionExpired(): never {
// Clear token from localStorage
localStorage.removeItem(AUTH_TOKEN_KEY);
// Clear token from baseApiService singleton to prevent stale auth state
baseApiService.setBearerToken("");
// Redirect to login with error parameter for user feedback
window.location.href = "/login?error=session_expired";
// Throw to stop further execution (this line won't actually run due to redirect)
throw new Error("Session expired: Redirecting to login page");
}
/**
* Check if a response indicates an authentication error
* @param response - The fetch Response object
* @returns True if the response status is 401
*/
export function isUnauthorizedResponse(response: Response): boolean {
return response.status === 401;
}
/**
* Handle API response with automatic session expiration handling
* @param response - The fetch Response object
* @throws Error if response is 401 (after handling session expiration)
*/
export function handleAuthResponse(response: Response): void {
if (isUnauthorizedResponse(response)) {
handleSessionExpired();
}
}