1 Commits

Author SHA1 Message Date
Jorit Tijsen
8b8c9b60d9 Add FriendlyCaptcha vendor dir 2026-02-27 09:30:52 +01:00
15 changed files with 815 additions and 2 deletions

View File

@@ -1,2 +0,0 @@
public/img
storage

View File

@@ -0,0 +1,56 @@
name: run-tests
on:
push:
branches: [master]
pull_request:
branches: [master]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [ubuntu-latest, windows-latest]
php: [7.4, 8.0, 8.1]
laravel: [8.*, 9.*, 10.*]
stability: [prefer-stable]
include:
- laravel: 10.*
testbench: 8.*
- laravel: 9.*
testbench: 7.*
- laravel: 8.*
testbench: 6.*
exclude:
- laravel: 10.*
php: 8.0
- laravel: 10.*
php: 7.4
- laravel: 9.*
php: 7.4
name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo
coverage: none
- name: Setup problem matchers
run: |
echo "::add-matcher::${{ runner.tool_cache }}/php.json"
echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Install dependencies
run: |
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update
composer update --${{ matrix.stability }} --prefer-dist --no-interaction
- name: Execute tests
run: vendor/bin/phpunit

View File

@@ -0,0 +1,4 @@
preset: laravel
disabled:
- single_class_element_per_statement

View File

@@ -0,0 +1,7 @@
# Changelog
All notable changes to `ossycodes/friendlycaptcha` will be documented in this file
## 1.0.0 - 2021-10-21
- initial release

View File

