Skip to content

Commit

Permalink
perf(frontend/desktop):add sign in error tips (labring#3471)
Browse files Browse the repository at this point in the history
  • Loading branch information
xudaotutou committed Jul 6, 2023
1 parent 9e83f02 commit 613ce0f
Show file tree
Hide file tree
Showing 13 changed files with 84 additions and 61 deletions.
1 change: 0 additions & 1 deletion frontend/desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
"@emotion/react": "^11.10.6",
"@emotion/styled": "^11.10.6",
"@kubernetes/client-node": "^0.18.1",
"@prisma/client": "4.14.1",
"@tanstack/react-query": "^4.29.3",
"axios": "^1.3.5",
"clsx": "^1.2.1",
Expand Down
22 changes: 1 addition & 21 deletions frontend/desktop/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions frontend/desktop/public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@
"Verify password": "Verify password",
"verify code tips":"6-digit Verification Code",
"phone number tips":"Phone Number",
"Invalid phone number": "Invalid phone number",
"Invalid username or password": "Invalid username or password",
"Invalid verification code":"Invalid verification code",
"Get code failed":"Get code failed",
"Read and agree":"Please read and agree to the agreement below",
"agree policy":"I have read and agree to the",
"Service Agreement":"Service Agreement",
Expand Down
3 changes: 2 additions & 1 deletion frontend/desktop/public/locales/zh-Hans/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@
"password tips": "密码为8位以上字符",
"username tips":"用户名为3-16位的英文或数字的字符",
"Invalid username or password": "用户名或密码错误",
"Invalid mobile number": "无效的手机号码",
"Invalid phone number":"无效的手机号码",
"Invalid verification code": "无效的验证码",
"Get code failed": "获取验证码失败",
"Read and agree": "请阅读并同意下方协议",
"agree policy": "我已阅读并同意",
"and": "",
Expand Down
3 changes: 2 additions & 1 deletion frontend/desktop/public/locales/zh/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@
"username tips":"用户名为3-16位的英文或数字的字符",
"Verify password": "确认密码",
"Invalid username or password": "用户名或密码错误",
"Invalid mobile number":"无效的手机号码",
"Invalid phone number":"无效的手机号码",
"Invalid verification code":"无效的验证码",
"Get code failed":"获取验证码失败",
"Read and agree":"请阅读并同意下方协议",
"agree policy":"我已阅读并同意",
"and":"",
Expand Down
44 changes: 33 additions & 11 deletions frontend/desktop/src/pages/api/auth/phone/sms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,21 @@ import * as Util from '@alicloud/tea-util'
import { jsonRes } from '@/services/backend/response';
import { addOrUpdateCode, checkSendable } from '@/services/backend/db/verifyCode';
import { enableSms } from '@/services/enable';
import { retrySerially } from '@/utils/tools';
const accessKeyId = process.env.ALI_ACCESS_KEY_ID
const accessKeySecret = process.env.ALI_ACCESS_KEY_SECRET
const templateCode = process.env.ALI_TEMPLATE_CODE
const signName = process.env.ALI_SIGN_NAME

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
if(!enableSms()){
if (!enableSms()) {
throw new Error('SMS is not enabled')
}
const { phoneNumbers } = req.body;
if (!await checkSendable(phoneNumbers)) {
return jsonRes(res, {
message: 'SMS already sent',
message: 'code already sent',
code: 400
})
}
Expand All @@ -42,24 +43,45 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)

const client = new Dysmsapi(config)
const runtime = new Util.RuntimeOptions({})
const result = await client.sendSmsWithOptions(sendSmsRequest, runtime)
if (result.body.code !== 'OK') {
jsonRes(res, {
message: `ALISMS_ERROR: ${result.body.message}`
})
return
}
const result = await retrySerially(async () => {
try {
const _result = await client.sendSmsWithOptions(sendSmsRequest, runtime)

if (!_result) {
throw new Error('sms result is null')
}
if (_result.statusCode !== 200) {
throw new Error(`sms result status code is ${_result.statusCode}
${_result.body}
${phoneNumbers},
${new Date()}
`
)
}
if (_result.body.code !== 'OK') {
throw new Error(`
${_result.body.message}
${phoneNumbers},
${new Date()}`)
}
return _result
} catch (error) {
return Promise.reject(error)
}
}, 3)

// update cache
await addOrUpdateCode({ phone: phoneNumbers, code })
return jsonRes(res, {
message: 'SMS sent',
message: 'successfully',
code: 200
})

} catch (error) {
console.log(error)
jsonRes(res, {
message: 'Failed to send SMS'
message: 'Failed to send code',
code: 500
})
}

