/
login.ts
106 lines (97 loc) 路 2.5 KB
/
login.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
import { createModel } from '@rematch/core';
import i18next from 'i18next';
import type { RootModel } from '.';
import { isTokenExpire } from '../../utils';
import API from '../api';
import storage from '../storage';
export const HEADERS = {
JSON: 'application/json',
};
export type LoginError = {
type: string;
description: string;
};
export type LoginResponse = {
username: string | null;
token: string | null;
};
export type LoginBody = {
error?: LoginError;
} & LoginResponse;
export function getDefaultUserState(): LoginBody {
const token = storage.getItem('token');
const username = storage.getItem('username');
const defaultUserState = isTokenExpire(token)
? { token: null, username: null }
: { token, username };
return defaultUserState;
}
const defaultUserState: LoginBody = getDefaultUserState();
/**
*
* @category Model
*/
export const login = createModel<RootModel>()({
state: {
username: defaultUserState.username,
token: defaultUserState.token,
},
reducers: {
logOutUser(state) {
storage.removeItem('username');
storage.removeItem('token');
return {
...state,
username: null,
token: null,
};
},
addError(state, error: LoginError) {
return {
...state,
error,
};
},
clearError(state) {
return {
...state,
error: undefined,
};
},
logInUser(state, response: LoginResponse) {
// we might persist this in another way with
storage.setItem('username', response.username as string);
storage.setItem('token', response.token as string);
return {
...state,
token: response.token as string,
username: response.username as string,
};
},
},
effects: (dispatch) => ({
async getUser({ username, password }, state) {
const basePath = state.configuration.config.base;
try {
const payload: LoginResponse = await API.request(
`${basePath}-/verdaccio/sec/login`,
'POST',
{
body: JSON.stringify({ username, password }),
headers: {
Accept: HEADERS.JSON,
'Content-Type': HEADERS.JSON,
},
}
);
dispatch.login.logInUser(payload);
dispatch.packages.getPackages(undefined);
} catch (error: any) {
dispatch.login.addError({
type: 'error',
description: i18next.t('form-validation.unable-to-sign-in'),
});
}
},
}),
});