All Projects → DarkGhostHunter → Captchavel

DarkGhostHunter / Captchavel

Licence: mit
Integrate reCAPTCHA into your Laravel app better than the Big G itself!

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Captchavel

Nocaptcha
🛂 Helper for Google's new noCAPTCHA (reCAPTCHA v2 & v3)
Stars: ✭ 313 (+682.5%)
Mutual labels:  laravel, recaptcha
Laravel Recaptcha
Google ReCaptcha package for Laravel
Stars: ✭ 273 (+582.5%)
Mutual labels:  laravel, recaptcha
Scrutiny
Ensure your laravel-based project is running in the correct server environment
Stars: ✭ 36 (-10%)
Mutual labels:  laravel
Laravel 2c2p
Laravel 2C2P package
Stars: ✭ 39 (-2.5%)
Mutual labels:  laravel
Laravel Queue Database Ph4
Laravel Database Queue with Optimistic locking
Stars: ✭ 37 (-7.5%)
Mutual labels:  laravel
Laravel Support
Rinvex common support helpers, contracts, and traits required by various Rinvex packages. Validator functionality, and basic controller included out-of-the-box.
Stars: ✭ 36 (-10%)
Mutual labels:  laravel
Revision
Revisions for Eloquent Models
Stars: ✭ 37 (-7.5%)
Mutual labels:  laravel
Nova Bar Metrics
A Laravel Nova tool for bar chart metrics and frequency distributions.
Stars: ✭ 36 (-10%)
Mutual labels:  laravel
Adaptcms
AdaptCMS is an open source CMS that is made for complete control of your website, easiness of use and easily adaptable to any type of website. It's made easy with advanced custom fields, a very simple but powerful template system and much more.
Stars: ✭ 39 (-2.5%)
Mutual labels:  laravel
Stationery Cms
💡基于laravel-admin1.6.0开发的办公用品管理系统,含excel导出、查询快递功能
Stars: ✭ 37 (-7.5%)
Mutual labels:  laravel
Lara Eye
Filter your Query\Builder using a structured query language
Stars: ✭ 39 (-2.5%)
Mutual labels:  laravel
Laravel Ip Gateway
Laravel IP Gateway
Stars: ✭ 37 (-7.5%)
Mutual labels:  laravel
Laravel Personality Insights
👩 👱 Using IBM Watson Personality Insights Service with Laravel 5
Stars: ✭ 36 (-10%)
Mutual labels:  laravel
Api Tester
API tester for laravel-admin
Stars: ✭ 38 (-5%)
Mutual labels:  laravel
Ys Tinify Laravel
Tinify API support with laravel
Stars: ✭ 36 (-10%)
Mutual labels:  laravel
Http Basic Auth Guard
HTTP Basic Auth Guard for Lumen 5.x
Stars: ✭ 39 (-2.5%)
Mutual labels:  laravel
Laravel Qrcode Ecommerce
This is a complete laravel project that handles qrcodes, payments, api/microservices, and ecommerce
Stars: ✭ 36 (-10%)
Mutual labels:  laravel
Nuswhispers
NUSWhispers source.
Stars: ✭ 36 (-10%)
Mutual labels:  laravel
Mingyuyue
古诗词取名后台
Stars: ✭ 37 (-7.5%)
Mutual labels:  laravel
Freelancers Market
Laravel Project to help freelance websites clients and freelancers to find each other.
Stars: ✭ 39 (-2.5%)
Mutual labels:  laravel

Franck V. - Unsplash (UL) #JjGXjESMxOY

Latest Version on Packagist License Coverage Status Maintainability

Captchavel

Integrate reCAPTCHA into your Laravel app better than the Big G itself!

It uses your Laravel HTTP Client and HTTP/2, making your app fast. You only need a couple of lines to integrate.

Table of Contents

Requirements

  • Laravel 8.x
  • PHP 8.0

If you need support for old versions, consider sponsoring or donating.

Installation

You can install the package via composer:

composer require darkghosthunter/captchavel

Set up

Add the reCAPTCHA keys for your site to the environment file of your project. You can add each of them for reCAPTCHA v2 checkbox, invisible, Android, and v3 (score).

