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

56 lines
1.6 KiB
TypeScript
Raw Normal View History

import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
2025-09-28 11:29:57 +08:00
import { SysSettingsService } from "@certd/lib-server";
import { logger } from "@certd/basic";
import { ICaptchaAddon } from "../../../plugins/plugin-captcha/api.js";
2025-09-28 11:29:57 +08:00
import { AddonGetterService } from "../../pipeline/service/addon-getter-service.js";
@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class CaptchaService {
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
2025-09-28 11:29:57 +08:00
addonGetterService: AddonGetterService;
async getCaptcha(captchaAddonId?:number){
if (!captchaAddonId) {
const settings = await this.sysSettingsService.getPublicSettings()
captchaAddonId = settings.captchaAddonId ?? 0
}
2025-09-28 11:29:57 +08:00
const addon:ICaptchaAddon = await this.addonGetterService.getAddonById(captchaAddonId,true,0)
if (!addon) {
throw new Error('验证码插件还未配置')
}
return await addon.getCaptcha()
}
async doValidate(opts:{form:any,must?:boolean,captchaAddonId?:number}){
if (!opts.captchaAddonId) {
const settings = await this.sysSettingsService.getPublicSettings()
opts.captchaAddonId = settings.captchaAddonId ?? 0
}
2025-09-28 11:29:57 +08:00
const addon = await this.addonGetterService.getById(opts.captchaAddonId,0)
if (!addon) {
if (opts.must) {
throw new Error('请先配置验证码插件');
}
logger.warn('验证码插件还未配置,忽略验证码校验')
return true
}
if (!opts.form) {
throw new Error('请输入验证码');
}
const res = await addon.onValidate(opts.form)
if (!res) {
throw new Error('验证码错误');
}
return true
}
}