forked from alan2207/bulletproof-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.tsx
65 lines (57 loc) · 1.44 KB
/
auth.tsx
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
import { initReactQueryAuth } from 'react-query-auth';
import { Spinner } from '@/components/Elements';
import {
loginWithEmailAndPassword,
getUser,
registerWithEmailAndPassword,
UserResponse,
LoginCredentialsDTO,
RegisterCredentialsDTO,
AuthUser,
} from '@/features/auth';
import storage from '@/utils/storage';
async function handleUserResponse(data: UserResponse) {
const { jwt, user } = data;
storage.setToken(jwt);
return user;
}
async function loadUser() {
if (storage.getToken()) {
const data = await getUser();
return data;
}
return null;
}
async function loginFn(data: LoginCredentialsDTO) {
const response = await loginWithEmailAndPassword(data);
const user = await handleUserResponse(response);
return user;
}
async function registerFn(data: RegisterCredentialsDTO) {
const response = await registerWithEmailAndPassword(data);
const user = await handleUserResponse(response);
return user;
}
async function logoutFn() {
storage.clearToken();
window.location.assign(window.location.origin as unknown as string);
}
const authConfig = {
loadUser,
loginFn,
registerFn,
logoutFn,
LoaderComponent() {
return (
<div className="w-screen h-screen flex justify-center items-center">
<Spinner size="xl" />
</div>
);
},
};
export const { AuthProvider, useAuth } = initReactQueryAuth<
AuthUser | null,
unknown,
LoginCredentialsDTO,
RegisterCredentialsDTO
>(authConfig);