Fixed Captcha

This commit is contained in:
SepehrYahyaee
2026-05-31 14:01:04 +03:30
parent 389133e1c9
commit 2b7192151d
6 changed files with 225 additions and 137 deletions

View File

@@ -1,4 +1,5 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { randomUUID } from "node:crypto";
import {
CaptchaAuthErrorCode,
@@ -15,27 +16,43 @@ export class CaptchaChallengeService {
private readonly captchaService: CaptchaService,
private readonly hashService: HashService,
private readonly captchaChallengeDbService: CaptchaChallengeDbService,
private readonly configService: ConfigService,
) {}
async issue(): Promise<CaptchaResponseDto> {
const generated = this.captchaService.generate();
const captchaId = randomUUID();
const answerHash = await this.hashService.hash(
this.captchaService.normalizeAnswer(generated.text),
);
await this.captchaChallengeDbService.create({
if (this.configService.get<string>("NODE_ENV") === "development") {
const answerHash = await this.hashService.hash(
this.captchaService.normalizeAnswer(generated.text),
);
const result = {
captchaId,
answerHash:
this.configService.get<string>("NODE_ENV") === "development"
? answerHash
: "",
image: generated.image,
expiresAt: generated.expiresAt,
expireAt: new Date(generated.expiresAt),
usedAt: null,
};
}
const result = {
captchaId,
answerHash,
image: generated.image,
expiresAt: generated.expiresAt,
expireAt: new Date(generated.expiresAt),
usedAt: null,
});
};
await this.captchaChallengeDbService.create(result);
return {
captchaId,
text: generated.text, /* TODO: REMOVE THIS FOR PROD*/
text: generated.text /* TODO: REMOVE THIS FOR PROD*/,
image: generated.image,
expiresAt: generated.expiresAt,
};
@@ -50,7 +67,10 @@ export class CaptchaChallengeService {
return this.decodeImage(challenge.image);
}
async verify(captchaId: string | undefined, answer: string | undefined): Promise<void> {
async verify(
captchaId: string | undefined,
answer: string | undefined,
): Promise<void> {
if (!captchaId?.trim()) {
throwCaptchaAuthError(CaptchaAuthErrorCode.CAPTCHA_REQUIRED);
}

View File

@@ -1,13 +1,17 @@
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { HydratedDocument } from "mongoose";
@Schema({ collection: "captcha-challenges", timestamps: true, versionKey: false })
@Schema({
collection: "captcha-challenges",
timestamps: true,
versionKey: false,
})
export class CaptchaChallenge {
@Prop({ required: true, unique: true, index: true })
captchaId: string;
@Prop({ required: true })
answerHash: string;
@Prop()
answerHash?: string;
@Prop({ required: true })
image: string;