优化 captcha服务,允许复用session
This commit is contained in:
@@ -23,6 +23,7 @@ const config = {
|
||||
useRedis: false,
|
||||
allowMaxTryCount: 5,
|
||||
allowMaxAngleDiff: 8,
|
||||
allowReuseCount: 2,
|
||||
expriedTimeSec: 60,
|
||||
}
|
||||
},
|
||||
|
||||
@@ -10,6 +10,7 @@ interface CaptchaSessionRedisDataJSON {
|
||||
rotateDeg: number;
|
||||
tryCount: number;
|
||||
isPassed: boolean;
|
||||
allowReuseCount: number;
|
||||
expiredTimestamp?: number;
|
||||
}
|
||||
|
||||
@@ -26,6 +27,7 @@ class _CaptchaSession {
|
||||
private readonly logger = new Logger('Service', 'captchaSession');
|
||||
private readonly AllowMaxTryCount: number = config.service.captchaSession.allowMaxTryCount;
|
||||
private readonly AllowMaxAngleDiff: number = config.service.captchaSession.allowMaxAngleDiff;
|
||||
private readonly AllowReuseCount: number = config.service.captchaSession.allowReuseCount;
|
||||
private readonly ExpriedTimeSec: number = config.service.captchaSession.expriedTimeSec;
|
||||
private readonly RedisCommonKey: string = 'Service:captchaSession:';
|
||||
private redisConnection?: Redis;
|
||||
@@ -101,12 +103,14 @@ class _CaptchaSession {
|
||||
*
|
||||
* @param session 验证会话标识符
|
||||
* @param rotateDeg 图片旋转角度
|
||||
* @param reuseCount 可选,允许重复使用的次数
|
||||
* @returns true存储成功 false存储失败
|
||||
*/
|
||||
public async add(session: string, rotateDeg: number): Promise<boolean> {
|
||||
public async add(session: string, rotateDeg: number, reuseCount?: number): Promise<boolean> {
|
||||
const result: CaptchaSessionRedisDataJSON = {
|
||||
rotateDeg: rotateDeg,
|
||||
tryCount: 0,
|
||||
allowReuseCount: reuseCount || this.AllowReuseCount,
|
||||
isPassed: false,
|
||||
}
|
||||
|
||||
@@ -142,9 +146,19 @@ class _CaptchaSession {
|
||||
const result = await this.get(session);
|
||||
if (!result)
|
||||
return false;
|
||||
if (result.isPassed)
|
||||
if (!result.isPassed)
|
||||
return false;
|
||||
|
||||
// 验证通过,允许重复使用次数-1
|
||||
result.allowReuseCount--;
|
||||
if(result.allowReuseCount == 0)
|
||||
this.remove(session);
|
||||
return result.isPassed;
|
||||
else if(this.useRedis){
|
||||
await this.redisConnection!.del(this.RedisCommonKey + session);
|
||||
await this.redisConnection!.set(this.RedisCommonKey + session, JSON.stringify(result));
|
||||
this.redisConnection!.expire(this.RedisCommonKey + session, this.ExpriedTimeSec);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user