-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathuse-auth.tsx
More file actions
63 lines (55 loc) · 1.52 KB
/
use-auth.tsx
File metadata and controls
63 lines (55 loc) · 1.52 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
58
59
60
61
62
63
import {JWT_LOCAL_STORAGE_KEY} from '@/modules/auth/shared'
import {trpcReact} from '@/trpc/trpc'
import {t} from '@/utils/i18n'
import {redirect} from './redirects'
/**
* Make sure to hard reload page after updating this because trpc client is created on page load and it's only possible to update it on page load.
*/
export function useJwt() {
const jwt = window.localStorage.getItem(JWT_LOCAL_STORAGE_KEY)
return {
jwt,
removeJwt() {
window.localStorage.removeItem(JWT_LOCAL_STORAGE_KEY)
},
setJwt(jwt: string) {
window.localStorage.setItem(JWT_LOCAL_STORAGE_KEY, jwt)
},
}
}
export function useAuth() {
const {jwt, setJwt, removeJwt} = useJwt()
const logoutMut = trpcReact.user.logout.useMutation({
onSuccess(didWork) {
// TODO: add translation
if (!didWork) throw new Error("Logout didn't work.")
removeJwt()
// Hard navigate to `/login` to force all parent layouts to re-render
window.location.href = '/login'
},
onError() {
alert(t('logout-error-generic'))
},
})
const refreshTokenQ = trpcReact.user.renewToken.useMutation()
const refreshToken = async () => {
const res = await refreshTokenQ.mutateAsync()
setJwt(res)
}
return {
jwt,
async logout() {
logoutMut.mutate()
},
loginWithJwt(jwt: string) {
setJwt(jwt)
// Hard navigate to `/` to force all parent layouts to re-render
window.location.href = redirect.getRedirectPath()
},
signUpWithJwt(jwt: string) {
setJwt(jwt)
window.location.href = '/onboarding/account-created'
},
refreshToken,
}
}