|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useCallback, useEffect, useRef } from 'react'; |
| 4 | +import { useLogout } from './useLogout'; |
| 5 | +import { useToast } from '@/shared/hook/useToast'; |
| 6 | +import { useAuthStore } from '@/domains/shared/store/auth'; |
| 7 | + |
| 8 | +const IDLE_TIMEOUT = 4 * 60 * 60 * 1000; |
| 9 | + |
| 10 | +export const useIdleLogout = () => { |
| 11 | + const handleLogout = useLogout(); |
| 12 | + const timerRef = useRef<NodeJS.Timeout | null>(null); |
| 13 | + const warningTimerRef = useRef<NodeJS.Timeout | null>(null); |
| 14 | + const { toastInfo } = useToast(); |
| 15 | + const { isLoggedIn } = useAuthStore(); |
| 16 | + |
| 17 | + const resetTimer = useCallback(() => { |
| 18 | + if (!isLoggedIn) return; |
| 19 | + if (timerRef.current) clearTimeout(timerRef.current); |
| 20 | + if (warningTimerRef.current) clearTimeout(warningTimerRef.current); |
| 21 | + |
| 22 | + timerRef.current = setTimeout(() => { |
| 23 | + toastInfo('5초 뒤 자동 로그아웃 예정 \n 움직이면 자동 로그아웃 취소됩니다.'); |
| 24 | + warningTimerRef.current = setTimeout(() => handleLogout(), 5000); |
| 25 | + }, IDLE_TIMEOUT); |
| 26 | + }, [isLoggedIn, handleLogout, toastInfo]); |
| 27 | + |
| 28 | + useEffect(() => { |
| 29 | + const events = ['mousemove', 'keydown', 'mousedown', 'touchstart']; |
| 30 | + events.forEach((e) => window.addEventListener(e, resetTimer)); |
| 31 | + |
| 32 | + resetTimer(); |
| 33 | + |
| 34 | + return () => { |
| 35 | + if (timerRef.current) clearTimeout(timerRef.current); |
| 36 | + if (warningTimerRef.current) clearTimeout(warningTimerRef.current); |
| 37 | + events.forEach((e) => window.removeEventListener(e, resetTimer)); |
| 38 | + }; |
| 39 | + }, [resetTimer]); |
| 40 | +}; |
0 commit comments