Coder Social home page Coder Social logo

hcaptcha-bundle's Introduction

HCaptcha bundle for Symfony 3+ Symfony

This bundle brings into your Symfony website a new Form type, namely HCaptchaType, that is used to display and validate a CAPTCHA served by https://www.hcaptcha.com.

This bundle is tested for Symfony major versions 3, 4, 5 and 6. Major version 2 works for Symfony 3 and 4, with PHP 7.2+ ; major version 3 for Symfony 5 and 6 with PHP 7.4 or 8.x ; major version 4 for Symfony 6.4 and 7 with PHP 8.2+. The test dependencies requirements can be more stringent.

Installation

Applications that use Symfony Flex

Open a command console, enter your project directory and execute:

$ composer require meteo-concept/hcaptcha-bundle

In order to avoid making you install another HTTP client if you already have a compatible one, this bundle depends on virtual packages, namely PSR-18 psr/http-client-interface and PSR-17 psr/http-factory-interface. If you don't have any real package already installed in your application providing an implementation for these, composer will complain that the bundle is not installable. In this case, you have to provide a real implementation at the same time as the bundle.

For instance, starting from Symfony 4:

$ composer require meteo-concept/hcaptcha-bundle symfony/http-client nyholm/psr7

For Symfony 3:

$ composer require meteo-concept/hcaptcha-bundle guzzlehttp/guzzle nyholm/psr7

Applications that don't use Symfony Flex

Step 1: Download the Bundle

Install the bundle with one of the commands above. You now have to enable it and configure it without the recipe.

Step 2: Enable the Bundle

Then, enable the bundle by adding it to the list of registered bundles in the config/bundles.php file of your project:

// config/bundles.php

return [
    // ...
    MeteoConcept\HCaptchaBundle\MeteoConceptHCaptchaBundle::class => ['all' => true],
];

Configuration

This captcha is provided with a Symfony flex contrib recipe so it should come with a configuration if you have those enabled. Otherwise, you can copy the configuration from the contrib repository: https://github.com/symfony/recipes-contrib/tree/master/meteo-concept/hcaptcha-bundle.

Configure the bundle, for instance in config/packages/meteo_concept_hcaptcha.yml:

parameters:
    hcaptcha_site_key: '%env(resolve:HCAPTCHA_SITE_KEY)%'
    hcaptcha_secret: '%env(resolve:HCAPTCHA_SECRET)%'

meteo_concept_h_captcha:
  hcaptcha:
    site_key: '%hcaptcha_site_key%'
    secret: '%hcaptcha_secret%'
  validation: 'strict' # this is the default

with the corresponding change in .env:

HCAPTCHA_SITE_KEY="10000000-ffff-ffff-ffff-000000000001"
HCAPTCHA_SECRET="0x0000000000000000000000000000000000000000"

The site key and secret are the values hCaptcha gives you at https://dashboard.hcaptcha.com. The global configuration makes all captchas use the same site key by default but it's possible to change it in the definition of each form.

The values shown here are dummy values usable for integration testing (https://docs.hcaptcha.com/#integrationtest). Put the real values in .env.local (at least, the secret, the site key is public).

The validation can be set to 'strict' or 'lax'. If it's 'lax', then the CAPTCHA will be considered valid even if the hCaptcha endpoint times out or return a HTTP 500 error for instance (so as to not frustrate the users too much). If it's strict (the default), then the CAPTCHA will not be considered valid unless the endpoint returns a "success: true" answer.

Configure Twig to load the specific template for the hCaptcha widget (or provide your own).

twig:
    ...
    form_themes:
        - '@MeteoConceptHCaptcha/hcaptcha_form.html.twig'
        - ...

If you use Guzzle or another HTTP library, you may also need a configuration for that bundle and its services. For instance, for Guzzle, you probably need the following in services.yaml:

services:
    Psr\Http\Client\ClientInterface:
        class: GuzzleHttp\Client
    Psr\Http\Message\RequestFactoryInterface:
        class: Nyholm\Psr7\Factory\Psr17Factory
    Psr\Http\Message\StreamFactoryInterface:
        class: Nyholm\Psr7\Factory\Psr17Factory

Usage

Use the captcha in your forms:

<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

use MeteoConcept\HCaptchaBundle\Form\HCaptchaType;

class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, [
                'label' => 'Name',
            ])
            ->add('email', TextType::class, [
                'label' => 'Email',
            ])
            ->add('message', TextareaType::class, [
                'label' => 'How can we help you ?',
            ])
            ->add('captcha', HCaptchaType::class, [
                'label' => 'Anti-bot test',
                // optionally: use a different site key than the default one:
                'hcaptcha_site_key' => '10000000-ffff-ffff-ffff-000000000001',
            ])
        ;
    }
}

