diff --git a/Frontend/lib/auth-context.tsx b/Frontend/lib/auth-context.tsx index ba9fdc7..2c6caa2 100644 --- a/Frontend/lib/auth-context.tsx +++ b/Frontend/lib/auth-context.tsx @@ -2,6 +2,7 @@ import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from "react" import { useSession, signIn, signOut } from "next-auth/react" +import { usePathname } from "next/navigation" import type { User, Ticket, TicketStatus, Room } from "./types" const API_URL = process.env.NEXT_PUBLIC_API_URL + "/api" @@ -23,6 +24,7 @@ interface AuthContextType { updateUserRole: (userId: number, role: string) => Promise deleteUser: (userId: number) => Promise adminResetPassword: (userId: number, password: string) => Promise + validateSession: () => Promise } const AuthContext = createContext(null) @@ -32,6 +34,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { const [tickets, setTickets] = useState([]) const [rooms, setRooms] = useState([]) const [authHeader, setAuthHeader] = useState(null) + const pathname = usePathname() // Fetch rooms on mount useEffect(() => { @@ -284,6 +287,34 @@ export function AuthProvider({ children }: { children: ReactNode }) { } }, [authHeader]) + const validateSession = useCallback(async () => { + if (!authHeader) return false + try { + const res = await fetch(`${API_URL}/auth/me`, { + headers: { "Authorization": authHeader } + }) + if (res.ok) { + const freshUser = await res.json() + setUser(freshUser) + return true + } else { + // If the checking fails (401/403), log the user out + logout() + return false + } + } catch (e) { + console.error("Session validation failed", e) + return false + } + }, [authHeader, logout]) + + // Validate session on route change + useEffect(() => { + if (authHeader) { + validateSession() + } + }, [pathname, authHeader, validateSession]) + return ( {children}