pcpuma_unam_api/src/guards/hcaptcha.guard.ts
2023-02-02 10:50:25 -06:00

38 lines
1.1 KiB
TypeScript

const { verify } = require('hcaptcha');
import {
BadRequestException,
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Observable } from 'rxjs';
@Injectable()
export class HcaptchaGuard implements CanActivate {
constructor(private configService: ConfigService) {}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const secret = this.configService.get<string>('HCAPTCHA_KEY');
const token = context.switchToHttp().getRequest().headers.hcaptcha;
// if (this.configService.get<string>('STATE') !== 'produccion') return true;
if (!token)
throw new BadRequestException('No se mando un token de hcaptcha.');
return verify(secret, token)
.then((data) => {
if (data.success === true) return true;
else throw new ForbiddenException('El token de hcaptcha no es válido.');
})
.catch((err) => {
throw new InternalServerErrorException(
'Ocurrio un error con el hcaptcha.',
);
});
}
}