useAuth.ts
1.21 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
import { useState, useCallback } from "react";
import ky from "ky";
interface LoginResponse {
status: number;
data: {
access_token: string;
refresh_token: string;
expiration: string;
};
}
interface Token {
accessToken: string;
refreshToken: string;
expiration: Date;
}
export function useAuth() {
const [token, setToken] = useState<Token | null>(() => {
const item = localStorage.getItem("token");
if (item) {
const token = JSON.parse(item);
token.expiration = new Date(token.expiration);
return token;
}
return null;
});
const login = useCallback(
async (username: string, password: string, remember: boolean) => {
const response = await ky
.post("/users/login", {
json: {
user_id: username,
password: password,
},
})
.json<LoginResponse>();
const token = {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
expiration: new Date(response.data.expiration),
};
setToken(token);
if (remember) {
localStorage.setItem("token", JSON.stringify(token));
}
},
[]
);
return { token, login };
}