-
Notifications
You must be signed in to change notification settings - Fork 531
/
auth.ts
54 lines (46 loc) · 1.64 KB
/
auth.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
43
44
45
46
47
48
49
50
51
52
53
54
import { ApiLogoutResp, ReactAuthDataType } from '@shared/authApiTypes';
import { useMutation } from '@tanstack/react-query';
import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai';
/**
* Atoms
*/
const authDataAtom = atom<ReactAuthDataType | false>(window.txConsts.preAuth);
const isAuthenticatedAtom = atom((get) => !!get(authDataAtom))
/**
* Hooks
*/
//Authentication hook, only re-renders on login/logout
export const useIsAuthenticated = () => {
return useAtomValue(isAuthenticatedAtom);
};
//Wipes auth data from the atom, this is triggered when an api pr page call returns a logout notice
export const useExpireAuthData = () => {
const setAuthData = useSetAtom(authDataAtom);
return (src = 'unknown') => {
console.log(`Logout notice received from '${src}'. Wiping auth data.`);
setAuthData(false);
window.history.replaceState(null, '', '/login#expired');
}
}
//Generic authentication hook, using it will cause your component to re-render on _any_ auth changes
export const useAuth = () => {
const [authData, setAuthData] = useAtom(authDataAtom);
const logoutMutation = useMutation<ApiLogoutResp>({
mutationKey: ['auth'],
mutationFn: () => fetch('/auth/logout', { method: 'POST' }).then(res => res.json()),
onSuccess: (data) => {
if (data.logout) {
setAuthData(false);
window.history.replaceState(null, '', '/login#logout');
}
},
});
return {
authData,
setAuthData,
logout: {
mutate: logoutMutation.mutate,
isLoading: logoutMutation.isPending,
}
}
};