Completed
Push — master ( 00ed35...63fbb3 )
by Oscar
10:20
created

Recaptcha::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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