If you don't have one, generate it in your reCAPTCHA Admin panel.

RECAPTCHA_V2_CHECKBOX_SECRET=6t5geA1UAAAAAN...
RECAPTCHA_V2_CHECKBOX_KEY=6t5geA1UAAAAAN...

RECAPTCHA_V2_INVISIBLE_SECRET=6t5geA2UAAAAAN...
RECAPTCHA_V2_INVISIBLE_KEY=6t5geA2UAAAAAN...

RECAPTCHA_V2_ANDROID_SECRET=6t5geA3UAAAAAN...
RECAPTCHA_V2_ANDROID_KEY=6t5geA3UAAAAAN...

RECAPTCHA_V3_SECRET=6t5geA4UAAAAAN...
RECAPTCHA_V3_KEY=6t5geA4UAAAAAN...

This allows you to check different reCAPTCHA mechanisms using the same application, in different environments.

Captchavel already comes with v2 keys for local development. For v3, you will need to create your own set of credentials.

Usage

After you integrate reCAPTCHA into your frontend or Android app, set the Captchavel middleware in the routes you want:

  • recaptcha.v2 for Checkbox, Invisible and Android challenges.
  • recaptcha.v3 for Score driven interaction.

Checkbox, Invisible and Android challenges

Add the recaptcha.v2 middleware to your POST routes. The middleware will catch the g-recaptcha-response input and check if it's valid.

  • recaptcha.v2:checkbox for explicitly rendered checkbox challenges.
  • recaptcha.v2:invisible for invisible challenges.
  • recaptcha.v2:android for Android app challenges.

When the validation fails, the user will be redirected back to the form route, or a JSON response will be returned with the validation errors.

Route::post('login', '[email protected]')
    ->middleware('recaptcha.v2:checkbox');

You can change the input name from g-recaptcha-response to a custom using a second parameter, like recaptcha.v2:checkbox,_recaptcha.

Score driven interaction

The reCAPTCHA v3 middleware works differently from v2. This is a score-driven challenge between 0.0 and 1.0 where robots will get lower scores than humans. The default threshold is 0.5.

Simply add the recaptcha.v3 middleware to your route:

Route::post('comment', '[email protected]')
    ->middleware('recaptcha.v3');

Once the challenge has been received, you will have access to two methods from the Request instance: isHuman() and isRobot(), which return true or false:

public function store(Request $request, Post $post)
{
    $request->validate([
        'body' => 'required|string|max:255'
    ]);
    
    $comment = $post->comment()->make($request->only('body'));
    
    // Flag the comment as "moderated" if it was a written by robot. 
    $comment->moderated = $request->isRobot();
    
    $comment->save();
    
    return view('post.comment.show', ['comment' => $comment]);
}

Threshold, action and input name

The middleware accepts three parameters in the following order:

  1. Threshold: Values above or equal are considered human.
  2. Action: The action name to optionally check against.
  3. Input: The name of the reCAPTCHA input to verify.
Route::post('comment', '[email protected]')
    ->middleware('recaptcha.v3:0.7,login,custom-recaptcha-input');

When checking the action name, ensure your Frontend action matches

Faking robot and human scores

You can easily fake a reCAPTCHA v3 response in your local development by setting CAPTCHAVEL_FAKE to true.

CAPTCHAVEL_FAKE=true

Then, you can fake a low-score response by adding an is_robot a checkbox, respectively.

<form id='login' method="POST">
  <input type="email" name="email">
  <input type="password" name="password">
  <input type="checkbox" name="is_robot" checked>
  <button class="g-recaptcha" data-sitekey="{{ captchavel('invisible') }}" data-callback='onSubmit'>Login</button>
  <br/>
</form>

Frontend integration

Check the official reCAPTCHA documentation to integrate the reCAPTCHA script in your frontend, or inside your Android application.

You can use the captchavel() helper to output the site key depending on the challenge version you want to render: checkbox, invisible, android or score (v3).