Expand Down
2 changes: 1 addition & 1 deletion frontend/desktop/src/pages/callback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const Callback: NextPage = () => {
data = (await request.post<any, { data: Session, code: number }>('/api/auth/oauth/wechat', { code }))
break;
default:
throw Error('provider error')
throw new Error('provider error')
break;
}
if (data.code === 200) {
Expand Down
37 changes: 24 additions & 13 deletions frontend/desktop/src/pages/signin.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { FormEventHandler, MouseEventHandler, useEffect, useMemo, useRef, useState } from "react";
import React, { FormEventHandler, MouseEventHandler, useEffect, useRef, useState } from "react";
import { Image, Tab, TabIndicator, TabList, Tabs } from "@chakra-ui/react";
import { useQuery } from "@tanstack/react-query";
import Layout from "@/components/layout";
Expand Down Expand Up @@ -33,12 +33,12 @@ function usePassword({ setError }: { setError: React.Dispatch<React.SetStateActi
// 是否为初次登录
const [isFirst, setIsFirst] = useState(true)
const verify = () => {
if(!strongUsername(username.current)){
setError(t('username tips')||'Username must be 3-16 characters, including letters, numbers')
if (!strongUsername(username.current)) {
setError(t('username tips') || 'Username must be 3-16 characters, including letters, numbers')
return false
}
if(!strongPassword(password.current)){
setError(t('password tips')||'8 characters or more')
if (!strongPassword(password.current)) {
setError(t('password tips') || '8 characters or more')
return false
}
if (!username || !password.current) {
Expand Down Expand Up @@ -148,7 +148,8 @@ function usePassword({ setError }: { setError: React.Dispatch<React.SetStateActi
}
function useSms({ setError }: { setError: React.Dispatch<React.SetStateAction<string>> }) {
const { t } = useTranslation()

// 防止input失去焦点
const _remainTime = useRef(0);
const phoneNumber = useRef('')
const checkValue = useRef('')
const isValidPhoneNumber =
Expand All @@ -171,9 +172,10 @@ function useSms({ setError }: { setError: React.Dispatch<React.SetStateAction<st
const sign = () => request.post<any, ApiResp<Session>>('/api/auth/phone/verify', { phoneNumbers: phoneNumber.current, code: checkValue.current })

const SmsModal = () => {
const [remainTime, setRemainTime] = useState(0);

const [_phone, setPhone] = useState(phoneNumber.current)
const [_code, setCode] = useState(checkValue.current)
const [remainTime, setRemainTime] = useState(_remainTime.current);
useEffect(() => {
if (remainTime <= 0) return;
const interval = setInterval(() => {
Expand All @@ -184,12 +186,21 @@ function useSms({ setError }: { setError: React.Dispatch<React.SetStateAction<st
const getCode: MouseEventHandler = async (e) => {
e.preventDefault()
if (!isValidPhoneNumber()) {
setError(t('Invalid mobile number') || 'Invalid mobile number')
setError(t('Invalid phone number') || 'Invalid phone number')
return
}
setRemainTime(60)
await request.post<any, Session>('/api/auth/phone/sms', { phoneNumbers: phoneNumber.current })
// vaildPhone()
_remainTime.current = 60
try {
const res = await request.post<any, ApiResp<any>>('/api/auth/phone/sms', { phoneNumbers: phoneNumber.current })
if (res.code !== 200 || res.message !== 'successfully') {
throw new Error('Get code failed')
}
} catch (err) {
setError(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'}>
<InputLeftAddon
Expand Down Expand Up @@ -394,7 +405,7 @@ export default function Login(
// 确认密码后注册
const signUpByPassword = async (e: { preventDefault: () => void; }) => {
e.preventDefault()
if(!confirmPassword()){
if (!confirmPassword()) {
return
}
setIsLoading(true)
Expand Down Expand Up @@ -436,7 +447,7 @@ export default function Login(
sx={
{
'> div:not(:last-child):not(.chakra-tabs), > Button:not(:last-child)': {
width:'266px',
width: '266px',
minH: '42px',
mb: '14px',
borderRadius: '4px',
Expand All @@ -451,7 +462,7 @@ export default function Login(
<FormErrorMessage position={'absolute'} top='0' display={'flex'}
bg={'rgba(249, 78, 97, 1)'}
transform={'translateY(-50%)'}
// width={'auto !important'}
// width={'auto !important'}
>
<Img src={warnIcon.src} mr={'8px'}></Img>
<Text color={'#fff'} >{error}</Text>
Expand Down
1 change: 0 additions & 1 deletion frontend/desktop/src/services/backend/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ export const verifyJWT: (token: string) => Promise<string | JwtPayload> = (token
export const generateJWT = (
uid: string
) => {
// console.log('generateJWT', jwtSecret, uid)
return sign({ uid }, jwtSecret, {
expiresIn: '7d'
})
Expand Down
3 changes: 0 additions & 3 deletions frontend/desktop/src/services/backend/db/mongodb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,8 @@ export async function connectToDatabase() {
global.mongodb.on('close', () => {
global.mongodb = null;
})
// global.mongodb.on()
// mongoose.set('strictQuery', true);
await global.mongodb.connect();
return global.mongodb;
// console.log('mongo connected');
} catch (error) {
console.log('error->', 'mongo connect error');
global.mongodb = null;
Expand Down
2 changes: 0 additions & 2 deletions frontend/desktop/src/services/backend/db/verifyCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ type TVerification_Codes = {
async function connectToUserCollection() {
const client = await connectToDatabase();
const collection = client.db().collection<TVerification_Codes>('verification_codes');
// console.log('connect to verification_codes collection')
await collection.createIndex({ createdTime: 1 }, { expireAfterSeconds: 60 * 5 })
return collection;
}
Expand Down Expand Up @@ -41,7 +40,6 @@ export async function checkSendable({ phone }: { phone: string }) {
$lt: new Date().getTime()
}
})
// console.log(result, 'checkable result')
return !result
}
// checkCode
Expand Down
1 change: 0 additions & 1 deletion frontend/desktop/src/services/enable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,5 @@ export const enableSms = () => process.env.SMS_ENABLED === 'true' && !!process.e
!!process.env.ALI_TEMPLATE_CODE
export const enableWechat = () => process.env.WECHAT_ENABLED === 'true' && !!process.env.WECHAT_CLIENT_ID && !!process.env.WECHAT_CLIENT_SECRET;
export const enableRecharge = () => {
console.log(process.env.RECHARGE_ENABLED)
return process.env.RECHARGE_ENABLED === 'true'
};
24 changes: 19 additions & 5 deletions frontend/desktop/src/utils/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,24 @@ export async function getBase64FromRemote(url: string) {

export const getFavorable =
(steps: number[] = [], ratios: number[] = []) =>
(amount: number) => {
let ratio = 0;
(amount: number) => {
let ratio = 0;

const step = [...steps].reverse().findIndex((step) => amount >= step);
if (ratios.length > step && step > -1) ratio = [...ratios].reverse()[step];
return Math.floor((amount * ratio) / 100);
const step = [...steps].reverse().findIndex((step) => amount >= step);
if (ratios.length > step && step > -1) ratio = [...ratios].reverse()[step];
return Math.floor((amount * ratio) / 100);
};
export const retrySerially = <T>(fn: () => Promise<T>, times: number) => new Promise((res, rej) => {
let retries=0
const attempt = () => {
fn().then((_res)=>{

res(_res)
}).catch((error) => {
retries++
console.log(`Attempt ${retries} failed: ${error}`)
retries < times ? attempt() : rej(error);
});
};
attempt();
});

0 comments on commit 613ce0f

Please sign in to comment.