Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

namespace Blumilk\Website\Providers;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
use Lunaweb\RecaptchaV3\Facades\RecaptchaV3;

class AppServiceProvider extends ServiceProvider
{
Expand All @@ -18,5 +20,18 @@ public function boot(): void
$request->setLocale("pl");
app()->setLocale("pl");
}

$this->app["validator"]->extend("recaptchav3", function ($attribute, $value, $parameters): bool {
$action = $parameters[0];
$minScore = isset($parameters[1]) ? (float)$parameters[1] : 0.5;

try {
$score = RecaptchaV3::verify($value, $action);

return $score && $score >= $minScore;
} catch (Exception) {
return false;
}
});
}
}
52 changes: 52 additions & 0 deletions tests/Unit/RecaptchaTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Validator;
use Lunaweb\RecaptchaV3\Facades\RecaptchaV3;
use Tests\TestCase;

class RecaptchaTest extends TestCase
{
public function testRecaptchav3ValidationPassesWhenScoreIsHighEnough(): void
{
RecaptchaV3::shouldReceive("verify")
->once()
->andReturn(0.8);

$data = ["token" => "dummy-token"];
$rules = ["token" => "recaptchav3:contact,0.5"];

$validator = Validator::make($data, $rules);

$this->assertTrue($validator->passes());
}

public function testRecaptchav3ValidationFailsWhenScoreIsTooLow(): void
{
RecaptchaV3::shouldReceive("verify")
->once()
->andReturn(0.3);

$data = ["token" => "dummy-token"];
$rules = ["token" => "recaptchav3:contact,0.5"];

$validator = Validator::make($data, $rules);

$this->assertFalse($validator->passes());
}

public function testRecaptchav3ValidationFailsWhenExceptionIsThrown(): void
{
RecaptchaV3::shouldReceive("verify")
->once()
->andThrow(new Exception());

$data = ["token" => "dummy-token"];
$rules = ["token" => "recaptchav3:contact,0.5"];

$validator = Validator::make($data, $rules);

$this->assertFalse($validator->passes());
}
}