I am trying to implement a server-side validation for reCaptcha using Nestjs and I want to if I should implement this as a module or as a service for modules(such as a self written user authentication module) that would require the use of reCaptcha.
I solved it by creating a seperate RecaptchaGuard.
// recaptcha.guard.ts
import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpService,
  ForbiddenException,
} from "@nestjs/common";
@Injectable()
export class RecaptchaGuard implements CanActivate {
  constructor(private readonly httpService: HttpService) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const { body } = context.switchToHttp().getRequest();
    const { data } = await this.httpService
      .post(
        `https://www.google.com/recaptcha/api/siteverify?response=${body.recaptchaValue}&secret=${process.env.RECAPTCHA_SECRET}`
      )
      .toPromise();
    if (!data.success) {
      throw new ForbiddenException();
    }
    return true;
  }
}
Next you can simply apply the recaptcha guard on a controller.
// app.controller.ts
import { Controller, Post, UseGuard } from '@nestjs/common';
import { RecaptchaGuard } from './recaptcha.guard.ts'
    
@Controller()
export class AppController {
 @Post()
 @UseGuard(RecaptchaGuard)
 async postForm(){
  //
 }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With