Recaptcha::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use RuntimeException;
9
use ReCaptcha\ReCaptcha as GoogleRecaptcha;
10
11
/**
12
 * Middleware to include google recaptcha protection.
13
 */
14
class Recaptcha
15
{
16
    use Utils\AttributeTrait;
17
18
    private $secret;
19
20
    /**
21
     * Constructor. Set the secret token.
22
     *
23
     * @param string $secret
24
     */
25
    public function __construct($secret)
26
    {
27
        $this->secret = $secret;
28
    }
29
30
    /**
31
     * Execute the middleware.
32
     *
33
     * @param ServerRequestInterface $request
34
     * @param ResponseInterface      $response
35
     * @param callable               $next
36
     *
37
     * @return ResponseInterface
38
     */
39
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
40
    {
41
        if (!self::hasAttribute($request, ClientIp::KEY)) {
42
            throw new RuntimeException('Recaptcha middleware needs ClientIp executed before');
43
        }
44
45
        if (Utils\Helpers::isPost($request)) {
46
            $recaptcha = new GoogleRecaptcha($this->secret);
47
48
            $data = $request->getParsedBody();
49
            $res = $recaptcha->verify(isset($data['g-recaptcha-response']) ? $data['g-recaptcha-response'] : '', ClientIp::getIp($request));
50
51
            if (!$res->isSuccess()) {
52
                return $response->withStatus(403);
53
            }
54
        }
55
56
        return $next($request, $response);
57
    }
58
}
59