refactor: centralize authentication handling

- Replaced direct localStorage token access with a centralized `getBearerToken` function across various components and hooks to improve code maintainability and security.
- Updated API calls to use `authenticatedFetch` for consistent authentication handling.
- Enhanced user experience by ensuring proper redirection to login when authentication fails.
- Cleaned up unused imports and improved overall code structure for better readability.
This commit is contained in:
DESKTOP-RTLN3BA\$punk 2025-12-02 01:24:09 -08:00
parent 6cc9e38e1d
commit b2a97b39ce
35 changed files with 396 additions and 497 deletions

View file

@ -2,6 +2,7 @@
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { authenticatedFetch } from "@/lib/auth-utils";
interface User {
id: string;
@ -25,19 +26,10 @@ export function useUser() {
if (typeof window === "undefined") return;
setLoading(true);
const response = await fetch(`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/users/me`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("surfsense_bearer_token")}`,
},
method: "GET",
});
if (response.status === 401) {
// Clear token and redirect to home
localStorage.removeItem("surfsense_bearer_token");
window.location.href = "/";
throw new Error("Unauthorized: Redirecting to login page");
}
const response = await authenticatedFetch(
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/users/me`,
{ method: "GET" }
);
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.status}`);