90 lines
2.0 KiB
TypeScript
90 lines
2.0 KiB
TypeScript
import { Request, Response } from 'express';
|
|
import { CaptchaService } from '../services/captchaService';
|
|
|
|
/**
|
|
* 验证码控制器
|
|
* 处理验证码的生成和验证
|
|
*/
|
|
export class CaptchaController {
|
|
private captchaService: CaptchaService;
|
|
|
|
constructor() {
|
|
this.captchaService = new CaptchaService();
|
|
}
|
|
|
|
/**
|
|
* 生成验证码
|
|
* @param req - Express请求对象
|
|
* @param res - Express响应对象
|
|
*/
|
|
async generateCaptcha(req: Request, res: Response) {
|
|
try {
|
|
const { captchaId, svg } = this.captchaService.generateCaptcha();
|
|
|
|
return res.json({
|
|
success: true,
|
|
data: {
|
|
captchaId,
|
|
svg
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error('生成验证码失败:', error);
|
|
return res.status(500).json({
|
|
success: false,
|
|
message: '生成验证码失败'
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 验证验证码
|
|
* @param req - Express请求对象
|
|
* @param res - Express响应对象
|
|
*/
|
|
async verifyCaptcha(req: Request, res: Response) {
|
|
try {
|
|
const { captchaId, code } = req.body;
|
|
|
|
const result = this.captchaService.verifyCaptcha(captchaId, code);
|
|
|
|
if (!result.success) {
|
|
return res.status(400).json(result);
|
|
}
|
|
|
|
return res.json({
|
|
success: true,
|
|
message: '验证码正确'
|
|
});
|
|
} catch (error) {
|
|
console.error('验证验证码失败:', error);
|
|
return res.status(500).json({
|
|
success: false,
|
|
message: '服务器内部错误'
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 检查验证码是否启用
|
|
* @param req - Express请求对象
|
|
* @param res - Express响应对象
|
|
*/
|
|
async checkCaptchaEnabled(req: Request, res: Response) {
|
|
try {
|
|
const enabled = await this.captchaService.checkCaptchaEnabled();
|
|
|
|
return res.json({
|
|
success: true,
|
|
data: { enabled }
|
|
});
|
|
} catch (error) {
|
|
console.error('检查验证码状态失败:', error);
|
|
return res.status(500).json({
|
|
success: false,
|
|
message: '服务器内部错误'
|
|
});
|
|
}
|
|
}
|
|
}
|