Skip to content

Commit

Permalink
fix(desktop):fix verification code restriction (#4449)
Browse files Browse the repository at this point in the history
  • Loading branch information
xudaotutou authored Jan 2, 2024
1 parent 1ea7542 commit 873894f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
10 changes: 7 additions & 3 deletions frontend/desktop/src/pages/api/auth/phone/sms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,18 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (!enableSms()) {
throw new Error('SMS is not enabled');
}
const { phoneNumbers } = req.body;
if (!(await checkSendable(phoneNumbers))) {
const { phoneNumbers } = req.body as { phoneNumbers?: string };
if (!phoneNumbers)
return jsonRes(res, {
message: 'phoneNumbers is invalid',
code: 400
});
if (!(await checkSendable({ phone: phoneNumbers }))) {
return jsonRes(res, {
message: 'code already sent',
code: 400
});
}

// randomly generate six bit check code
const code = Math.floor(Math.random() * 900000 + 100000).toString();
const sendSmsRequest = new dysmsapi.SendSmsRequest({
Expand Down
15 changes: 7 additions & 8 deletions frontend/desktop/src/services/backend/db/verifyCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { connectToDatabase } from './mongodb';
type TVerification_Codes = {
phone: string;
code: string;
createdTime: number;
createdAt: Date;
};

async function connectToUserCollection() {
const client = await connectToDatabase();
const collection = client.db().collection<TVerification_Codes>('verification_codes');
await collection.createIndex({ createdTime: 1 }, { expireAfterSeconds: 60 * 5 });
await collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 60 * 5 });
return collection;
}

Expand All @@ -23,7 +23,7 @@ export async function addOrUpdateCode({ phone, code }: { phone: string; code: st
{
$set: {
code,
createdTime: new Date().getTime()
createdAt: new Date()
}
},
{
Expand All @@ -37,10 +37,9 @@ export async function checkSendable({ phone }: { phone: string }) {
const codes = await connectToUserCollection();
const result = await codes.findOne({
phone,
createdTime: {
createdAt: {
// 在区间范围内找到就是已经发送过了,不能再发了
$gt: new Date().getTime() - 60 * 1000,
$lt: new Date().getTime()
$gt: new Date(new Date().getTime() - 60 * 1000)
}
});
return !result;
Expand All @@ -51,9 +50,9 @@ export async function checkCode({ phone, code }: { phone: string; code: string }
const result = await codes.findOne({
phone,
code,
createdTime: {
createdAt: {
// 5分钟内有效
$gt: new Date().getTime() - 5 * 60 * 1000
$gt: new Date(new Date().getTime() - 5 * 60 * 1000)
}
});
return !!result;
Expand Down

0 comments on commit 873894f

Please sign in to comment.