Recaptcha   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 7

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 7
dl 0
loc 45
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B __invoke() 0 19 5
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