1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\Csrf; |
6
|
|
|
|
7
|
|
|
use Chubbyphp\ErrorHandler\HttpException; |
8
|
|
|
use Chubbyphp\Session\SessionInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
10
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
11
|
|
|
use Psr\Log\LoggerInterface; |
12
|
|
|
use Psr\Log\NullLogger; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @deprecated use CsrfErrorResponseMiddleware |
16
|
|
|
*/ |
17
|
|
|
final class CsrfMiddleware |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var CsrfErrorResponseMiddleware |
21
|
|
|
*/ |
22
|
|
|
private $middleware; |
23
|
|
|
|
24
|
|
|
const CSRF_KEY = 'csrf'; |
25
|
|
|
|
26
|
|
|
const EXCEPTION_STATUS = 424; |
27
|
|
|
|
28
|
|
|
const EXCEPTION_MISSING_IN_SESSION = 'Csrf token is missing within session'; |
29
|
|
|
const EXCEPTION_MISSING_IN_BODY = 'Csrf token is missing within body'; |
30
|
|
|
const EXCEPTION_IS_NOT_SAME = 'Csrf token within body is not the same as in session'; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param CsrfTokenGeneratorInterface $csrfTokenGenerator |
34
|
|
|
* @param SessionInterface $session |
35
|
|
|
* @param LoggerInterface|null $logger |
36
|
|
|
*/ |
37
|
6 |
|
public function __construct( |
38
|
|
|
CsrfTokenGeneratorInterface $csrfTokenGenerator, |
39
|
|
|
SessionInterface $session, |
40
|
|
|
LoggerInterface $logger = null |
41
|
|
|
) { |
42
|
6 |
|
$this->middleware = new CsrfErrorResponseMiddleware( |
43
|
6 |
|
$csrfTokenGenerator, |
44
|
6 |
|
$session, |
45
|
|
|
new class() implements CsrfErrorHandlerInterface { |
46
|
3 |
|
public function errorResponse( |
47
|
|
|
Request $request, |
48
|
|
|
Response $response, |
49
|
|
|
int $code, |
50
|
|
|
string $reasonPhrase |
51
|
|
|
): Response { |
52
|
3 |
|
throw HttpException::create($request, $response, $code, $reasonPhrase); |
53
|
|
|
} |
54
|
|
|
}, |
55
|
6 |
|
$logger |
56
|
|
|
); |
57
|
|
|
|
58
|
6 |
|
$this->csrfTokenGenerator = $csrfTokenGenerator; |
|
|
|
|
59
|
6 |
|
$this->session = $session; |
|
|
|
|
60
|
6 |
|
$this->logger = $logger ?? new NullLogger(); |
|
|
|
|
61
|
6 |
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param Request $request |
65
|
|
|
* @param Response $response |
66
|
|
|
* @param callable $next |
67
|
|
|
* |
68
|
|
|
* @return Response |
69
|
|
|
*/ |
70
|
6 |
|
public function __invoke(Request $request, Response $response, callable $next = null) |
71
|
|
|
{ |
72
|
6 |
|
return $this->middleware->__invoke($request, $response, $next); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: