Files
certd/packages/ui/certd-server/src/modules/basic/service/code-service.ts
T

221 lines
6.8 KiB
TypeScript
Raw Normal View History

2025-01-15 01:05:34 +08:00
import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
2024-11-28 17:36:45 +08:00
import { cache, isDev, randomNumber } from '@certd/basic';
2024-12-11 11:30:32 +08:00
import { SysSettingsService, SysSiteInfo } from '@certd/lib-server';
2024-11-28 17:36:45 +08:00
import { SmsServiceFactory } from '../sms/factory.js';
import { ISmsService } from '../sms/api.js';
import { CodeErrorException } from '@certd/lib-server/dist/basic/exception/code-error-exception.js';
import { EmailService } from './email-service.js';
2024-12-22 14:00:46 +08:00
import { AccessService } from '@certd/lib-server';
import { AccessSysGetter } from '@certd/lib-server';
2024-12-11 11:30:32 +08:00
import { isComm } from '@certd/plus-core';
2023-01-29 13:44:19 +08:00
// {data: '<svg.../svg>', text: 'abcd'}
/**
*/
@Provide()
2025-01-15 01:05:34 +08:00
@Scope(ScopeEnum.Request, { allowDowngrade: true })
2023-01-29 13:44:19 +08:00
export class CodeService {
@Inject()
2024-11-28 17:36:45 +08:00
sysSettingsService: SysSettingsService;
@Inject()
emailService: EmailService;
@Inject()
accessService: AccessService;
2023-01-29 13:44:19 +08:00
/**
*/
async generateCaptcha(randomStr) {
2024-08-28 14:40:50 +08:00
const svgCaptcha = await import('svg-captcha');
2023-01-29 13:44:19 +08:00
const c = svgCaptcha.create();
//{data: '<svg.../svg>', text: 'abcd'}
const imgCode = c.text; // = RandomUtil.randomStr(4, true);
2024-11-28 17:36:45 +08:00
cache.set('imgCode:' + randomStr, imgCode, {
2023-01-29 13:44:19 +08:00
ttl: 2 * 60 * 1000, //过期时间 2分钟
});
return c;
}
async getCaptchaText(randomStr) {
2024-11-28 17:36:45 +08:00
return cache.get('imgCode:' + randomStr);
2023-01-29 13:44:19 +08:00
}
async removeCaptcha(randomStr) {
2024-11-28 17:36:45 +08:00
cache.delete('imgCode:' + randomStr);
2023-01-29 13:44:19 +08:00
}
2024-11-28 17:36:45 +08:00
async checkCaptcha(randomStr: string, userCaptcha: string) {
2023-01-29 13:44:19 +08:00
const code = await this.getCaptchaText(randomStr);
if (code == null) {
throw new Error('验证码已过期');
}
2024-11-28 17:36:45 +08:00
if (code.toLowerCase() !== userCaptcha.toLowerCase()) {
2023-01-29 13:44:19 +08:00
throw new Error('验证码不正确');
}
2024-11-28 17:36:45 +08:00
await this.removeCaptcha(randomStr);
2023-01-29 13:44:19 +08:00
return true;
}
/**
*/
2025-07-24 16:56:22 +08:00
async sendSmsCode(
phoneCode = '86',
mobile: string,
randomStr: string,
opts?: {
duration?: number,
verificationType?: string,
verificationCodeLength?: number,
2025-07-24 16:56:22 +08:00
},
) {
2024-12-01 03:09:29 +08:00
if (!mobile) {
2024-12-01 03:02:59 +08:00
throw new Error('手机号不能为空');
}
if (!randomStr) {
throw new Error('randomStr不能为空');
}
2024-11-28 17:36:45 +08:00
const verificationCodeLength = Math.floor(Math.max(Math.min(opts?.verificationCodeLength || 4, 8), 4));
const duration = Math.floor(Math.max(Math.min(opts?.duration || 5, 15), 1));
2025-07-24 16:56:22 +08:00
2024-11-28 17:36:45 +08:00
const sysSettings = await this.sysSettingsService.getPrivateSettings();
if (!sysSettings.sms?.config?.accessId) {
throw new Error('当前站点还未配置短信');
}
const smsType = sysSettings.sms.type;
const smsConfig = sysSettings.sms.config;
const sender: ISmsService = SmsServiceFactory.createSmsService(smsType);
const accessGetter = new AccessSysGetter(this.accessService);
sender.setCtx({
accessService: accessGetter,
config: smsConfig,
});
const smsCode = randomNumber(verificationCodeLength);
2024-11-28 17:36:45 +08:00
await sender.sendSmsCode({
mobile,
code: smsCode,
phoneCode,
});
2025-07-24 16:56:22 +08:00
const key = this.buildSmsCodeKey(phoneCode, mobile, randomStr, opts?.verificationType);
2024-11-28 17:36:45 +08:00
cache.set(key, smsCode, {
2025-07-24 16:56:22 +08:00
ttl: duration * 60 * 1000, //5分钟
2024-11-28 17:36:45 +08:00
});
2024-11-30 01:57:09 +08:00
return smsCode;
2023-01-29 13:44:19 +08:00
}
/**
2025-07-24 16:56:22 +08:00
*
* @param email 收件邮箱
* @param randomStr
* @param opts title标题 content内容模版 duration有效时间单位分钟 verificationType验证类型
2023-01-29 13:44:19 +08:00
*/
2025-07-24 16:56:22 +08:00
async sendEmailCode(
email: string,
randomStr: string,
opts?: {
title?: string,
content?: string,
duration?: number,
verificationType?: string,
verificationCodeLength?: number,
2025-07-24 16:56:22 +08:00
},
) {
2024-12-01 03:02:59 +08:00
if (!email) {
throw new Error('Email不能为空');
}
if (!randomStr) {
throw new Error('randomStr不能为空');
}
2024-11-28 17:36:45 +08:00
2024-12-11 11:30:32 +08:00
let siteTitle = 'Certd';
if (isComm()) {
const siteInfo = await this.sysSettingsService.getSetting<SysSiteInfo>(SysSiteInfo);
if (siteInfo) {
siteTitle = siteInfo.title || siteTitle;
}
}
const verificationCodeLength = Math.floor(Math.max(Math.min(opts?.verificationCodeLength || 4, 8), 4));
const duration = Math.floor(Math.max(Math.min(opts?.duration || 5, 15), 1));
const code = randomNumber(verificationCodeLength);
2025-07-24 16:56:22 +08:00
const title = `${siteTitle}${!!opts?.title ? opts.title : '验证码'}`;
const content = !!opts.content ? this.compile(opts.content)({code, duration}) : `您的验证码是${code},请勿泄露`;
2024-11-28 17:36:45 +08:00
await this.emailService.send({
2025-07-24 16:56:22 +08:00
subject: title,
content: content,
2024-11-28 17:36:45 +08:00
receivers: [email],
});
2025-07-24 16:56:22 +08:00
const key = this.buildEmailCodeKey(email, randomStr, opts?.verificationType);
2024-11-28 17:36:45 +08:00
cache.set(key, code, {
2025-07-24 16:56:22 +08:00
ttl: duration * 60 * 1000, //5分钟
2024-11-28 17:36:45 +08:00
});
2024-11-30 01:57:09 +08:00
return code;
2024-11-28 17:36:45 +08:00
}
/**
* checkSms
*/
async checkSmsCode(opts: { mobile: string; phoneCode: string; smsCode: string; randomStr: string; verificationType?: string; throwError: boolean; errorNum?: number }) {
2025-07-24 16:56:22 +08:00
const key = this.buildSmsCodeKey(opts.phoneCode, opts.mobile, opts.randomStr, opts.verificationType);
2024-11-28 17:36:45 +08:00
if (isDev()) {
return true;
}
return this.checkValidateCode(key, opts.smsCode, opts.throwError, opts.errorNum);
2024-11-28 17:36:45 +08:00
}
2025-07-24 16:56:22 +08:00
buildSmsCodeKey(phoneCode: string, mobile: string, randomStr: string, verificationType?: string) {
return ['sms', verificationType, phoneCode, mobile, randomStr].filter(item => !!item).join(':');
2024-11-28 17:36:45 +08:00
}
2025-07-24 16:56:22 +08:00
buildEmailCodeKey(email: string, randomStr: string, verificationType?: string) {
return ['email', verificationType, email, randomStr].filter(item => !!item).join(':');
2024-11-28 17:36:45 +08:00
}
2025-08-09 16:59:48 +08:00
checkValidateCode(key: string, userCode: string, throwError = true, errorNum = 3) {
// 记录异常次数key
const err_num_key = key + ':err_num';
2024-11-28 17:36:45 +08:00
//验证图片验证码
const code = cache.get(key);
if (code == null || code !== userCode) {
let maxRetryCount = false;
if (!!code && errorNum > 0) {
const err_num = cache.get(err_num_key) || 0
if(err_num >= errorNum - 1) {
maxRetryCount = true;
cache.delete(key);
cache.delete(err_num_key);
} else {
cache.set(err_num_key, err_num + 1, {
ttl: 30 * 60 * 1000
});
}
}
2024-11-28 17:36:45 +08:00
if (throwError) {
throw new CodeErrorException(!maxRetryCount ? '验证码错误': '验证码错误请获取新的验证码');
2024-11-28 17:36:45 +08:00
}
return false;
}
cache.delete(key);
cache.delete(err_num_key);
2024-11-28 17:36:45 +08:00
return true;
}
checkEmailCode(opts: { randomStr: string; validateCode: string; email: string; verificationType?: string; throwError: boolean; errorNum?: number }) {
2025-07-24 16:56:22 +08:00
const key = this.buildEmailCodeKey(opts.email, opts.randomStr, opts.verificationType);
return this.checkValidateCode(key, opts.validateCode, opts.throwError, opts.errorNum);
2023-01-29 13:44:19 +08:00
}
2025-07-24 16:56:22 +08:00
compile(templateString: string) {
return new Function(
"data",
` with(data || {}) {
return \`${templateString}\`;
}
`
);
}
2023-01-29 13:44:19 +08:00
}