Giter Site home page Giter Site logo

biscolab / laravel-recaptcha Goto Github PK

View Code? Open in Web Editor NEW
505.0 4.0 58.0 626 KB

Google ReCaptcha package for Laravel

Home Page: https://github.com/biscolab/laravel-recaptcha#readme

License: MIT License

PHP 100.00%
recaptcha laravel-recaptcha php laravel data-validation form-validation google-recaptcha recaptcha-validation google-recaptcha-v2 laravel5

laravel-recaptcha's Introduction

Laravel ReCAPTCHA is a very simply-to-use Laravel 5 package to embed Google reCAPTCHA in your application.

Build Status Scrutinizer Code Quality Code Coverage Packagist version Downloads MIT License

What is reCAPTCHA?

Google developers says: "reCAPTCHA protects you against spam and other types of automated abuse. Here, we explain how to add reCAPTCHA to your site or application."

You can find further info at Google reCAPTCHA Developer's Guide

reCAPTCHA available versions

At this moment there are 3 versions available (for web applications):

Get your key first!

First of all you have to create your own API keys here

Follow the instructions and at the end of the process you will find Site key and Secret key. Keep them close..you will need soon!

System requirements

Package version reCaptcha version PHP version Laravel version
6.1 v3, v2 Invisible, v2 Checkbox 7.3 or greater 7, 8, 9, 10, 11
6.0 v3, v2 Invisible, v2 Checkbox 7.3 or greater 7, 8, 9, 10
5.x v3, v2 Invisible, v2 Checkbox 7.3 or greater 7, 8, 9
4.2.x to 4.4.x v3, v2 Invisible, v2 Checkbox 7.1 or greater 5.5 or greater, 6, 7, 8
4.1.x v3, v2 Invisible, v2 Checkbox 7.1 or greater 5.5 or greater, 6, 7
4.0.x v3, v2 Invisible, v2 Checkbox 7.1 or greater 5.5 or greater, 6
3.x v3, v2 Invisible, v2 Checkbox 7.1 or greater 5.5 or greater, 6 (*)
2.x v2 Invisible, v2 Checkbox 5.5.9, 7.0 or greater 5.0 or greater

(*) Version 3.6.1 is Laravel 6 ready

Composer

You can install the package via composer:

$ composer require biscolab/laravel-recaptcha

Laravel 5.5 (or greater) uses package auto-discovery, so doesn't require you to manually add the Service Provider, but if you don't use auto-discovery ReCaptchaServiceProvider must be registered in config/app.php:

'providers' => [
    ...
    Biscolab\ReCaptcha\ReCaptchaServiceProvider::class,
];

You can use the facade for shorter code. Add ReCaptcha to your aliases:

'aliases' => [
    ...
    'ReCaptcha' => Biscolab\ReCaptcha\Facades\ReCaptcha::class,
];

Publish package

Create config/recaptcha.php configuration file using the following artisan command:

$ php artisan vendor:publish --provider="Biscolab\ReCaptcha\ReCaptchaServiceProvider"

Set the environment

Add your API Keys

Open .env file and set RECAPTCHA_SITE_KEY and RECAPTCHA_SECRET_KEY:

# in your .env file
RECAPTCHA_SITE_KEY=<YOUR_API_SITE_KEY>
RECAPTCHA_SECRET_KEY=<YOUR_API_SECRET_KEY>
RECAPTCHA_SKIP_IP=<YOUR_IP_LIST>

RECAPTCHA_SKIP_IP (since v5.2.0, not required, CSV format ) allows you to add a list of IP/CIDR (netmask included). It will be the value of skip_ip

The following environment variables have been removed!!! Now only sensitive informations as API keys are allowed as environment variables, that means you have to set configuration values in config/recaptcha.php

  • RECAPTCHA_DEFAULT_VERSION
  • RECAPTCHA_CURL_TIMEOUT
  • RECAPTCHA_DEFAULT_VALIDATION_ROUTE
  • RECAPTCHA_DEFAULT_TOKEN_PARAMETER_NAME
  • RECAPTCHA_DEFAULT_LANGUAGE

Complete configuration

Open config/recaptcha.php configuration file and set version:

