添加 人机验证服务Demo接口
This commit is contained in:
35
src/api/CheckCaptcha.ts
Normal file
35
src/api/CheckCaptcha.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { API, RequestData } from "@lib/API/API";
|
||||
import ServerStdResponse from "@lib/ServerResponse/ServerStdResponse";
|
||||
import { Response } from "express";
|
||||
import CaptchaSession from "@lib/Service/CaptchaSession";
|
||||
// 验证人机验证
|
||||
class CheckCaptcha extends API {
|
||||
constructor() {
|
||||
super('POST', '/captcha');
|
||||
}
|
||||
|
||||
public async onRequset(data: RequestData, res: Response): Promise<void> {
|
||||
// 获取session以及angle
|
||||
const { session, angle } = data;
|
||||
if (!session || !angle) {
|
||||
res.json({ ...ServerStdResponse.ERROR });
|
||||
return;
|
||||
}
|
||||
switch (await CaptchaSession.check(session, angle)) {
|
||||
case 0:// 验证已过期或服务器错误
|
||||
res.json({ ...ServerStdResponse.ERROR, message: 'expired or server error' });
|
||||
break;
|
||||
case 1:// 通过验证
|
||||
res.json(ServerStdResponse.OK);
|
||||
break;
|
||||
case -1:// 超过最大允许尝试次数
|
||||
res.json({ ...ServerStdResponse.ERROR, message: 'max try count' });
|
||||
break;
|
||||
case -2:// 角度差异过大
|
||||
res.json({ ...ServerStdResponse.ERROR, message: 'error angle' });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default CheckCaptcha;
|
||||
30
src/api/GetCaptcha.ts
Normal file
30
src/api/GetCaptcha.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { API, RequestData } from "@lib/API/API";
|
||||
import ServerStdResponse from "@lib/ServerResponse/ServerStdResponse";
|
||||
import { Response } from "express";
|
||||
import crypto from 'crypto'
|
||||
import CaptchaSession from "@lib/Service/CaptchaSession";
|
||||
// 获取人机验证
|
||||
class GetCaptcha extends API {
|
||||
constructor() {
|
||||
super('GET', '/captcha');
|
||||
}
|
||||
|
||||
public async onRequset(data: RequestData, res: Response): Promise<void> {
|
||||
// 生成角度及session
|
||||
const angle = Math.floor(60 + 240 * Math.random());
|
||||
const session = crypto.createHash('md5').update(`${Math.random()} ${Date.now()}`).digest('hex');
|
||||
|
||||
// 存储验证信息
|
||||
if (await CaptchaSession.add(session, angle)) {
|
||||
res.json({...ServerStdResponse.OK, data: {
|
||||
session,
|
||||
// ... other data
|
||||
}})
|
||||
} else {
|
||||
this.logger.error(`Failed to store session [${session}] and rotation angle [${angle}]`);
|
||||
res.json(ServerStdResponse.ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default GetCaptcha;
|
||||
Reference in New Issue
Block a user