/
useSms.tsx
227 lines (215 loc) · 6.4 KB
/
useSms.tsx
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import request from '@/services/request';
import useSessionStore from '@/stores/session';
import { ApiResp, Session } from '@/types';
import {
Image,
Input,
InputGroup,
InputLeftAddon,
InputRightAddon,
Link,
Text
} from '@chakra-ui/react';
import { useTranslation } from 'next-i18next';
import NextLink from 'next/link';
import { useRouter } from 'next/router';
import { MouseEventHandler, useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { getRegionToken, UserInfo } from '@/api/auth';
import { jwtDecode } from 'jwt-decode';
import { uploadConvertData } from '@/api/platform';
import { AccessTokenPayload } from '@/types/token';
import { sessionConfig } from '@/utils/sessionConfig';
export default function useSms({
showError
}: {
showError: (errorMessage: string, duration?: number) => void;
}) {
const { t } = useTranslation();
const _remainTime = useRef(0);
const router = useRouter();
const setSession = useSessionStore((s) => s.setSession);
const [isLoading, setIsLoading] = useState(false);
const setToken = useSessionStore((s) => s.setToken);
const { register, handleSubmit, trigger, getValues } = useForm<{
phoneNumber: string;
verifyCode: string;
}>();
const login = async () => {
const deepSearch = (obj: any): string => {
if (!obj || typeof obj !== 'object') return t('Submit Error');
if (!!obj.message) {
return obj.message;
}
return deepSearch(Object.values(obj)[0]);
};
await handleSubmit(
async (data) => {
try {
setIsLoading(true);
const result1 = await request.post<any, ApiResp<{ token: string }>>(
'/api/auth/phone/verify',
{
phoneNumbers: data.phoneNumber,
code: data.verifyCode
}
);
const globalToken = result1?.data?.token;
if (!globalToken) throw Error();
setToken(globalToken);
const regionTokenRes = await getRegionToken();
if (regionTokenRes?.data) {
await sessionConfig(regionTokenRes.data);
uploadConvertData([3]).then(
(res) => {
console.log(res);
},
(err) => {
console.log(err);
}
);
await router.replace('/');
}
} catch (error) {
showError(t('Invalid verification code') || 'Invalid verification code');
} finally {
setIsLoading(false);
}
},
(err) => {
showError(deepSearch(err));
}
)();
};
const SmsModal = () => {
const [remainTime, setRemainTime] = useState(_remainTime.current);
useEffect(() => {
if (remainTime <= 0) return;
const interval = setInterval(() => {
setRemainTime(remainTime - 1);
}, 1000);
return () => clearInterval(interval);
}, [remainTime]);
const getCode: MouseEventHandler = async (e) => {
e.preventDefault();
if (!(await trigger('phoneNumber'))) {
showError(t('Invalid phone number') || 'Invalid phone number');
return;
}
setRemainTime(60);
_remainTime.current = 60;
try {
const res = await request.post<any, ApiResp<any>>('/api/auth/phone/sms', {
phoneNumbers: getValues('phoneNumber')
});
if (res.code !== 200 || res.message !== 'successfully') {
throw new Error('Get code failed');
}
} catch (err) {
showError(t('Get code failed') || 'Get code failed');
setRemainTime(0);
_remainTime.current = 0;
}
};
return (
<>
<InputGroup
variant={'unstyled'}
bg="rgba(255, 255, 255, 0.65)"
mt={'20px'}
width="266px"
minH="42px"
mb="14px"
borderRadius="4px"
p="10px"
border="1px solid #E5E5E5"
>
<InputLeftAddon>
<Text pr={'7px'} borderRight="1px solid rgba(0, 0, 0, 0.4)">
+86
</Text>
</InputLeftAddon>
<Input
type="tel"
placeholder={t('phone number tips') || ''}
mx={'12px'}
variant={'unstyled'}
bg={'transparent'}
id="phoneNumber"
fontSize="14px"
fontWeight="400"
_autofill={{
bg: 'transparent'
}}
{...register('phoneNumber', {
pattern: {
value: /^1[3-9]\d{9}$/,
message: 'Invalid mobile number'
},
required: 'Phone number can not be blank'
})}
/>
<InputRightAddon
fontStyle="normal"
fontWeight="500"
fontSize="10px"
lineHeight="20px"
color="#219BF4"
>
{remainTime <= 0 ? (
<Link as={NextLink} href="" onClick={getCode}>
{t('Get Code')}
</Link>
) : (
<Text>{remainTime} s</Text>
)}
</InputRightAddon>
</InputGroup>
<InputGroup
variant={'unstyled'}
bg="rgba(255, 255, 255, 0.65)"
width="266px"
minH="42px"
mb="14px"
borderRadius="4px"
p="10px"
border="1px solid #E5E5E5"
>
<InputLeftAddon>
<Image src="/images/ant-design_safety-outlined.svg" alt="safety" />
</InputLeftAddon>
<Input
type="text"
placeholder={t('verify code tips') || ''}
pl={'12px'}
variant={'unstyled'}
id="verifyCode"
fontSize="14px"
fontWeight="400"
_autofill={{
backgroundColor: 'transparent !important',
backgroundImage: 'none !important'
}}
{...register('verifyCode', {
required: 'verify code can not be blank',
pattern: {
value: /^[0-9]{6}$/,
message: 'Invalid verification code'
}
})}
/>
<InputRightAddon>
{getValues('verifyCode')?.length === 6 && (
<Image src="images/material-symbols_update.svg" alt="material-symbols_update" />
)}
</InputRightAddon>
</InputGroup>
</>
);
};
return {
SmsModal,
login,
isLoading
};
}