|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useSession, signOut } from "next-auth/react"; |
| 4 | +import { useEffect, useRef } from "react"; |
| 5 | + |
| 6 | +// Use 30 seconds for testing |
| 7 | +const SESSION_TIMEOUT = 30 * 1000; // 30 seconds for testing |
| 8 | + |
| 9 | +export function useSessionTimeoutTest() { |
| 10 | + const { data: session, status } = useSession(); |
| 11 | + const timeoutRef = useRef<NodeJS.Timeout | null>(null); |
| 12 | + |
| 13 | + useEffect(() => { |
| 14 | + // Only run on client side |
| 15 | + if (typeof window === 'undefined') return; |
| 16 | + |
| 17 | + if (status === "authenticated" && session) { |
| 18 | + console.log('🕐 Session timeout test started - 30 seconds'); |
| 19 | + |
| 20 | + const startTimeout = () => { |
| 21 | + // Clear existing timeout |
| 22 | + if (timeoutRef.current) { |
| 23 | + clearTimeout(timeoutRef.current); |
| 24 | + } |
| 25 | + |
| 26 | + // Set new timeout |
| 27 | + timeoutRef.current = setTimeout(() => { |
| 28 | + console.log('🚪 Session expired - signing out'); |
| 29 | + signOut({ |
| 30 | + callbackUrl: "/login?expired=true", |
| 31 | + redirect: true |
| 32 | + }); |
| 33 | + }, SESSION_TIMEOUT); |
| 34 | + }; |
| 35 | + |
| 36 | + // Start the initial timeout |
| 37 | + startTimeout(); |
| 38 | + |
| 39 | + // Reset timeout on user activity |
| 40 | + const resetTimeout = () => { |
| 41 | + console.log('🔄 User activity detected - resetting timeout'); |
| 42 | + startTimeout(); |
| 43 | + }; |
| 44 | + |
| 45 | + // Listen for user activity |
| 46 | + const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click']; |
| 47 | + events.forEach(event => { |
| 48 | + document.addEventListener(event, resetTimeout, true); |
| 49 | + }); |
| 50 | + |
| 51 | + return () => { |
| 52 | + if (timeoutRef.current) { |
| 53 | + clearTimeout(timeoutRef.current); |
| 54 | + } |
| 55 | + events.forEach(event => { |
| 56 | + document.removeEventListener(event, resetTimeout, true); |
| 57 | + }); |
| 58 | + }; |
| 59 | + } |
| 60 | + }, [session, status]); |
| 61 | +} |
0 commit comments