@@ -0,0 +1,55 @@
# Contributing
Contributions are **welcome** and will be fully **credited**.
Please read and understand the contribution guide before creating an issue or pull request.
## Etiquette
This project is open source, and as such, the maintainers give their free time to build and maintain the source code
held within. They make the code freely available in the hope that it will be of use to other developers. It would be
extremely unfair for them to suffer abuse or anger for their hard work.
Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
world that developers are civilized and selfless people.
It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
## Viability
When requesting or submitting new features, first consider whether it might be useful to others. Open
source projects are used by many developers, who may have entirely different needs to your own. Think about
whether or not your feature is likely to be used by other users of the project.
## Procedure
Before filing an issue:
- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
- Check to make sure your feature suggestion isn't already present within the project.
- Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
- Check the pull requests tab to ensure that the feature isn't already in progress.
Before submitting a pull request:
- Check the codebase to ensure that your feature doesn't already exist.
- Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
## Requirements
If the project maintainer has any additional requirements, you will find them listed here.
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
**Happy coding**!

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) ossycodes <osaigbovoemmanuel1@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,154 @@
# A simple package to help integrate FriendlyCaptcha.
[![Latest Version on Packagist](https://img.shields.io/packagist/v/ossycodes/friendlycaptcha.svg?style=flat-square)](https://packagist.org/packages/ossycodes/friendlycaptcha)
[![Total Downloads](https://img.shields.io/packagist/dt/ossycodes/friendlycaptcha.svg?style=flat-square)](https://packagist.org/packages/ossycodes/friendlycaptcha)
![GitHub Actions](https://github.com/ossycodes/friendlycaptcha/actions/workflows/main.yml/badge.svg)
This package helps in setting up and validating FriendlyCaptcha widget and response in your Laravel applications
## Installation
You can install the package via composer:
```bash
composer require ossycodes/friendlycaptcha
```
### Configuration
Add `FRIENDLY_CAPTCHA_SECRET`, `FRIENDLY_CAPTCHA_SITEKEY` and optional `FRIENDLY_CAPTCHA_PUZZLE_ENDPOINT`, `FRIENDLY_CAPTCHA_VERIFY_ENDPOINT` in **.env** file :
```
FRIENDLY_CAPTCHA_SECRET=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
FRIENDLY_CAPTCHA_SITEKEY=XXXXXXXXXXXXXXXX
FRIENDLY_CAPTCHA_PUZZLE_ENDPOINT=https://api.friendlycaptcha.com/api/v1/puzzle #optional
FRIENDLY_CAPTCHA_VERIFY_ENDPOINT=https://api.friendlycaptcha.com/api/v1/siteverify #optional
```
You can obtain your site-key from [here](https://docs.friendlycaptcha.com/#/installation?id=_1-generating-a-sitekey) and secret from [here](https://apiserver-prod.friendlycaptcha.eu/dashboard/accounts/1118678876/apikeys)
## Usage
For FriendlyCaptcha widget scripts from a CDN, add the Blade directive `@friendlyCaptchaRenderWidgetScripts` in your layout file. This should be added to the `<head>` of your document.
```blade
<html>
<head>
@friendlyCaptchaRenderWidgetScripts()
</head>
<body>
{{ $slot }}
</body>
</html>
```
or if you don't want to use the Blade directive you can do this instead
```php
{!! FriendlyCaptcha::renderWidgetScripts() !!}
```
You have two options on how to add the script tag either from unpkg (default) or from jsdelivr
`@friendlyCaptchaRenderWidgetScripts()`
or
`@friendlyCaptchaRenderWidgetScripts('jsdelivr')`
`{!! FriendlyCaptcha::renderWidgetScripts() !!}`
or
`{!! FriendlyCaptcha::renderWidgetScripts('jsdelivr') !!}`
You can also host the FriendlyCaptcha widget scripts yourself:
```
npm install --save friendly-challenge@0.9.9
```
And import it in your app:
```js
import "friendly-challenge/widget";
```
Once that's done, you can call the `renderWidget()` method in `<form>` to output the appropriate markup (friendlycaptcha widget) with your site key configured.
```blade
<form action="/" method="POST">
{!! FriendlyCaptcha::renderWidget() !!}
or with custom theme
{!! FriendlyCaptcha::renderWidget(['dark-theme' => true]) !!}
or with custom language
{!! FriendlyCaptcha::renderWidget(['data-lang' => 'en']) !!}
<button>
Submit
</button>
</form>
```
Finally On the server, use the provided validation rule to validate the CAPTCHA response.
```php
use Illuminate\Validation\Rule;
public function submit(Request $request)
{
$request->validate([
'frc-captcha-solution' => ['required', Rule::friendlycaptcha()],
]);
}
```
If you prefer to not use a macro, you can resolve an instance of the rule from the container via dependency injection or the `app()` helper.
```php
use Ossycodes\FriendlyCaptcha\Rules\FriendlyCaptcha;
public function submit(Request $request, FriendlyCaptcha $friendlyCaptcha)
{
$request->validate([
'frc-captcha-solution' => ['required', $friendlyCaptcha],
]);
}
```
```php
use Ossycodes\FriendlyCaptcha\Rules\FriendlyCaptcha;
public function submit(Request $request)
{
$request->validate([
'frc-captcha-solution' => ['required', app(FriendlyCaptcha::class)],
]);
}
```
### Testing
```bash
composer test
```
### Security
If you discover any security related issues, please email osaigbovoemmanuel1@gmail.com instead of using the issue tracker.
## Credits
- [Osaigbovo Emmanuel](https://github.com/ossycodes)
- [Julian Dorn](https://github.com/wi-wissen)
- [All Contributors](../../contributors)
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
## How do I say Thank you?
Please buy me a cup of coffee https://www.paypal.com/paypalme/osaigbovoemmanuel , Leave a star and follow me on [Twitter](https://twitter.com/ossycodes) .

View File

@@ -0,0 +1,59 @@
{
"name": "ossycodes/friendlycaptcha",
"description": "A simple package to help integrate FriendlyCaptcha in your Laravel applications.",
"keywords": [
"friendlycaptcha",
"captcha",
"laravel"
],
"homepage": "https://github.com/ossycodes/friendlycaptcha",
"license": "MIT",
"type": "library",
"authors": [
{
"name": "ossycodes",
"email": "osaigbovoemmanuel1@gmail.com",
"role": "Developer"
}
],
"require": {
"php": "^7.4|^8.0|^8.1|^8.2|^8.3",
"illuminate/support": "^8.0|^9.0|^10.0|^11.0|^12.0",
"guzzlehttp/guzzle": "^7.0"
},
"require-dev": {
"orchestra/testbench": "^6.0|^7.0|^8.0|^9.0",
"phpunit/phpunit": "^8.0 || ^9.5 || ^10.5 || ^11.0 || ^12.0"
},
"autoload": {
"psr-4": {
"Ossycodes\\FriendlyCaptcha\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Ossycodes\\FriendlyCaptcha\\Tests\\": "tests"
}
},
"scripts": {
"test": "vendor/bin/phpunit",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage"
},
"config": {
"sort-packages": true,
"platform-check": false,
"allow-plugins": {
"php-http/discovery": true
}
},
"extra": {
"laravel": {
"providers": [
"Ossycodes\\FriendlyCaptcha\\FriendlyCaptchaServiceProvider"
],
"aliases": {
"FriendlyCaptcha": "Ossycodes\\FriendlyCaptcha\\Facades\\FriendlyCaptcha"
}
}
}
}

View File

@@ -0,0 +1,18 @@
<?php
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
*/
return [
'secret_missing' => 'Sie haben vergessen, den Parameter secret (=API-Schlüssel) hinzuzufügen.',
'secret_invalid' => 'Der von Ihnen angegebene API-Schlüssel war ungültig.',
'solution_missing' => 'Sie haben vergessen, den Parameter secret (=API-Schlüssel) hinzuzufügen.',
'secret_missing' => 'Sie haben vergessen, den Lösungsparameter hinzuzufügen.',
'bad_request' => 'Mit Ihrer Anfrage ist etwas anderes nicht in Ordnung, z. B. ist Ihr Anfragekörper leer.',
'solution_invalid' => 'Die von Ihnen angegebene Lösung war ungültig (vielleicht wurde versucht, das Rätsel zu manipulieren).',
'solution_timeout_or_duplicate' => 'Das Rätsel, für das Sie die Lösung angegeben haben, ist abgelaufen oder wurde bereits verwendet.',
'unexpected' => 'Ein unerwarteter Fehler ist aufgetreten.'
];

View File

@@ -0,0 +1,18 @@
<?php
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
*/
return [
'secret_missing' => 'You forgot to add the secret (=API key) parameter.',
'secret_invalid' => 'The API key you provided was invalid.',
'solution_missing' => 'You forgot to add the secret (=API key) parameter.',
'secret_missing' => 'You forgot to add the solution parameter.',
'bad_request' => 'Something else is wrong with your request, e.g. your request body is empty.',
'solution_invalid' => 'The solution you provided was invalid (perhaps the user tried to tamper with the puzzle).',
'solution_timeout_or_duplicate' => 'The puzzle that the solution was for has expired or has already been used.',
'unexpected' => 'An unexpected error occurred.'
];

View File

@@ -0,0 +1,18 @@
<?php
namespace Ossycodes\FriendlyCaptcha\Facades;
use Illuminate\Support\Facades\Facade;
class FriendlyCaptcha extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'FriendlyCaptcha';
}
}

View File

@@ -0,0 +1,203 @@
<?php
namespace Ossycodes\FriendlyCaptcha;
use GuzzleHttp\Client;
class FriendlyCaptcha
{
/**
* FriendlyCaptcha secret
*
* @var string
*/
protected $secret;
/**
* FriendlyCaptcha sitekey
*
* @var string
*/
protected $sitekey;
/**
* FriendlyCaptcha Puzzle endpoint
*/
protected $puzzle;
/**
* FriendlyCaptcha verify endpoint
*/
protected $verify;
/**
* error messages
*
* @var array
*/
protected $error = [];
public $isSuccess = false;
/**
* @var \GuzzleHttp\Client
*/
protected $http;
public function __construct($secret, $sitekey, $puzzle, $verify, $options = [])
{
$this->secret = $secret;
$this->sitekey = $sitekey;
$this->puzzle = $puzzle;
$this->verify = $verify;
$this->http = new Client($options);
}
public function renderWidgetScripts($option = 'unpkg')
{
if ($option == 'unpkg') {
return <<<EOF
<script type="module" src="https://unpkg.com/friendly-challenge@0.9.9/widget.module.min.js" async defer></script>
<script nomodule src="https://unpkg.com/friendly-challenge@0.9.9/widget.min.js" async defer></script>
EOF;
}
return <<<EOF
<script type="module" src="https://cdn.jsdelivr.net/npm/friendly-challenge@0.9.9/widget.module.min.js" async defer></script>
<script nomodule src="https://cdn.jsdelivr.net/npm/friendly-challenge@0.9.9/widget.min.js" async defer></script>
EOF;
}
public function renderWidget($attributes = [])
{
$attributes = $this->prepareAttributes($attributes);
return '<div' . $this->buildAttributes($attributes) . '></div>';
}
/**
* Prepare HTML attributes and ensure that the correct classes and attributes for captcha are inserted.
*
* @param array $attributes
*
* @return array
*/
protected function prepareAttributes(array $attributes)
{
$attributes['data-puzzle-endpoint'] = $this->puzzle;
$attributes['data-sitekey'] = $this->sitekey;
if (isset($attributes['dark-theme'])) {
$attributes['class'] = 'frc-captcha dark';
unset($attributes['dark-theme']);
return $attributes;
}
$attributes['class'] = trim('frc-captcha');
$locale = app()->getLocale();
if (in_array($locale, ["en", "fr", "de", "it", "nl", "pt", "es", "ca", "da", "ja", "ru", "sv", "el", "uk", "bg", "cs", "sk", "no", "fi", "lt", "lt", "pl", "et", "hr", "sr", "sl", "hu", "ro", "zh", "zh_TW", "vi"])) {
//use supported locale - https://docs.friendlycaptcha.com/#/widget_api?id=data-lang-attribute
$attributes['data-lang'] = $locale;
}
return $attributes;
}
/**
* Build HTML attributes.
*
* @param array $attributes
*
* @return string
*/
protected function buildAttributes(array $attributes)
{
$html = [];
foreach ($attributes as $key => $value) {
$html[] = $key . '="' . $value . '"';
}
return count($html) ? ' ' . implode(' ', $html) : '';
}
/**
* Verify FriendlyCaptcha response.
*
* @param string $solution
*
* @return bool
*/
public function verifyRequest($solution)
{
return $this->verifyResponse(
$solution,
);
}
/**
* Verify FriendlyCaptcha response.
*
* @param string $solution
*
* @return self
*/
public function verifyResponse($solution)
{
if (empty($solution)) {
return false;
}
$verifyResponse = $this->sendRequestVerify([
'solution' => $solution,
'secret' => $this->secret,
'sitekey' => $this->sitekey,
]);
if (isset($verifyResponse['success']) && $verifyResponse['success'] === true) {
$this->isSuccess = true;
return $this;
}
if (isset($verifyResponse['errors'])) {
$this->errors = $verifyResponse['errors'];
}
if (isset($verifyResponse['error'])) {
$this->errors = [$verifyResponse['error']];
}
$this->isSuccess = false;
return $this;
}
/**
* Send verify request.
*
* @param array $data
*
* @return array
*/
protected function sendRequestVerify(array $data = [])
{
$response = $this->http->request('POST', $this->verify, [
'form_params' => $data,
]);
return json_decode($response->getBody(), true);
}
public function isSuccess()
{
return $this->isSuccess;
}
public function getErrors()
{
return $this->errors;
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace Ossycodes\FriendlyCaptcha;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Ossycodes\FriendlyCaptcha\FriendlyCaptcha;
class FriendlyCaptchaServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application services.
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->bootConfig();
}
$this->bootBladeDirectives();
$this->bootMacro();
$this->bootLang();
}
/**
* Boot config.
*/
protected function bootConfig()
{
$path = __DIR__ . '/config/friendlycaptcha.php';
if (function_exists('config_path')) {
$this->publishes([$path => config_path('friendlycaptcha.php')]);
}
}
/**
* Boot blade directives
*/
public function bootBladeDirectives()
{
Blade::directive('friendlyCaptchaRenderWidgetScripts', function ($option) {
$option = trim($option, "'");
if (empty($option) || $option == 'unpkg') {
return <<<EOF
<script type="module" src="https://unpkg.com/friendly-challenge@0.9.8/widget.module.min.js" async defer></script>
<script nomodule src="https://unpkg.com/friendly-challenge@0.9.8/widget.min.js" async defer></script>
EOF;
}
return <<<EOF
<script type="module" src="https://cdn.jsdelivr.net/npm/friendly-challenge@0.9.8/widget.module.min.js" async defer></script>
<script nomodule src="https://cdn.jsdelivr.net/npm/friendly-challenge@0.9.8/widget.min.js" async defer></script>
EOF;
});
}
/**
* boot macro
*/
public function bootMacro()
{
Rule::macro('friendlycaptcha', function () {
return app(\Ossycodes\FriendlyCaptcha\Rules\FriendlyCaptcha::class);
});
}
/**
* boot lang
*/
public function bootLang()
{
Rule::macro('friendlycaptcha', function () {
$this->loadTranslationsFrom(__DIR__.'/../lang', 'friendlycaptcha');
});
}
/**
* Register the application services.
*/
public function register()
{
$path = __DIR__ . '/config/friendlycaptcha.php';
$this->mergeConfigFrom($path, 'friendlycaptcha');
$this->app->singleton('FriendlyCaptcha', function ($app) {
return new FriendlyCaptcha(
$app['config']['friendlycaptcha.secret'],
$app['config']['friendlycaptcha.sitekey'],
$app['config']['friendlycaptcha.puzzle_endpoint'],
$app['config']['friendlycaptcha.verify_endpoint'],
$app['config']['friendlycaptcha.options']
);
});
$this->app->alias('FriendlyCaptcha', FriendlyCaptcha::class);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['FriendlyCaptcha'];
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace Ossycodes\FriendlyCaptcha\Rules;
use Illuminate\Contracts\Validation\Rule;
use Ossycodes\FriendlyCaptcha\FriendlyCaptcha as FriendlyCaptchaClient;
class FriendlyCaptcha implements Rule
{
protected $friendlyCaptchaClient;
protected array $messages = [];
public function __construct(
FriendlyCaptchaClient $friendlyCaptcha
) {
$this->friendlyCaptchaClient = $friendlyCaptcha;
}
public function passes($attribute, $value)
{
$response = $this->friendlyCaptchaClient->verifyResponse($value);
if ($response->isSuccess()) {
return true;
}
foreach ($response->getErrors() as $errorCode) {
$this->messages[] = $this->mapErrorCodeToMessage($errorCode);
}
return false;
}
public function message()
{
return $this->messages;
}
/**
* map FriendlyCaptcha error code to human readable validation message
*
* @var string $code
*/
protected function mapErrorCodeToMessage(string $code): string
{
switch ($code) {
case "secret_missing":
return __('validation.secret_missing');
break;
case "secret_invalid":
return __('validation.secret_invalid');
break;
case "solution_missing":
return __('validation.solution_missing');
break;
case "bad_request":
return __('validation.bad_request');
break;
case "solution_invalid":
return __('validation.solution_invalid');
break;
case "solution_timeout_or_duplicate":
return __('validation.solution_timeout_or_duplicate');
break;
default:
return __('validation.unexpected');
}
}
}

View File

@@ -0,0 +1,12 @@
<?php
return [
'secret' => env('FRIENDLY_CAPTCHA_SECRET'),
'sitekey' => env('FRIENDLY_CAPTCHA_SITEKEY'),
'puzzle_endpoint' => env('FRIENDLY_CAPTCHA_PUZZLE_ENDPOINT', 'https://api.friendlycaptcha.com/api/v1/puzzle'),
'verify_endpoint' => env('FRIENDLY_CAPTCHA_VERIFY_ENDPOINT', 'https://api.friendlycaptcha.com/api/v1/siteverify'),
'options' => [
'timeout' => 30,
'http_errors' => false,
],
];