This commit is contained in:
39
app/Http/Controllers/Concerns/ManagesCaptcha.php
Normal file
39
app/Http/Controllers/Concerns/ManagesCaptcha.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Concerns;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
trait ManagesCaptcha
|
||||
{
|
||||
protected function buildCaptchaQuestion(Request $request, string $context): string
|
||||
{
|
||||
$first = random_int(2, 9);
|
||||
$second = random_int(1, 9);
|
||||
$isSubtraction = random_int(0, 1) === 1;
|
||||
|
||||
if ($isSubtraction && $second > $first) {
|
||||
[$first, $second] = [$second, $first];
|
||||
}
|
||||
|
||||
$question = $isSubtraction ? "{$first} - {$second}" : "{$first} + {$second}";
|
||||
$answer = (string) ($isSubtraction ? $first - $second : $first + $second);
|
||||
|
||||
$request->session()->put("captcha.{$context}.answer", $answer);
|
||||
|
||||
return $question;
|
||||
}
|
||||
|
||||
protected function captchaIsValid(Request $request, string $context, string $field = 'captcha'): bool
|
||||
{
|
||||
$expected = (string) $request->session()->get("captcha.{$context}.answer", '');
|
||||
$provided = trim((string) $request->input($field, ''));
|
||||
|
||||
return $expected !== '' && hash_equals($expected, $provided);
|
||||
}
|
||||
|
||||
protected function clearCaptcha(Request $request, string $context): void
|
||||
{
|
||||
$request->session()->forget("captcha.{$context}.answer");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user