Skip to content

Commit

Permalink
Feat/recaptcha (#298)
Browse files Browse the repository at this point in the history
* error handling

* init recaptcha

---------

Co-authored-by: Andrei Ioniță <[email protected]>
  • Loading branch information
gheorghelupu17 and andreiio committed Oct 3, 2023
1 parent 7f6e96c commit 57aa135
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
34 changes: 34 additions & 0 deletions app/Rules/Recaptcha.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Http;

class Recaptcha implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$response = Http::asForm()
->post(config('services.google_recaptcha.url'), [
'secret' => config('services.google_recaptcha.secret_key'),
'response' => $value,
])
->json();

$success = (bool) data_get($response, 'success');
$score = (float) data_get($response, 'score');

if (! $success || $score < config('services.google_recaptcha.threshold')) {
$fail('The :attribute field is invalid.');
}
}
}
6 changes: 6 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,10 @@

'google_maps_api_key' => env('GOOGLE_MAPS_API_KEY'),

'google_recaptcha' => [
'url' => 'https://www.google.com/recaptcha/api/siteverify',
'site_key' => env('GOOGLE_RECAPTCHA_SITE_KEY'),
'secret_key' => env('GOOGLE_RECAPTCHA_SECRET_SITE_KEY'),
'threshold' => max(0.0, min(1.0, floatval(env('GOOGLE_RECAPTCHA_SECRET_SITE_KEY', 0.5)))),
],
];

0 comments on commit 57aa135

Please sign in to comment.