-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
auth.tsx
93 lines (77 loc) · 2.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { configureAuth } from 'react-query-auth';
import { Navigate, useLocation } from 'react-router-dom';
import { z } from 'zod';
import { paths } from '@/config/paths';
import { AuthResponse, User } from '@/types/api';
import { api } from './api-client';
// api call definitions for auth (types, schemas, requests):
// these are not part of features as this is a module shared across features
const getUser = async (): Promise<User> => {
const response = await api.get('/auth/me');
return response.data;
};
const logout = (): Promise<void> => {
return api.post('/auth/logout');
};
export const loginInputSchema = z.object({
email: z.string().min(1, 'Required').email('Invalid email'),
password: z.string().min(5, 'Required'),
});
export type LoginInput = z.infer<typeof loginInputSchema>;
const loginWithEmailAndPassword = (data: LoginInput): Promise<AuthResponse> => {
return api.post('/auth/login', data);
};
export const registerInputSchema = z
.object({
email: z.string().min(1, 'Required'),
firstName: z.string().min(1, 'Required'),
lastName: z.string().min(1, 'Required'),
password: z.string().min(1, 'Required'),
})
.and(
z
.object({
teamId: z.string().min(1, 'Required'),
teamName: z.null().default(null),
})
.or(
z.object({
teamName: z.string().min(1, 'Required'),
teamId: z.null().default(null),
}),
),
);
export type RegisterInput = z.infer<typeof registerInputSchema>;
const registerWithEmailAndPassword = (
data: RegisterInput,
): Promise<AuthResponse> => {
return api.post('/auth/register', data);
};
const authConfig = {
userFn: getUser,
loginFn: async (data: LoginInput) => {
const response = await loginWithEmailAndPassword(data);
return response.user;
},
registerFn: async (data: RegisterInput) => {
const response = await registerWithEmailAndPassword(data);
return response.user;
},
logoutFn: logout,
};
export const { useUser, useLogin, useLogout, useRegister, AuthLoader } =
configureAuth(authConfig);
export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
const user = useUser();
const location = useLocation();
if (!user.data) {
console.log({
pathname: location.pathname,
redirectTo: paths.auth.login.getHref(location.pathname),
});
return (
<Navigate to={paths.auth.login.getHref(location.pathname)} replace />
);
}
return children;
};