return [
    'api_site_key'                  => env('RECAPTCHA_SITE_KEY', ''),
    'api_secret_key'                => env('RECAPTCHA_SECRET_KEY', ''),
    // changed in v4.0.0
    'version'                       => 'v2', // supported: "v3"|"v2"|"invisible"
    // @since v3.4.3 changed in v4.0.0
    'curl_timeout'                  => 10,
    'skip_ip'                       => env('RECAPTCHA_SKIP_IP', []), // array of IP addresses - String: dotted quad format e.g.: "127.0.0.1", IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed
    // @since v3.2.0 changed in v4.0.0
    'default_validation_route'      => 'biscolab-recaptcha/validate',
    // @since v3.2.0 changed in v4.0.0
    'default_token_parameter_name' => 'token',
    // @since v3.6.0 changed in v4.0.0
    'default_language'             => null,
    // @since v4.0.0
    'default_form_id'              => 'biscolab-recaptcha-invisible-form', // Only for "invisible" reCAPTCHA
    // @since v4.0.0
    'explicit'                     => false, // true|false
    // @since v4.3.0
    'api_domain'                   => "www.google.com", // default value is "www.google.com"
    // @since v5.1.0
    'empty_message'                => false,
    // @since v5.1.0
    'error_message_key'            => 'validation.recaptcha',
    // @since v4.0.0
    'tag_attributes'               => [
        'theme'                    => 'light', // "light"|"dark"
        'size'                     => 'normal', // "normal"|"compact"
        'tabindex'                 => 0,
        'callback'                 => null, // DO NOT SET "biscolabOnloadCallback"
        'expired-callback'         => null, // DO NOT SET "biscolabOnloadCallback"
        'error-callback'           => null, // DO NOT SET "biscolabOnloadCallback"
    ]
];
Key Type Description Default
api_site_key and api_secret_key string reCAPTCHA keys you have to create in order to perform Google API authentication. For more information about Site Key and Secret Key please visit Google reCAPTCHA developer documentation ''
version string indicates the reCAPTCHA version (supported: v3|v2|invisible). Get more info about reCAPTCHA version at https://developers.google.com/recaptcha/docs/versions 'v2'
curl_timeout int the maximum number of seconds to allow cURL functions to execute 10
skip_ip array | string a whitelist of IP addresses (array or CSV) that, if recognized, disable the reCAPTCHA validation (return always true) and if you embed JS code in blade (view) file NO validation call will be performed []
default_validation_route string the route called via javascript built-in validation script (v3 only) 'biscolab-recaptcha/validate'
default_token_parameter_name string the name of "token" GET parameter sent to default_validation_route to be validated (v3 only) 'token'
default_language string the default language code. It has no effect with v3. See https://developers.google.com/recaptcha/docs/language for further information null
default_form_id string the default form ID. Only for "invisible" reCAPTCHA 'biscolab-recaptcha-invisible-form'
explicit bool deferring the render can be achieved by specifying your onload callback function and adding parameters to the JavaScript resource. It has no effect with v3 and invisible (supported values: true|false) false
api_domain string customize API domain. Default value is 'www.google.com', but, if not accessible you ca set that value to 'www.recaptcha.net'. More info about Can I use reCAPTCHA globally? 'www.google.com'
empty_message bool set default error message to null false
error_message_key string set default error message translation key 'validation.recaptcha'

(array) tag_attributes

Key Type Description Default
tag_attributes.theme string the color theme of the widget. (supported values: "light"|"dark") 'light'
tag_attributes.size string the size of the widget. (supported values: "normal"|"compact") 'normal'
tag_attributes.tabindex int the tabindex of the widget and challenge 0
tag_attributes.callback string the name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback null
tag_attributes.expired-callback string the name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify null
tag_attributes.error-callback string the name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry null

DO NOT SET tag_attributes.callback, tag_attributes.expired-callback, tag_attributes.error-callback to biscolabOnloadCallback. biscolabOnloadCallback is the default JavaScript callback function called when explicit is set to true and widget onload event is fired.

Here you can find further details about tag_attributes.* https://developers.google.com/recaptcha/docs/display#render_param

Reload config cache file

!!! IMPORTANT !!! Every time you change some configuration run the following shell command:

$ php artisan config:cache

Have you updated?

If you are migrating from an older version check your config/recaptcha.php configuration file and compare it with https://github.com/biscolab/laravel-recaptcha/blob/master/config/recaptcha.php.

Make sure config/recaptcha.php is updated

Customize error message

Just for v2 and invisible users.

Before starting please add the validation message to resources/lang/[LANG]/validation.php file

return [
    ...
    'recaptcha' => 'Hey!!! :attribute is wrong!',
];

Embed in Blade

Insert htmlScriptTagJsApi() helper before closing </head> tag.

You can also use ReCaptcha::htmlScriptTagJsApi().

<!DOCTYPE html>
<html>
    <head>
        ...
        {!! htmlScriptTagJsApi($configuration) !!}
    </head>

htmlScriptTagJsApi

htmlScriptTagJsApi function accepts $configuration argument. $configuration has different keys depending on which ReCAPTCHA you are using:

ReCAPTCHA v2 Checkbox

htmlScriptTagJsApi($configuration)

$configuration argument can have following keys:

Form set-up

After you have to insert htmlFormSnippet() helper inside the form where you want to use the field g-recaptcha-response.

You can also use ReCaptcha::htmlFormSnippet() .