<form id='login' method="POST">
  <input type="email" name="email">
  <input type="password" name="password">
  
  <button class="g-recaptcha" data-sitekey="{{ captchavel('invisible') }}" data-callback='onSubmit'>Login</button>
  <br/>
</form>

You can also retrieve the key using android for Android apps.

Advanced configuration

Captchavel is intended to work out-of-the-box, but you can publish the configuration file for fine-tuning and additional reCAPTCHA verification.

php artisan vendor:publish --provider="DarkGhostHunter\Captchavel\CaptchavelServiceProvider"

You will get a config file with this array:

<?php

return [
    'enable' => env('CAPTCHAVEL_ENABLE',  false),
    'fake' => env('CAPTCHAVEL_FAKE', false),
    'hostname' => env('RECAPTCHA_HOSTNAME'),
    'apk_package_name' => env('RECAPTCHA_APK_PACKAGE_NAME'),
    'threshold' => 0.5,
    'credentials' => [
        // ...
    ]
];

Enable Switch

CAPTCHAVEL_ENABLE=true

The main switch to enable or disable Captchavel middleware. This can be handy to enable on some local environments to check real interaction using the included localhost test keys.

When switched off, the g-recaptcha-response won't be validated in the Request input, so you can safely disregard any frontend script or reCAPTCHA tokens or boxes.

Fake responses

CAPTCHAVEL_FAKE=true

Setting this to true will allow your application to fake v3-score responses from reCAPTCHA servers.

This is automatically set to true when running unit tests.

Hostname and APK Package Name

RECAPTCHA_HOSTNAME=myapp.com
RECAPTCHA_APK_PACKAGE_NAME=my.package.name

If you are not verifying the Hostname or APK Package Name in your reCAPTCHA Admin Panel, you will have to issue the strings in the environment file.

When the reCAPTCHA response from the servers is retrieved, it will be checked against these values when present. In case of mismatch, a validation exception will be thrown.

Threshold

return [
    'threshold' => 0.4
];

Default threshold to check against reCAPTCHA v3 challenges. Values equal or above will be considered as human.

If you're not using reCAPTCHA v3, or you're fine with the default, leave this alone. You can still override the default in a per-route basis.

Credentials

return [
    'credentials' => [
        // ...
    ]
];

Here is the full array of reCAPTCHA credentials to use depending on the version. Do not change the array unless you know what you're doing.

Testing with Captchavel

When unit testing your application, this package automatically fakes reCAPTCHA responses.

When mocking requests, there is no need to add any reCAPTCHA token or secrets in your tests.

When using reCAPTCHA v3 (score), you can fake a response made by a human or robot by simply using the fakeHuman() and fakeRobot() methods, which will score 1.0 or 0.0 respectively.

<?php

use DarkGhostHunter\Captchavel\Facades\Captchavel;

// Let the user login normally.
Captchavel::fakeHuman();

$this->post('login', [
    'email' => '[email protected]',
    'password' => '123456',
])->assertRedirect('user.welcome');

// ... but if it's a robot, force him to use 2FA.
Captchavel::fakeRobot();

$this->post('login', [
    'email' => '[email protected]',
    'password' => '123456',
])->assertViewIs('login.2fa');

Alternatively, fakeScore() method that will fake any score you set.

Fake responses don't come with actions, hostnames or APK package names.

Events

When a reCAPTCHA challenge is resolved, whatever result is received, the ReCaptchaResponseReceived event fires with the HTTP Request instance and the reCAPTCHA response.

Using your own reCAPTCHA middleware

You may want to create your own reCAPTCHA middleware. Instead of doing one from scratch, you can extend the BaseReCaptchaMiddleware.

<?php

namespace App\Http\Middleware;

use Closure;
use DarkGhostHunter\Captchavel\Http\Middleware\BaseReCaptchaMiddleware;

class MyReCaptchaMiddleware extends BaseReCaptchaMiddleware
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $input = 'g-recaptcha-response';
        
        $this->validateRequest($request, $input);

        $response = $this->retrieve($request, $input, 2, 'checkbox');

        if ($response->isInvalid()) {
            throw $this->validationException($input, 'Complete the reCAPTCHA challenge');
        }

        return $next($request);
    }
}

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].