1 |
8c45ccb0
|
hrubyjar
|
import { authController } from '../controllers';
|
2 |
|
|
import { LoginResponse } from '../api';
|
3 |
|
|
|
4 |
|
|
export async function loginUser(username: string, password: string): Promise<boolean> {
|
5 |
|
|
try {
|
6 |
|
|
const loginRes = await authController.authLoginPost({ username, password });
|
7 |
|
|
|
8 |
|
|
const data: LoginResponse = loginRes.data;
|
9 |
|
|
|
10 |
|
|
if (data && data.token) {
|
11 |
|
|
localStorage.setItem('token', JSON.stringify(data));
|
12 |
|
|
return true;
|
13 |
|
|
}
|
14 |
|
|
} catch (e) {
|
15 |
|
|
if (e instanceof Error) {
|
16 |
|
|
if (e.message.includes('status code 401')) {
|
17 |
|
|
return false;
|
18 |
|
|
}
|
19 |
|
|
}
|
20 |
|
|
}
|
21 |
|
|
|
22 |
|
|
return false;
|
23 |
|
|
}
|
24 |
|
|
|
25 |
|
|
export async function logoutUser(): Promise<boolean> {
|
26 |
|
|
localStorage.clear();
|
27 |
|
|
return true;
|
28 |
|
|
}
|
29 |
|
|
export async function getTokenData(): Promise<LoginResponse | null> {
|
30 |
|
|
const dataJSON = localStorage.getItem('token');
|
31 |
|
|
|
32 |
|
|
if (!dataJSON) {
|
33 |
|
|
// no token found
|
34 |
|
|
return null;
|
35 |
|
|
}
|
36 |
|
|
|
37 |
|
|
return JSON.parse(dataJSON);
|
38 |
|
|
}
|
39 |
|
|
export async function getToken(): Promise<string> {
|
40 |
|
|
const data = await getTokenData();
|
41 |
|
|
if (!data) {
|
42 |
|
|
return '';
|
43 |
|
|
}
|
44 |
|
|
|
45 |
|
|
return data.token ?? '';
|
46 |
|
|
}
|