payment-backoffice/app/hooks/useTokenExpiration.ts
2025-08-06 09:41:20 +02:00

67 lines
2.0 KiB
TypeScript

"use client";
import { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useRouter } from "next/navigation";
import { AppDispatch } from "@/app/redux/types";
import {
selectTimeUntilExpiration,
selectIsLoggedIn,
} from "@/app/redux/auth/selectors";
import { autoLogout } from "@/app/redux/auth/authSlice";
export function useTokenExpiration() {
const dispatch = useDispatch<AppDispatch>();
const router = useRouter();
const timeUntilExpiration = useSelector(selectTimeUntilExpiration);
const isLoggedIn = useSelector(selectIsLoggedIn);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
// Clear any existing timeout
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
// Only set up expiration monitoring if user is logged in and we have expiration data
if (isLoggedIn && timeUntilExpiration > 0) {
// Set timeout to logout 1 second after token expires
const logoutDelay = (timeUntilExpiration + 1) * 1000;
timeoutRef.current = setTimeout(() => {
console.log("Token expired, auto-logging out user");
dispatch(autoLogout("Token expired"));
router.push("/login");
}, logoutDelay);
// Also set up periodic checks every 5 minutes
const checkInterval = setInterval(() => {
// Re-dispatch checkAuthStatus to get updated expiration time
// This will be handled by the ReduxProvider
}, 5 * 60 * 1000); // 5 minutes
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
clearInterval(checkInterval);
};
}
}, [isLoggedIn, timeUntilExpiration, dispatch, router]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return {
timeUntilExpiration,
isLoggedIn,
};
}