后端加入Redis、旋转图片验证接口

This commit is contained in:
2024-08-30 21:34:24 +08:00
parent a69cd3af61
commit 29f2c09a69
15 changed files with 551 additions and 2 deletions

View File

@@ -0,0 +1,41 @@
import { API } from "../Plugs/API/API";
import ServerStdResponse from "../ServerStdResponse";
import captchaSession from "../Plugs/Service/captchaSession";
// 检查人机验证
class CheckCaptcha extends API {
constructor() {
super('POST', '/checkCaptcha');
}
public async onRequset(data: any, res: any) {
let { session, rotateDeg } = data;
if (!session || !rotateDeg) {
return res.json(ServerStdResponse.PARAMS_MISSING);
}
switch (await captchaSession.check(session, rotateDeg)) {
case 0:
// 验证码已过期或服务器错误
res.json(ServerStdResponse.CAPTCHA.NOTFOUND);
break;
case 1:
// 验证通过
res.json(ServerStdResponse.OK);
break;
case -1:
// 超过最大尝试次数
res.json(ServerStdResponse.CAPTCHA.MAX_TRY_COUNT);
break;
case -2:
// 角度不正确
res.json(ServerStdResponse.CAPTCHA.NOTRIGHT);
break;
default:
// 未知错误
res.json(ServerStdResponse.SERVER_ERROR);
break;
}
}
}
export default CheckCaptcha;

View File

@@ -0,0 +1,36 @@
import fs from "fs";
import { API } from "../Plugs/API/API";
import ServerStdResponse from "../ServerStdResponse";
import captchaSession from "../Plugs/Service/captchaSession";
import path from "path";
import sharp from "sharp";
import crypto from 'crypto'
// 获取人机验证图片及标识符
class GetCaptcha extends API {
constructor() {
super('GET', '/captcha');
}
public async onRequset(data: any, res: any) {
const imgsPath = path.join(__dirname, '../assets/captchaImgs');
const fileList = fs.readdirSync(imgsPath)
const imgPath = path.join(imgsPath, fileList[Math.floor(Math.random() * fileList.length)]);
const rotateDeg = Math.floor(Math.random() * 240) + 60;
const img = Buffer.from(await sharp(imgPath).rotate(-rotateDeg).toBuffer()).toString('base64')
const session = crypto.createHash('md5').update(`${Math.random()} ${Date.now()}`).digest('hex');
if (await captchaSession.add(session, rotateDeg)) {
return res.json({
...ServerStdResponse.OK, data: {
img: img,
session: session,
imgPreStr: 'data:image/jpeg;base64,'
}
});
} else {
return res.json(ServerStdResponse.SERVER_ERROR)
}
}
}
export default GetCaptcha;