-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAutoLogout.ts
More file actions
86 lines (70 loc) Β· 2.53 KB
/
useAutoLogout.ts
File metadata and controls
86 lines (70 loc) Β· 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { jwtDecode } from 'jwt-decode';
import { useEffect, useRef } from 'react';
import useAuthStore from './useAuthStore';
import { useErrorStore } from './useErrorStore';
// 5λΆ λ²νΌ (λ°λ¦¬μ΄) -> λ§λ£ 5λΆ μ μ 미리 λ‘κ·Έμμ μν΄
const BUFFER_TIME = 5 * 60 * 1000;
export function useAutoLogout() {
const { token, logout } = useAuthStore();
const showError = useErrorStore((state) => state.showError);
const isLoggingOut = useRef(false);
useEffect(() => {
if (!token) {
isLoggingOut.current = false;
return;
}
const checkAndLogout = () => {
if (isLoggingOut.current) return;
try {
const decoded = jwtDecode(token);
if (!decoded.exp) return;
// ν ν° expλ μ΄ λ¨μμ΄λ―λ‘ λ°λ¦¬μ΄λ‘ λ³ν
const expTimeMs = decoded.exp * 1000;
const now = Date.now();
// (λ§λ£μκ° - λ²νΌ) μμ κΉμ§ λ¨μ μκ°
const timeLeftToLogout = expTimeMs - BUFFER_TIME - now;
if (timeLeftToLogout <= 0) {
// μ΄λ―Έ λ§λ£ μμ μ(νΉμ λ²νΌ μμ μ) μ§λ¬λ€λ©΄ μ¦μ λ‘κ·Έμμ
handleLogout();
} else {
// μμ§ μκ°μ΄ λ¨μλ€λ©΄ νμ΄λ¨Έ μ€μ
const timerId = setTimeout(() => {
handleLogout();
}, timeLeftToLogout);
return timerId;
}
} catch (error) {
// ν ν° λμ½λ© μ€ν¨ μ (μ ν¨νμ§ μμ ν ν°) κ°μ λ‘κ·Έμμ
console.error('Invalid token format', error);
handleLogout();
}
};
const handleLogout = () => {
if (isLoggingOut.current) return;
isLoggingOut.current = true;
logout();
showError(
'λ‘κ·ΈμΈ μ μ§ μκ°μ΄ λ§λ£λμ΄ μλμΌλ‘ λ‘κ·Έμμλμμ΅λλ€.',
'λ‘κ·Έμμ μλ΄',
() => {
window.location.href = '/login';
},
'λ€μ λ‘κ·ΈμΈνκΈ°'
);
};
// 1. λ§μ΄νΈ μμ μ μ²΄ν¬ & νμ΄λ¨Έ μ€μ
let timerId = checkAndLogout();
// 2. λΈλΌμ°μ ν νμ±ν(ν¬μ»€μ€ 볡κ·) μμ μ λ€μ 체ν¬
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
if (timerId) clearTimeout(timerId);
timerId = checkAndLogout();
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
if (timerId) clearTimeout(timerId);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [token, logout, showError]);
}