perf: 登录支持双重认证

This commit is contained in:
xiaojunnuo
2025-04-17 22:34:21 +08:00
parent 8e50e5dee3
commit 48aef25b3f
16 changed files with 132 additions and 55 deletions
@@ -1,8 +1,7 @@
import {ALL, Body, Controller, Inject, Post, Provide} from '@midwayjs/core';
import {BaseController, SysSafeSetting} from '@certd/lib-server';
import {cloneDeep} from 'lodash-es';
import {SafeService} from "../../../modules/sys/settings/safe-service.js";
import {isPlus} from "@certd/plus-core";
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { BaseController, SysSafeSetting } from "@certd/lib-server";
import { cloneDeep } from "lodash-es";
import { SafeService } from "../../../modules/sys/settings/safe-service.js";
/**
@@ -25,9 +24,6 @@ export class SysSettingsController extends BaseController {
@Post("/save", { summary: "sys:settings:edit" })
async safeSave(@Body(ALL) body: any) {
if (!isPlus()) {
throw new Error('本功能需要开通专业版')
}
await this.safeService.saveSafeSetting(body);
return this.ok({});
}
@@ -63,7 +63,7 @@ export class LoginController extends BaseController {
) {
const token = await this.loginService.loginByTwoFactor({
loginCode: body.loginCode,
loginId: body.loginId,
verifyCode: body.verifyCode,
});
@@ -1,7 +1,7 @@
import { Provide } from '@midwayjs/core';
import { IMidwayKoaContext, IWebMiddleware, NextFunction } from '@midwayjs/koa';
import { logger } from '@certd/basic';
import { Result } from '@certd/lib-server';
import { Result, TextException } from "@certd/lib-server";
@Provide()
export class GlobalExceptionMiddleware implements IWebMiddleware {
@@ -14,12 +14,15 @@ export class GlobalExceptionMiddleware implements IWebMiddleware {
await next();
logger.info('请求完成:', url, Date.now() - startTime + 'ms');
} catch (err) {
if(err instanceof TextException){
delete err.stack
}
logger.error('请求异常:', url, Date.now() - startTime + 'ms', err);
ctx.status = 200;
if (err.code == null || typeof err.code !== 'number') {
err.code = 1;
}
ctx.body = Result.error(err.code, err.message);
ctx.body = Result.error(err.code, err.message,err.data);
}
};
}
@@ -158,21 +158,21 @@ export class LoginService {
//要检查
const randomKey = utils.id.simpleNanoId(12)
cache.set(`login_2fa_code:${randomKey}`, userId, {
ttl: 60 * 1000,
ttl: 60 * 1000 * 2,
})
throw new Need2FAException('已开启多重认证,请在60秒内输入验证码')
throw new Need2FAException('已开启多重认证,请在2分钟内输入OPT验证码',randomKey)
}
}
async loginByTwoFactor(req: { loginCode: string; verifyCode: string }) {
async loginByTwoFactor(req: { loginId: string; verifyCode: string }) {
//检查是否开启多重认证
if (!isPlus()) {
throw new Error('本功能需要开通专业版')
}
const userId = cache.get(`login_2fa_code:${req.loginCode}`)
const userId = cache.get(`login_2fa_code:${req.loginId}`)
if (!userId) {
throw new AuthException('登录状态已失效,请重新登录')
throw new AuthException('已超时,请返回重新登录')
}
await this.twoFactorService.verifyAuthenticatorCode(userId, req.verifyCode)