<form>
    @csrf

    ...
    {!! htmlFormSnippet() !!}
    <!-- OR -->
    {!! htmlFormSnippet($attributes) !!}
    <input type="submit">
</form>

DO NOT forget @csrf blade directive

htmlFormSnippet([, array $attributes = [] ])

htmlFormSnippet() function does not require attributes but you can override default config data- attributes:

{!! htmlFormSnippet([
    "theme" => "light",
    "size" => "normal",
    "tabindex" => "3",
    "callback" => "callbackFunction",
    "expired-callback" => "expiredCallbackFunction",
    "error-callback" => "errorCallbackFunction",
]) !!}

htmlFormSnippet methos allows are only folowing attribute names:

  • theme
  • size
  • tabindex
  • callback
  • expired-callback
  • error-callback

Any different attribute name will be rejected

Customization

In config/recaptcha.php you can customize reCAPTCHA widget setting tag_attributes array values. Take a look to tag_attributes section in Complete configuration

ReCAPTCHA v2 Invisible

htmlScriptTagJsApi($configuration)

$configuration argument can have following keys:

  • form_id set reCAPTCHA form ID. This will override default_form_id in config/recaptcha.php. This value will be returned by getFormId() function in order to set the form tag id property.

Form set-up

After you have to insert htmlFormButton($button_label, $properties) helper inside the form where you want to use reCAPTCHA.

This function creates submit button therefore you don't have to insert <input type="submit"> or similar.

You can also use ReCaptcha::htmlFormButton($button_label, $properties) .

$button_label is what you want to write on the submit button

<form id="{{ getFormId() }}">
  @csrf ... {!! htmlFormButton($button_label, $properties) !!}
</form>

DO NOT forget @csrf blade directive

getFormId()

getFormId function returns the default form ID value. This is the value of either default_form_id in config/recaptcha.php or $configuration['form_id'] previously set as arguments of htmlScriptTagJsApi helper.

$configuration['form_id'] overrides default settings.

htmlFormButton()

htmlFormButton function accepts 2 arguments:

  • $button_label: (string: optional) the button lable. For example: Subscribe!;
  • $properties: (array: optional) the HTML button properties. For example:
// $properties =
[
    'class' => 'btn btn-info',
    'data-foo' => 'bar'
]

If data-sitekey and data-callback properties are set, they will be overwritten

If class property is set the value g-recaptcha will be appended

Verify submitted data

Add recaptcha to your rules

$validator = Validator::make(request()->all(), [
    ...
    'g-recaptcha-response' => 'recaptcha',
    // OR since v4.0.0
    recaptchaFieldName() => recaptchaRuleName()
]);

// check if validator fails
if($validator->fails()) {
    ...
    $errors = $validator->errors();
}

Embed in Blade

Insert htmlScriptTagJsApi($config) helper before closing </head> tag.

<!DOCTYPE html>
<html>
    <head>
        ...
        {!! htmlScriptTagJsApi([
            'action' => 'homepage',
            'callback_then' => 'callbackThen',
            'callback_catch' => 'callbackCatch'
        ]) !!}

        <!-- OR! -->
        
        {!! htmlScriptTagJsApi([
            'action' => 'homepage',
            'custom_validation' => 'myCustomValidation'
        ]) !!}
    </head>

$config is required and is an associative array containing configuration parameters required for the JavaScript validation handling.

The keys are:

Key Required Description Default value
action no is the action parameter required by reCAPTCHA v3 API (further info) homepage
custom_validation no is the name of your custom callback javascript function who will override the built-in javascript validation system of this package empty string
callback_then no (overlooked if custom_validationis set) is the name of your custom callback javascript function called by the built-in javascript validation system of this package in case of response success empty string
callback_catch no (overlooked if custom_validationis set) is the name of your custom callback javascript function called by the built-in javascript validation system in this package in case of response fault empty string

Built-in javascript validation system

As callback of grecaptcha.execute an ajax call to config('recaptcha.default_validation_route') will be performed using fetch function. In case of successful response a Promise object will be received and passed as parameter to the callback_then function you have set. In not set, no actions will be performed.

Same will happen with callback_catch. callback_catch will be called in event of response errors and errors will pass as parameter et that function. If not set, no actions will be performed.

Please, go to Using Fetch for further information on fetch javascript function.

Warning!!! Check browser compatibility fetch function has compatibility issues with some browser like IE. Please create a custom validation function and set custom_validation with its name. That function has to accept as argument the tokenreceived from Google reCAPTCHA API.

Fetch browser compatibility

Validation Laravel route

Default validation route is config('recaptcha.default_validation_route', 'biscolab-recaptcha/validate').
Route and relative Controller are built-in in the package. The route if filtered and protected by Laravel web Middleware, that's why is important you embed csrf-token HTML meta tag and send X-Requested-Wit and X-CSRF-TOKEN headers.

