mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-07-22 23:31:12 +02:00
- Add baseApiService token clearing on 401 in use-user.ts - Add baseApiService token clearing on 401 in use-chats.ts (both fetchChats and deleteChat) - Add baseApiService token clearing on 401 in use-search-space.ts - Update all redirects to /login?error=session_expired for better UX - Add session_expired error message to auth-errors.ts This ensures consistent session invalidation across all API hooks, preventing stale auth state in the baseApiService singleton.
64 lines
1.6 KiB
TypeScript
64 lines
1.6 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState } from "react";
|
|
import { toast } from "sonner";
|
|
import { baseApiService } from "@/lib/apis/base-api.service";
|
|
|
|
interface User {
|
|
id: string;
|
|
email: string;
|
|
is_active: boolean;
|
|
is_superuser: boolean;
|
|
is_verified: boolean;
|
|
pages_limit: number;
|
|
pages_used: number;
|
|
}
|
|
|
|
export function useUser() {
|
|
const [user, setUser] = useState<User | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
const fetchUser = async () => {
|
|
try {
|
|
// Only run on client-side
|
|
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 from both localStorage and baseApiService
|
|
localStorage.removeItem("surfsense_bearer_token");
|
|
baseApiService.setBearerToken("");
|
|
// Redirect to login with session expired message
|
|
window.location.href = "/login?error=session_expired";
|
|
throw new Error("Unauthorized: Redirecting to login page");
|
|
}
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Failed to fetch user: ${response.status}`);
|
|
}
|
|
|
|
const data = await response.json();
|
|
setUser(data);
|
|
setError(null);
|
|
} catch (err: any) {
|
|
setError(err.message || "Failed to fetch user");
|
|
console.error("Error fetching user:", err);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
fetchUser();
|
|
}, []);
|
|
|
|
return { user, loading, error };
|
|
}
|