-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseAuth.ts
42 lines (34 loc) · 894 Bytes
/
useAuth.ts
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
import { useState, useEffect } from "react";
const TOKEN_STORAGE_KEY = "token";
interface User {
userId: number;
username: string;
role: string;
iat: number;
}
const useAuth = () => {
const [accessToken, setAccessToken] = useState<string | null>(null);
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
if (storedToken) {
setAccessToken(storedToken);
setUser({ ...JSON.parse(atob(storedToken.split(".")[1])) });
}
}, []);
const saveToken = (newToken: string) => {
localStorage.setItem(TOKEN_STORAGE_KEY, newToken);
setAccessToken(newToken);
};
const clearToken = () => {
localStorage.removeItem(TOKEN_STORAGE_KEY);
setAccessToken(null);
};
return {
accessToken,
saveToken,
clearToken,
user,
};
};
export default useAuth;