summaryrefslogtreecommitdiff
path: root/src/Middleware/VerifyCsrfToken.php
blob: 0623fa729916a2de0058429549003b02f5ca66c8 (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php

namespace Engelsystem\Middleware;

use Engelsystem\Http\Exceptions\HttpAuthExpired;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class VerifyCsrfToken implements MiddlewareInterface
{
    /** @var SessionInterface */
    protected $session;

    /**
     * @param SessionInterface $session
     */
    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    /**
     * Verify csrf tokens
     *
     * @param ServerRequestInterface  $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (
            $this->isReading($request)
            || $this->tokensMatch($request)
        ) {
            return $handler->handle($request);
        }

        throw new HttpAuthExpired('Authentication Token Mismatch');
    }

    /**
     * @param ServerRequestInterface $request
     * @return bool
     */
    protected function isReading(ServerRequestInterface $request): bool
    {
        return in_array(
            $request->getMethod(),
            ['GET', 'HEAD', 'OPTIONS']
        );
    }

    /**
     * @param ServerRequestInterface $request
     * @return bool
     */
    protected function tokensMatch(ServerRequestInterface $request): bool
    {
        $token = null;
        $body = $request->getParsedBody();
        $header = $request->getHeader('X-CSRF-TOKEN');

        if (is_array($body) && isset($body['_token'])) {
            $token = $body['_token'];
        }

        if (!empty($header)) {
            $header = array_shift($header);
        }

        $token = $token ?: $header;
        $sessionToken = $this->session->get('_token');

        return is_string($token)
            && is_string($sessionToken)
            && hash_equals($sessionToken, $token);
    }
}