You can also change the validation end-point changing default_validation_route value in recaptcha.php config file.

<head>
    ...
    <!-- IMPORTANT!!! remember CSRF token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>

Validation response object

The output will be a JSON containing following data:

  • Default output without errors
{
    "action":"homepage",
    "challenge_ts":"2019-01-29T00:42:08Z",
    "hostname":"www.yourdomain.ext",
    "score":0.9,
    "success":true
}
  • Output when calling IP is included in "skip_ip" config whitelist
{
    "skip_by_ip":true,
    "score":0.9,
    "success":true
}

If you embed code in your blade file using htmlScriptTagJsApiV3 helper no validation call will be performed!

More info at Configuration page

  • Output with an empty response from Google reCAPTCHA API
{
    "error":"cURL response empty",
    "score":0.1,
    "success":false
}

In the next paragraph you can learn how handle Validation promise object

"callback_then" and "callback_catch"

After built-in validation you should do something. How? Using callback_then and callback_catch functions.

What you have to do is just create functions and set parameters with their names.

  • callback_then must receive one argument of type Promise.

  • callback_catch must receive one argument of type string

The result should be something like that:

<head>
    ...
    <!-- IMPORTANT!!! remember CSRF token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    ...
    <script type="text/javascript">
        function callbackThen(response){
        	// read HTTP status
            console.log(response.status);
            
            // read Promise object
            response.json().then(function(data){
                console.log(data);
            });
        }
        function callbackCatch(error){
            console.error('Error:', error)
        }   
    </script>    
    ...
    {!! htmlScriptTagJsApiV3([
        'action' => 'homepage',
        'callback_then' => 'callbackThen',
        'callback_catch' => 'callbackCatch'
    ]) !!}    
</head>

"custom_validation" function

As just said you can handle validation with your own function. To do that you have to write your function and set custom_validation parameter with its name.

The result should be something like that:

<head>
    ...
    <!-- IMPORTANT!!! remember CSRF token --> 
    <meta name="csrf-token" content="{{ csrf_token() }}">
    ...
    <script type="text/javascript">
        function myCustomValidation(token) {
            // do something with token 
        }
    </script>    
    ...
    {!! htmlScriptTagJsApiV3([
        'action' => 'homepage',
        'custom_validation' => 'myCustomValidation'
    ]) !!}    
</head>

laravel-recaptcha's People

Contributors

aaronsaray avatar biscolab avatar dispercity avatar laravel-shift avatar matthiasgrube avatar paulredmond avatar rafaelyanagui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

laravel-recaptcha's Issues

Validation server error for some languages

When I try to validate recaptcha with language sk pt hu then validation failed.

Head example:
{!! htmlScriptTagJsApi(['lang' => 'sk']) !!}

Response from server:
{"message":"Server Error","country_status":"active"}

For other languages validation works.

Is there any fix for that?

config/recaptcha.php@47

There is a semicolon there, where a comma should be. It is causing an error when doing the vendor:publish for your config file.

Feature Request: Badge Configuration

I was just wondering if it is possible to configure where the badge shows up on the page. We are using the Invisible captcha, and it shows the small Google badge in the bottom right corner. We also have another JS tool that displays a badge in the same corner.

Looks like it is possible to adjust the badge location in the Google docs, but I'm not sure if it is possible to use these settings in the Laravel configuration.
See data-badge on this page...
https://developers.google.com/recaptcha/docs/invisible

Thanks in advance!

Uncaught (in promise) Timeout

I am using Laravel v5.6 and Laravel Recaptcha version 3.6.

I have a customer login page and an admin login page. I added the recaptcha to both and it works on the customer login page but when I click the checkbox on the admin login page I keep getting this "Uncaught (in promise) Timeout" error where the widget spins and then it goes back to the default unchecked state and therefore I am unable to log in.

null token recaptcha V3

as described in the documentation I installed the package and add the keys to the config then inserted the helper into the view.
I'm using recaptcha on the login form so the form is submitted to /login, I don't know if I have to add anything to the controller but that is not mentioned in the documentation so I assume it's handled by the package.

the recaptcha logo appear on the bottom right of the page and i can see requests going to https://www.google.com/recaptcha/api2/

Screenshots of the request and response

image
image
image

Environment:

  • Windows 10
  • PHP version 7.4.15
  • Laravel version 8.27.0
  • Package version 5.0.1

Additional context
the code inserted in the view head

{!! htmlScriptTagJsApi([
        'action' => 'homepage',
    ]) !!}

config file:

<?php
/**
 * Copyright (c) 2017 - present
 * LaravelGoogleRecaptcha - recaptcha.php
 * author: Roberto Belotti - [email protected]
 * web : robertobelotti.com, github.com/biscolab
 * Initial version created on: 12/9/2018
 * MIT license: https://github.com/biscolab/laravel-recaptcha/blob/master/LICENSE
 */