By default, the HCaptchaFormType class validates the field against constraints NotBlank and IsValidCaptcha (a new constraint installed with this bundle whose validator makes the CAPTCHA check by calling the hCaptcha API). You can override this set of constraints by passing the constraints option to the form builder. Also, HCaptchaFormType fields are passed 'mapped' => false by default since it doesn't make much sense to persist CAPTCHA values.

Updates and breaking changes

  • In major version 2, support for PHP7.1 has been dropped and support for PHP8.0 added.
  • In major version 3:
    • support for PHP <7.4 has been dropped
    • support for Symfony <5.3 has been dropped
    • support for Symfony 6.0 has been added
  • In major version 4:
    • support for PHP <8.2 has been dropped
    • support for Symfony <6.4 has been dropped
    • support for Symfony 7.0 has been added

hcaptcha-bundle's People

Contributors

esteveli avatar lgeorget avatar liarco avatar

Stargazers

 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

hcaptcha-bundle's Issues

Symfony 6.0 support

Hello,

Is there a symfony 6.x support planned?
Right now composer.json version constraints prevent installation but looks like code is compatible (I can provide help for tests if needed :) )

error: Cannot instantiate interface Psr\Http\Client\ClientInterface

Hello, I am on symfony 3.4, with php 7.4.
I followed the install guide but when I valided the form with hCaptcha confirmed, I have this error and I don't know how to do to debug this.
Any idea?

request.CRITICAL: Uncaught PHP Exception Symfony\Component\Debug\Exception\FatalThrowableError: "Cannot instantiate interface Psr\Http\Client\ClientInterface" at /home/www/site/var/cache/prod/ContainerQuncj5h/getMeteoConceptHCaptcha_CaptchaVerifierService.php line 8 {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Cannot instantiate interface Psr\\Http\\Client\\ClientInterface at /home/www/site/var/cache/prod/ContainerQuncj5h/getMeteoConceptHCaptcha_CaptchaVerifierService.php:8)"} []

here my composer.json:
image

Let me know if you need more informations! :)

Unable to install

I am using latest Symfony 6.x with Flex.

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires meteo-concept/hcaptcha-bundle ^3.3 -> satisfiable by meteo-concept/hcaptcha-bundle[v3.3.0].
    - meteo-concept/hcaptcha-bundle v3.3.0 requires psr/http-factory-implementation ^1.0 -> could not be found in any version, but the following packages provide it:
      - guzzlehttp/psr7 PSR-7 message implementation that also provides common utility methods
      - nyholm/psr7 A fast PHP7 implementation of PSR-7
      - http-interop/http-factory-guzzle An HTTP Factory using Guzzle PSR7
      - laminas/laminas-diactoros PSR HTTP Message implementations
      - zendframework/zend-diactoros PSR HTTP Message implementations
      - slim/psr7 Strict PSR-7 implementation
      - typo3/cms-core TYPO3 CMS Core
      - tuupola/http-factory Lightweight autodiscovering PSR-17 HTTP factories
      - httpsoft/http-message Strict and fast implementation of PSR-7 and PSR-17
      - typo3/cms TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj an
      - php-extended/php-http-message-factory-psr17 An implementation of the psr-17 based on the php-http-message-psr7 library
      - windwalker/uri Windwalker Uri package
      - mileschou/psr The support library for PSR
      - oro/platform Business Application Platform (BAP)
      - windwalker/http Windwalker Http package
      - sunrise/http-factory HTTP factory for PHP 7.1+ based on PSR-17
      - http-interop/http-factory-slim An HTTP Factory using Slim HTTP
      - bittyphp/http PSR-7 and PSR-17 HTTP implementation.
      - windwalker/framework The next generation PHP framework.
      - yiisoft/psr-dummy-provider PSR Dummy Provider
      ... and 45 more.
      Consider requiring one of these to satisfy the psr/http-factory-implementation requirement.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.
 - It's a private package and you forgot to add a custom repository to find it

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require meteo-concept/hcaptcha-bundle:*" to figure out if any version is installable, or "composer require meteo-concept/hcaptcha-bundle:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Do you have any idea why is this happening?

Symfony 3.2 issue

Hi!

I got an error in my try to install the package to Symfony 3.2:

