feat(auth): added in a rolling token

This commit is contained in:
2025-03-05 12:10:09 -06:00
parent 5fcadb9fc8
commit 50cf87380d
5 changed files with 73 additions and 10 deletions

View File

@@ -0,0 +1,49 @@
import {useQuery} from "@tanstack/react-query";
import {useSessionStore} from "../lib/store/sessionStore";
import {useEffect} from "react";
const fetchSession = async () => {
const token = localStorage.getItem("auth_token");
if (!token) {
throw new Error("No token found");
}
const res = await fetch("/api/auth/session", {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
// console.log(res);
if (!res.ok) {
throw new Error("Session not found");
}
return res.json();
};
export const useSession = () => {
const {setSession, clearSession, token} = useSessionStore();
// Fetch session only if token is available
const {data, status, error} = useQuery({
queryKey: ["session"],
queryFn: fetchSession,
enabled: !!token, // Prevents query if token is null
staleTime: 60 * 1000,
gcTime: 10 * 60 * 1000, // 10 mins
refetchOnWindowFocus: true,
//refetchInterval: 1000 * 60 * 2, // Auto-refetch every 2 minutes
});
useEffect(() => {
if (data) {
setSession(data.data.user, data.data.token);
}
if (error) {
clearSession();
}
}, [data, error]);
return {session: data && token ? {user: data.user, token: data.token} : null, status, error};
};