/**
 * To configure correctly please visit https://developers.google.com/recaptcha/docs/start
 */
return [

    /**
     *
     * The site key
     * get site key @ www.google.com/recaptcha/admin
     *
     */
    'api_site_key'                 => env('RECAPTCHA_SITE_KEY', ''),

    /**
     *
     * The secret key
     * get secret key @ www.google.com/recaptcha/admin
     *
     */
    'api_secret_key'               => env('RECAPTCHA_SECRET_KEY', ''),

    /**
     *
     * ReCATCHA version
     * Supported: "v2", "invisible", "v3",
     *
     * get more info @ https://developers.google.com/recaptcha/docs/versions
     *
     */
    'version'                      => 'v3',

    /**
     *
     * The curl timout in seconds to validate a recaptcha token
     * @since v3.5.0
     *
     */
    'curl_timeout'                 => 10,

    /**
     *
     * IP addresses for which validation will be skipped
     *
     */
    'skip_ip'                      => [],

    /**
     *
     * Default route called to check the Google reCAPTCHA token
     * @since v3.2.0
     *
     */
    'default_validation_route'     => 'biscolab-recaptcha/validate',

    /**
     *
     * The name of the parameter used to send Google reCAPTCHA token to verify route
     * @since v3.2.0
     *
     */
    'default_token_parameter_name' => 'token',

    /**
     *
     * The default Google reCAPTCHA language code
     * It has no effect with v3
     * @see   https://developers.google.com/recaptcha/docs/language
     * @since v3.6.0
     *
     */
    'default_language'             => null,

    /**
     *
     * The default form ID. Only for "invisible" reCAPTCHA
     * @since v4.0.0
     *
     */
    'default_form_id'              => 'biscolab-recaptcha-invisible-form',

    /**
     *
     * Deferring the render can be achieved by specifying your onload callback function and adding parameters to the JavaScript resource.
     * It has no effect with v3 and invisible
     * @see   https://developers.google.com/recaptcha/docs/display#explicit_render
     * @since v4.0.0
     * Supported true, false
     *
     */
    'explicit'                     => false,

    /**
     *
     * Set API domain. You can use "www.recaptcha.net" in case "www.google.com" is not accessible.
     * (no check will be made on the entered value)
     * @see   https://developers.google.com/recaptcha/docs/faq#can-i-use-recaptcha-globally
     * @since v4.3.0
     * Default 'www.google.com' (ReCaptchaBuilder::DEFAULT_RECAPTCHA_API_DOMAIN)
     *
     */
    'api_domain'                   => 'www.google.com',

    /**
     *
     * g-recaptcha tag attributes and grecaptcha.render parameters (v2 only)
     * @see   https://developers.google.com/recaptcha/docs/display#render_param
     * @since v4.0.0
     */
    'tag_attributes'               => [

        /**
         * The color theme of the widget.
         * Supported "light", "dark"
         */
        'theme'            => 'light',

        /**
         * The size of the widget.
         * Supported "normal", "compact"
         */
        'size'             => 'normal',

        /**
         * The tabindex of the widget and challenge.
         * If other elements in your page use tabindex, it should be set to make user navigation easier.
         */
        'tabindex'         => 0,

        /**
         * The name of your callback function, executed when the user submits a successful response.
         * The g-recaptcha-response token is passed to your callback.
         * DO NOT SET "biscolabOnloadCallback"
         */
        'callback'         => null,

        /**
         * The name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.
         * DO NOT SET "biscolabOnloadCallback"
         */
        'expired-callback' => null,

        /**
         * The name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored.
         * If you specify a function here, you are responsible for informing the user that they should retry.
         * DO NOT SET "biscolabOnloadCallback"
         */
        'error-callback'   => null,
    ]
];

Laravel Nova is always in English when using this package

Describe the bug
I have an installation of Laravel Nova in the same app that I'm using this package and I noticed that Laravel Nova started to be in English after installing this package. I have the translations for Laravel Nova to Brazilian Portuguese.

To Reproduce
Steps to reproduce the behavior:

  1. Install Laravel Nova (hard to reproduce because needs a license)
  2. Change the app to a different language
  3. Create some translations for this new language
  4. Install this package
  5. Go to Nova installation and you will see that Laravel Nova is in English

Expected behavior
See Laravel Nova in configured language.

Screenshots
When this package is installed:
image

If I comment this line in ReCaptchaServiceProvider:
image

Then I have it in the correct language:
image

Environment:

  • OS and server: Docker image php8.0-apache
  • PHP version 8.0
  • Laravel version 8.68.1
  • Package version 5.0.1

Can't undersand how you example of recaptcha v3 will work

I have implemented the example that you have in the documentation page of V3, and I understand that using the callback_then and callback_catch you will make a request for a specific library endpoint that returns the score of the user, but even if the user have a really bad score how this will prevent the form to be submitted.

