File size: 1,683 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php

namespace Presentation\Middlewares;

use Easy\Container\Attributes\Inject;
use Presentation\Validation\ValidationException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use User\Infrastructure\Services\Captcha\GoogleRecaptcha;
use User\Infrastructure\Services\Captcha\VerificationFailedException;

class CaptchaMiddleware implements MiddlewareInterface
{
    public function __construct(
        private GoogleRecaptcha $captcha,

        #[Inject('option.recaptcha.is_enabled')]
        private bool $captchaEnabled = false,
    ) {
    }

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        if (!$this->captchaEnabled) {
            return $handler->handle($request);
        }

        $params = $request->getParsedBody();
        $param = 'captcha-token';
        $token = $params->$param ?? null;

        if (!$token) {
            throw new ValidationException(
                'Missing captcha token in request body',
                $param
            );
        }

        if (!is_string($token)) {
            throw new ValidationException(
                'Captcha token must be a string',
                $param
            );
        }

        try {
            $this->captcha->verifyToken($token);
        } catch (VerificationFailedException $th) {
            throw new ValidationException(
                'Captcha verification failed',
                $param
            );
        }

        return $handler->handle($request);
    }
}