From 187723947fdc7b04a0275d2a42f673bcdaebdefe Mon Sep 17 00:00:00 2001 From: tone <3341154833@qq.com> Date: Thu, 26 Sep 2024 14:22:52 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=20captcha=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=EF=BC=8C=E5=85=81=E8=AE=B8=E5=A4=8D=E7=94=A8session?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/config.ts | 1 + src/lib/Service/CaptchaSession.ts | 20 +++++++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/config.ts b/src/config.ts index 450078b..2a904af 100644 --- a/src/config.ts +++ b/src/config.ts @@ -23,6 +23,7 @@ const config = { useRedis: false, allowMaxTryCount: 5, allowMaxAngleDiff: 8, + allowReuseCount: 2, expriedTimeSec: 60, } }, diff --git a/src/lib/Service/CaptchaSession.ts b/src/lib/Service/CaptchaSession.ts index 4417d40..0674dcd 100644 --- a/src/lib/Service/CaptchaSession.ts +++ b/src/lib/Service/CaptchaSession.ts @@ -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 { + public async add(session: string, rotateDeg: number, reuseCount?: number): Promise { 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; } /**