I think you should create a real example of a simple contact form protected with the recapctha v2, invisible and V3.

In the V2 example you append the g-recaptcha-response on the form that will be submitted and this make sense, but in V3 example I think you can always submit.

Can you explaining me if I'm seeing it wrong?
How this code will protect the form (in v3 example) if for example it is submitted for a bot that don't even run javascript?

validateV3() must be of type array, boolean returned

Describe the bug
This error does not happen all the time. It has been less than 1% in all page load. Sometime, when a recaptcha v3 enabled page is loaded, there is an error reported in sentry.io and the error is Return value of Biscolab\ReCaptcha\Controllers\ReCaptchaController::validateV3() must be of the type array, boolean returned.

The error stack is below:

Symfony\Component\Debug\Exception\FatalThrowableError: Return value of Biscolab\ReCaptcha\Controllers\ReCaptchaController::validateV3() must be of the type array, boolean returned
#54 vendor/biscolab/laravel-recaptcha/src/Controllers/ReCaptchaController.php(27): validateV3
#53 vendor/biscolab/laravel-recaptcha/src/Controllers/ReCaptchaController.php(0): call_user_func_array

To Reproduce
Steps to reproduce the behavior:

  1. Follow exact instruction to install recaptcha V3
  2. open the page with recaptcha V3 enabled
  3. See the error reported

Expected behavior
Error should not happen

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:
Homestead
Laravel 5.7.20

Additional context
n/a

Call to undefined method Biscolab\ReCaptcha\ReCaptchaBuilderV2::htmlFormButton()

Describe the bug
Hi, thanks for the package, unfortunately I get the following error:
Call to undefined method Biscolab\ReCaptcha\ReCaptchaBuilderV2::htmlFormButton()

When I remove {!! htmlFormButton() !!} the captcha appears correctly (without the submit button obviously).

Configs are set too, both in .env and recaptcha.php file.

I also tried {!! ReCaptcha::htmlFormButton() !!} and still the same, I'm using v2 but even if I change it to invisible in config, then I get this error instead: Call to undefined method Biscolab\ReCaptcha\ReCaptchaBuilderInvisible::htmlFormSnippet()

Environment:

  • OS and server: Mac
  • PHP version 8.0.8
  • Laravel version 8.66.0
  • Package version 5.0.1

Publish package command doesn't publish anything

Describe the bug
Using this command: php artisan vendor:publish --provider="Biscolab\ReCaptcha\ReCaptchaServiceProvider" does not publish any files.

To Reproduce
Follow the install instructions and execute php artisan vendor:publish --provider="Biscolab\ReCaptcha\ReCaptchaServiceProvider". Returned message is: Publishing complete. but nothing is published in config or anywhere else.

Expected behavior
At least the config file to be published.

Environment:

  • OS: Windows 10
  • PHP version 7.3.0
  • Laravel ^5.6

Additional context
Running locally under XAMPP v 3.2.2 using PHP 7.3.

Adding reCaptch to Login

Hello, this is not a bug.

I have implemented this package on a study project. I'm able to get keys from google, but how do I make the laravel login to validate de reCaptcha without messing with files in vendor folder?

I'm posting this because if I don't configure the proper domain, the login is successfull anyway.

Regards

Set language for ReCAPTCHA v2 Checkbox

