feat(auth): added in a rolling token
This commit is contained in:
16
frontend/src/hooks/useLogout.ts
Normal file
16
frontend/src/hooks/useLogout.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import {useSessionStore} from "@/lib/store/sessionStore";
|
||||
import {useRouter} from "@tanstack/react-router";
|
||||
|
||||
export const useLogout = () => {
|
||||
const {clearSession} = useSessionStore();
|
||||
const router = useRouter();
|
||||
const logout = async () => {
|
||||
router.invalidate();
|
||||
router.clearCache();
|
||||
clearSession();
|
||||
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
return logout;
|
||||
};
|
||||
49
frontend/src/hooks/useSession.ts
Normal file
49
frontend/src/hooks/useSession.ts
Normal 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};
|
||||
};
|
||||
Reference in New Issue
Block a user