Passed
Push — master ( bd753d...066495 )
by Darko
10:20
created

TurnstileService   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 28
dl 0
loc 64
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A verify() 0 22 4
A display() 0 23 3
A renderJs() 0 3 1
1
<?php
2
3
namespace App\Services;
4
5
use Illuminate\Support\Facades\Http;
6
7
class TurnstileService
8
{
9
    /**
10
     * Verify Cloudflare Turnstile token
11
     */
12
    public static function verify(string $token, ?string $remoteIp = null): bool
13
    {
14
        $secret = config('captcha.turnstile.secret');
15
16
        if (empty($secret)) {
17
            return false;
18
        }
19
20
        try {
21
            $response = Http::asForm()->post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
22
                'secret' => $secret,
23
                'response' => $token,
24
                'remoteip' => $remoteIp ?? request()->ip(),
25
            ]);
26
27
            $result = $response->json();
28
29
            return isset($result['success']) && $result['success'] === true;
30
        } catch (\Exception $e) {
31
            \Log::error('Turnstile verification failed: '.$e->getMessage());
32
33
            return false;
34
        }
35
    }
36
37
    /**
38
     * Get the Turnstile HTML widget
39
     */
40
    public static function display(array $attributes = []): string
41
    {
42
        $sitekey = config('captcha.turnstile.sitekey');
43
44
        if (empty($sitekey)) {
45
            return '';
46
        }
47
48
        $defaultAttributes = [
49
            'class' => 'cf-turnstile',
50
            'data-sitekey' => $sitekey,
51
            'data-theme' => 'auto',
52
            'data-size' => 'normal',
53
        ];
54
55
        $attributes = array_merge($defaultAttributes, $attributes);
56
57
        $attributesString = '';
58
        foreach ($attributes as $key => $value) {
59
            $attributesString .= sprintf('%s="%s" ', $key, htmlspecialchars($value));
60
        }
61
62
        return sprintf('<div %s></div>', trim($attributesString));
63
    }
64
65
    /**
66
     * Get the Turnstile JavaScript
67
     */
68
    public static function renderJs(): string
69
    {
70
        return '<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>';
71
    }
72
}
73