Add auth expiry interceptor and session-expired redirect
This commit is contained in:
@@ -10,10 +10,13 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import * as authApi from "../api/auth";
|
||||
import { SESSION_EXPIRED_EVENT } from "../api/client";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
@@ -64,6 +67,21 @@ export function AuthProvider({
|
||||
token: sessionStorage.getItem(SESSION_KEY),
|
||||
expiresAt: sessionStorage.getItem(SESSION_EXPIRES_KEY),
|
||||
}));
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleSessionExpired = useCallback((): void => {
|
||||
sessionStorage.removeItem(SESSION_KEY);
|
||||
sessionStorage.removeItem(SESSION_EXPIRES_KEY);
|
||||
setAuth({ token: null, expiresAt: null });
|
||||
navigate("/login", { replace: true });
|
||||
}, [navigate]);
|
||||
|
||||
useEffect((): (() => void) => {
|
||||
window.addEventListener(SESSION_EXPIRED_EVENT, handleSessionExpired);
|
||||
return (): void => {
|
||||
window.removeEventListener(SESSION_EXPIRED_EVENT, handleSessionExpired);
|
||||
};
|
||||
}, [handleSessionExpired]);
|
||||
|
||||
const isAuthenticated = useMemo<boolean>(() => {
|
||||
if (!auth.token || !auth.expiresAt) return false;
|
||||
|
||||
Reference in New Issue
Block a user