Skip to content

A middleware for AdonisJS to keep your web applications secure from bots using hCaptcha

License

Notifications You must be signed in to change notification settings

NerdyLuffy/adonisjs-hcaptcha

Repository files navigation

adonisjs-hcaptcha

A package to keep your AdonisJS applications safe from bots, spam and protect your user privacy


github-actions-image npm-image license-image synk-image


Installation

Install and configure the package in your Adonis project.
# npm
npm i adonisjs-hcaptcha
node ace configure adonisjs-hcaptcha

# yarn
yarn add adonisjs-hcaptcha
node ace configure adonisjs-hcaptcha

Usage

Step 1: Registration

Signup for a account on hCaptcha website Login and follow the steps to get your secret and site key

Step 2: Add variables in `.env` file

HCAPTCHA_SECRET_KEY=YOUR_SECRET_KEY 
HCAPTCHA_SITE_KEY=YOUR_SITE_KEY

Step 3: Add validation in the `.env.ts` file

import Env from '@ioc:Adonis/Core/Env'

export default Env.rules({
  // ....
  HCAPTCHA_SITE_KEY: Env.schema.string(),
  HCAPTCHA_SECRET_KEY: Env.schema.string(),
})

Step 4: Add middleware to `start/kernel.ts`

Server.middleware.registerNamed({
  // ....
  hcaptcha: () => import('App/Middleware/Hcaptcha'),
})

Step 5: Add middleware to your route

Route.post('login', 'UserController.login').middleware('hcaptcha')

The new middleware will check for h-captcha-response field in request input

h-captcha-response field will contain the unique one time non repeating token which will be validated with hCaptcha to make sure its not a bot

Step 6: Check response in your controller

export default class UsersController {
  public async index({ hcaptcha }: HttpContextContract) {
    if (hcaptcha.success) {
      // Do some action
    }
    // Throw error
  }
}