-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
passwordResetLogic.ts
107 lines (104 loc) 路 3.8 KB
/
passwordResetLogic.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { kea } from 'kea'
import api from 'lib/api'
import { successToast } from 'lib/utils'
import { passwordResetLogicType } from './passwordResetLogicType'
interface ResponseType {
success: boolean
errorCode?: string
errorDetail?: string
}
interface ResetResponseType extends ResponseType {
email?: string
}
interface ValidatedTokenResponseType extends ResponseType {
token?: string
uuid?: string
}
export const passwordResetLogic = kea<
passwordResetLogicType<ResetResponseType, ResponseType, ValidatedTokenResponseType>
>({
path: ['scenes', 'authentication', 'passwordResetLogic'],
loaders: ({ values }) => ({
resetResponse: [
null as ResetResponseType | null,
{
reset: async ({ email }: { email: string }) => {
try {
await api.create('api/reset/', { email })
return { success: true, email }
} catch (e) {
return { success: false, errorCode: e.code, errorDetail: e.detail }
}
},
},
],
validatedResetToken: [
null as ValidatedTokenResponseType | null,
{
validateResetToken: async ({ uuid, token }: { uuid: string; token: string }) => {
try {
await api.get(`api/reset/${uuid}/?token=${token}`)
return { success: true, token, uuid }
} catch (e) {
return { success: false, errorCode: e.code, errorDetail: e.detail }
}
},
},
],
newPasswordResponse: [
null as ResponseType | null,
{
updatePassword: async ({
password,
passwordConfirm,
}: {
password: string
passwordConfirm: string
}) => {
if (!values.validatedResetToken?.token || !values.validatedResetToken.uuid) {
return {
success: false,
errorCode: 'invalid_token',
errorDetail: 'Your link is invalid or expired.',
}
}
if (passwordConfirm !== password) {
return {
success: false,
errorCode: 'confirmation_does_not_match',
errorDetail: 'Password confirmation does not match.',
}
}
try {
await api.create(`api/reset/${values.validatedResetToken.uuid}/`, {
password,
token: values.validatedResetToken.token,
})
return { success: true }
} catch (e) {
return { success: false, errorCode: e.code, errorDetail: e.detail }
}
},
},
],
}),
listeners: {
updatePasswordSuccess: async ({ newPasswordResponse }, breakpoint) => {
if (newPasswordResponse.success) {
successToast(
'Password changed successfully',
'Your password was successfully changed. Redirecting you...'
)
await breakpoint(3000)
window.location.href = '/' // We need the refresh
}
},
},
urlToAction: ({ actions }) => ({
'/reset/:uuid/:token': ({ uuid, token }) => {
if (token && uuid) {
actions.validateResetToken({ uuid, token })
}
},
}),
})