PHP message: PHP Fatal error:  Uncaught InvalidArgumentException: [ERROR 1871] Element '{http://symfony.com/schema/dic/services}defaults': This element is not expected. Expected is ( {http://symfony.com/schema/dic/services}service ). (in /var/www/website/web/ - line 8, column 0) in /var/www/website/vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php:96
Stack trace:
#0 /var/www/website/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php(263): Symfony\Component\Config\Util\XmlUtils::loadFile('/var/www/websit...', Array)
#1 /var/www/website/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php(41): Symfony\Component\DependencyInjection\Loader\XmlFileLoader->parseFileToDOM('/var/www/websit...')
#2 /var/www/website/vendor/meteo-concept/hcaptcha-bundle/DependencyInjection/MeteoConceptHCaptchaExtension.php(18): Symfony\Component\DependencyInjection\Loader\XmlFileLoader->load('services.xml')
#3 /var/www/website/vendor/symf" while reading response header from upstream, client: 172.19.0.1, server: website, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.2-fpm.sock:", host: "127.0.0.1:8080"

Could you please help me to figure it out? Thank you in advance!

PHP 8 compatibility

Sorry if this is not the place, but I've updated my website to PHP 8 and got everything over to Symfony 5.2 including all packages, except for this one. For now I've resorted to reCaptcha, but I really don't want to use Google junk, and it's working poorly.

Anyway, would it be much trouble to update the package to support PHP 8? Would be great!

meteo-concept/hcaptcha-bundle conflicts with Symfony 5.2.*

It seems that the bundle can't be installed with symfony/http-client of version >=5.2.

$ composer require meteo-concept/hcaptcha-bundle symfony/http-client nyholm/psr7
Using version ^0.1.0@alpha for meteo-concept/hcaptcha-bundle
Using version ^1.4 for nyholm/psr7
./composer.json has been updated
Running composer update meteo-concept/hcaptcha-bundle symfony/http-client nyholm/psr7
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires meteo-concept/hcaptcha-bundle ^0.1.0@alpha -> satisfiable by meteo-concept/hcaptcha-bundle[v0.1.0-alpha].
    - meteo-concept/hcaptcha-bundle v0.1.0-alpha requires symfony/http-client >=4.3 <5.2 -> found symfony/http-client[v4.3.0-BETA1, ..., 4.4.x-dev, v5.0.0-BETA1, ..., 5.1.x-dev] but it conflicts with your root composer.json require
(5.2.*).


Installation failed, reverting ./composer.json and ./composer.lock to their original content.

HCaptchaBundle unhandled deprecation ErrorException warning

The newest version of HCaptchaBundle (v3.4.0) passes NULL values to urlencode() in \MeteoConcept\HCaptchaBundle\Service\HCaptchaVerifier::verify. Passing NULL values to urlencode() is deprecated and results in an unhandled ErrorException warning.

Support for custom Authenticator?

Works perfectly, use it for my signup form. But I can't use it in my login form, as it uses a custom Symfony authenticator. There aren't any docs outside of the readme, which doesn't help.

If there isn't any support, is it possible to check and verify the captcha myself?

Thank you!

Server Error when captcha empty

Hello,
I am using this bundle to have a captcha in my contact form, and sometimes I receive a server error :

{
    "class": "TypeError",
    "message": "Argument 1 passed to MeteoConcept\\HCaptchaBundle\\Form\\HCaptchaResponse::__construct() must be of the type string, null given, called in /home/kreyolgyhm/www/vendor/meteo-concept/hcaptcha-bundle/Form/DataTransformer/HCaptchaValueFetcher.php on line 58",
    "code": 0,
    "file": "/home/kreyolgyhm/www/vendor/meteo-concept/hcaptcha-bundle/Form/HCaptchaResponse.php:33",
    "trace": [
        "/home/kreyolgyhm/www/vendor/meteo-concept/hcaptcha-bundle/Form/DataTransformer/HCaptchaValueFetcher.php:58",
        "/home/kreyolgyhm/www/vendor/symfony/form/Form.php:1085",
        "/home/kreyolgyhm/www/vendor/symfony/form/Form.php:646",
        "/home/kreyolgyhm/www/vendor/symfony/form/Form.php:576",
        "/home/kreyolgyhm/www/vendor/symfony/form/Extension/HttpFoundation/HttpFoundationRequestHandler.php:109",
        "/home/kreyolgyhm/www/vendor/symfony/form/Form.php:490",
        "/home/kreyolgyhm/www/src/Controller/HelpController.php:27",
        "/home/kreyolgyhm/www/vendor/symfony/http-kernel/HttpKernel.php:157",
        "/home/kreyolgyhm/www/vendor/symfony/http-kernel/HttpKernel.php:79",
        "/home/kreyolgyhm/www/vendor/symfony/http-kernel/Kernel.php:196",
        "/home/kreyolgyhm/www/public/index.php:28"
    ]
}

It looks like it is caused by the captcha result being absent from the request. I don't know how it happens with my clients but when I delete the captcha widget from the webpage, I receive this error too. Is there anything to do to fix it?

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.