/
loginLogic.ts
47 lines (44 loc) 路 1.47 KB
/
loginLogic.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
import { kea } from 'kea'
import api from 'lib/api'
import { loginLogicType } from './loginLogicType'
import { router } from 'kea-router'
interface AuthenticateResponseType {
success: boolean
errorCode?: string
errorDetail?: string
}
export function afterLoginRedirect(): string {
return router.values.searchParams['next'] || '/'
}
export const loginLogic = kea<loginLogicType<AuthenticateResponseType>>({
path: ['scenes', 'authentication', 'loginLogic'],
loaders: {
authenticateResponse: [
null as AuthenticateResponseType | null,
{
authenticate: async ({ email, password }: { email: string; password: string }) => {
try {
await api.create('api/login', { email, password })
return { success: true }
} catch (e) {
return { success: false, errorCode: e.code, errorDetail: e.detail }
}
},
},
],
},
listeners: {
authenticateSuccess: ({ authenticateResponse }) => {
if (authenticateResponse?.success) {
window.location.href = afterLoginRedirect()
}
},
},
urlToAction: ({ actions }) => ({
'/login': ({}, { error, errorDetail }) => {
if (error) {
actions.authenticateSuccess({ success: false, errorCode: error, errorDetail })
}
},
}),
})