Files
FastGPT/src/pages/api/user/sendEmail.ts
archer 2cc32d1806 feat: 注册限流配置
feat: 页面加载动画
feat: md样式优化
feat: 移动端全屏覆盖
2023-03-05 12:47:09 +08:00

65 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@/service/response';
import { AuthCode } from '@/service/models/authCode';
import { connectToDatabase, User } from '@/service/mongo';
import { sendCode } from '@/service/utils/sendEmail';
import { EmailTypeEnum } from '@/constants/common';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { email, type } = req.query as { email: string; type: `${EmailTypeEnum}` };
if (!email || !type) {
throw new Error('缺少参数');
}
await connectToDatabase();
// 注册人数限流
if (type === EmailTypeEnum.register) {
const maxCount = process.env.MAX_USER ? +process.env.MAX_USER : Infinity;
const userCount = await User.count();
if (userCount >= maxCount) {
throw new Error('当前注册用户已满,请等待名额~');
}
}
let code = '';
for (let i = 0; i < 6; i++) {
code += Math.floor(Math.random() * 10);
}
// 判断 1 分钟内是否有重复数据
const authCode = await AuthCode.findOne({
email,
type,
expiredTime: { $gte: Date.now() + 4 * 60 * 1000 } // 如果有一个记录的过期时间,大于当前+4分钟说明距离上次发送还没到1分钟。因为默认创建时过期时间是未来5分钟
});
if (authCode) {
throw new Error('请勿频繁获取验证码');
}
// 创建 auth 记录
await AuthCode.create({
email,
type,
code
});
// 发送验证码
await sendCode(email as string, code, type as `${EmailTypeEnum}`);
jsonRes(res, {
message: '发送验证码成功'
});
} catch (err) {
jsonRes(res, {
code: 500,
error: err
});
}
}