As you wrote $configuration argument can have following keys:
{!! htmlScriptTagJsApi(['lang' => 'en' !!} , but it does not work. As I checked you need to pass {!! htmlScriptTagJsApi(['resources' => 'en' !!} instead. Please check if I am right.

Support for Laravel 8

Unable to install the same package on laravel 8, please provide support for the same.

image

Javascript callback function for v2

I used this code

<form action="" method="post">
        @csrf
        {!! htmlFormSnippet() !!}
        <input type="submit" value="Click here to continue" id="submit_form" disabled>
    </form>

and

htmlScriptTagJsApi()

I want to add javascript call back function to valid form and enable that button.
But I could not find any solution
I think this is new sugesstion. Thanks

getFormId() not work in last version

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

  • OS and server: [e.g. Ubuntu 16.04 / Nginx] (If you are using a VM on Windows DON'T "say" Windows)
  • PHP version [7.1.x]
  • Laravel version [e.g. 5.5]
  • Package version [e.g. 3.4.1]

Additional context
Add any other context about the problem here, like code snippets.

deferred rendering

Hi,

I'm trying to defer rendering because recaptcha isn't visible at first on my page,
I did set "explicit" to true in the config as mentioned in the doc,
but I can't find where to add the name for my onload callback,
could you please provide an example for this (and add it in the doc) ?

Best regards,

Olivier

Lazy load script (poor lighthouse score)

image

It would be nice to lazy load recaptcha as I don't even have the protected form until much lower on the page. Why download the script in the header when it could be loaded in the footer?

CSP nonce

Could the inline script be added with a nonce? Maybe optional integration with spatie/laravel-csp or some means for me to insert a nonce to the inline script. The markup is pretty hard-coded. If the view were moved out of inline blade markup into an actual blade.view, then I'd have some more flexibility.

Currently it is not possible to update while using php 8

Problem 2
- Root composer.json requires biscolab/laravel-recaptcha ^4.4 -> satisfiable by biscolab/laravel-recaptcha[4.4.0].
- biscolab/laravel-recaptcha 4.4.0 requires php ^7.1 -> your php version (8.0.2) does not satisfy that requirement.

it work with contactus page but not work in commnets !!

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

  • OS and server: [e.g. Ubuntu 16.04 / Nginx] (If you are using a VM on Windows DON'T "say" Windows)
  • PHP version [7.1.x]
  • Laravel version [e.g. 5.5]
  • Package version [e.g. 3.4.1]

Additional context
Add any other context about the problem here, like code snippets.

Route Caching Error Due to Closure

A recent update added a closure route, which makes my route:cache fail during php artisan route:cache:

image.

I am thankful that the package allows me to configure my own route path so I can define my own controller, however, I think it would be advisable to convert this to a controller.

Setup Airbrake for your PHP application

Installation

composer require airbrake/phpbrake

Example Usage

This usage example details how to create a notifier instance, set a global notifier instance, register the error handler, and includes a snippet of some code that would report an exception to Airbrake (You can find your project ID and API KEY with your project's settings):

// Create new Notifier instance.
$notifier = new Airbrake\Notifier(array(
    'projectId' => <Your project ID>,
    'projectKey' => '<Your project API KEY>',
));

// Set global notifier instance.
Airbrake\Instance::set($notifier);

// Register error and exception handlers.
$handler = new Airbrake\ErrorHandler($notifier);
$handler->register();

// Somewhere in the app...
try {
    throw new Exception('hello from phpbrake');
} catch(Exception $e) {
    Airbrake\Instance::notify($e);
}

Going further

Check out our official GitHub repo for info on additional features like:

Error with Ajax

Every time a request is sent using ajax, and there is an error, just let it do it once, you have to reload the page to be able to use it again, because it returns the catpcha error. It should have a function to refresh the captcha.
I made a login where it returns if the person has active, double authentication, so if it returns yes, it should ask for the code on the same page, but it doesn't stop because if it sends the code at once, it should refresh.

Environment:

  • OS and server: Ubuntu/Windows
  • PHP version [7.3.11]
  • Laravel version [7.29.3]

The problem of adding to the page later

Greetings,
I use Recaptcha v2 or Recaptcha v3 in my project, depending on the choice of admin.

I have no problem running it on any page.

However, I am having problems when my login screen is added to the page later. My scenario is as follows:

If the user is not logged in, I send an ajax request and get the login view in response to the ajax request. I show the login view to the user in Bootstrap-modal. During the display process (in Login View) for V2
{!! ReCaptcha::htmlScriptTagJsApi() !!} and {!! ReCaptcha::htmlFormSnippet () !!}
or for V3

{!! htmlScriptTagJsApi ([
         'action' => 'submit',
         'callback_then' => 'callbackThen',
         'callback_catch' => 'callbackCatch'
         ]) !!}

If I use it, V2 Recaptcha comes, but when the form is submitted, the default_validation_route is not requested.

I have the same problem in V3 as well. There is no request to default_validation_route.

let wID=grecaptcha.render('recaptcha-element');
grecaptcha.reset(wID);

not working with invisble

hi , everttime i try to submit the form i get Hey!!! Recaptcha is wrong!
i am using laravel 5.6
i also added this:

<script src='https://www.google.com/recaptcha/api.js' async defer></script><script>

--
  | function biscolabLaravelReCaptcha(token) {
  | document.getElementById("login-form").submit();
  | }
  | </script>
{!! htmlFormButton() !!}

Data-Callback overwriting

Describe the bug
When I use invisible captcha, it's not possible to overwrite data-callback

{!! htmlFormButton(trans('contact.send_button'), ['class' => 'btn submit', 'data-badge' => 'bottomleft', 'data-callback' => 'myCustomFunction']) !!}

Screen Shot 2021-01-14 at 11 02 34

Expected behavior
data-callback attribute must be overwritten to myCustomFunction

Environment:

  • PHP version 7.4.11
  • Laravel version 8.19.0
  • Package version 5.0

FEATURE REQUEST: Allow overriding captcha type in htmlScriptTagJsApi tag

Currently we have to set the size for v2 checkbox to 'normal' or 'compact' in the config, and it applies everywhere. However, for my use case I would like to be able to override this on certain pages. You already allow passing configuration in the JS tag, like this:

{!! htmlScriptTagJsApi(['lang' => 'de']) !!}

Can you make it so

{!! htmlFormSnippet() !!}

can also accept configuration, at least for size?

htmlScriptTagJsApi() display two curly brackets

Describe the bug
When I'm using ReCaptcha::htmlScriptTagJsApi() before my It display {}at the top of my page. But the package work well.

To Reproduce
Steps to reproduce the behavior:

  1. Add {{!! ReCaptcha::htmlScriptTagJsApi() !!}} before your .

Expected behavior
To not have this {}at the top of page.

Screenshots
Screenshot

Screenshot 2

Environment:

  • MacOS 12.1
  • PHP version [8.0.11]
  • Laravel version [8]
  • Package version [5.1.0]

Feature testing with recaptcha

Hello!

I couldn't find anything in your documentation about how to test recaptcha with phpunit. I have a complete set of feature tests for my authentication flow, and recently added recaptcha support with your package. And meanwhile I can disable recaptcha validation for testing via the CreatesApplication class, I'm not sure that is good solution and looking after a real way to test this.
Did I miss any guide or docs on this?
Would you mind adding it? Thanks!

Doesnt work sub domain

Hello everyone my domain is . dev.stabit.com
I am install package and configration is still work 127.0.0.1 and not work server . İf empty chapca not error message ı dont understand . PHP version 7.4 . Server laravel . versiyon 7

Site login
stabit
Stabit!!20

my config file

https://paste.laravel.io/b5541309-de64-439e-9b4e-228a6f7b3d6c

my html file

https://paste.laravel.io/94b9b17c-c716-4c0b-88c2-db6b5896d45c

and my recapcha config

http://prntscr.com/106q9lx

please help me.

Call to undefined function htmlScriptTagJsApiV3()

Error Exception Call to undefined function htmlScriptTagJsApiV3()

Steps to reproduce the behavior:

  1. do exact documentation of installation
  2. do exact as documentation to configure V3
  3. reload the page
  • OS: Windows 10
  • PHP version v7.1.29
  • laravel 5.8

Disable button after click

Describe Missing Feature
Not possible to disable the button after it is clicked.

To Reproduce
I want to disable the button after it is clicked, since some users click many times the button, currentlly the button remains enabled after the click.

Expected behavior
After click the button is disabled.

Environment:
Not browser dependent.

Possible Solution
On htmlScriptTagJsApi, add an additional propertie like :
'disable' => true, so the button is disabled after click or false if the button should remain enabled.

Laravel 7.x Support

Unable to upgrade to Laravel 7.x

Problem 1
- Conclusion: remove biscolab/laravel-recaptcha 4.0.1
- Conclusion: don't install biscolab/laravel-recaptcha 4.0.1
- Conclusion: don't install laravel/framework v7.0.2

Environment:

  • OS and server: Mac OS Catalina
  • PHP version [7.3.14]
  • Laravel version [e.g. 6.18.0]
  • Package version [e.g. 3.4.1]

[Laravel 8] Implementing ReCaptcha inside JetstreamServiceProvider

Hi mighty all,

Trying to inject the usual ReCaptcha (your packet) functionality into JetstreamServiceProvider.

GIST

If the captcha is empty — everything is OK and I get an error, but if captcha is passed/checked I also get an error saying "You have to pass ReCaptcha check". Deep night now, please point me in the right direction.

P.S. All the same works for Jetstream while creating a new user (updated validator inside Fortify/CreateNewUser.php).

Ignoring HTML5 form validation

if the input field is empty, the submit event handler doesn't run. It will be triggered only if the HTML5 validation (the required attribute, in this case) has passed.

I'd expect a captcha to run after the HTML5 validation too; why do I have to annoy the user compiling a captcha if later on I'd warn him there are missing fields ? First I should force the user to do everything in the right way, then ensure it's a human and not a bot, IMHO.

Appearently, reCaptcha does something on the form it attaches on, removing the HTML5 validation feature.

The form will be submitted with the empty field, without notifying the user about its obligatoriness.

Any clue on why it acts like this ? Is there a way I can instruct reCaptcha to let HTML5 form validation run before taking control ?

Laravel 8 support

Hi, thanks for this project. Can you add Laravel 8 compatibility?

Add Localization to Captcha

Hi,
is it possible to add localization to googles recaptcha ?

My steps in ReCaptchaBuilder class were:

Add Facade:
use Illuminate\Support\Facades\App;

Add propery
protected $locale; property.

Updated constructor
public function __construct(...) { ... $this->locale = App::getLocale(); }

and then make some changes in this method (showing changes just in version v2)

htmlScriptTagJsApi() {
     <script src=\"https://www.google.com/recaptcha/api.js?hl={$this->locale}\" async defer></script>
}

Valid code languages can be found here:
https://developers.google.com/recaptcha/docs/language

best regards
Greg

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.