Csrf::processRequest()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 12
cts 12
cp 1
rs 8.2222
c 0
b 0
f 0
cc 7
eloc 11
nc 4
nop 2
crap 7
1
<?php
2
3
namespace BrainExe\Core\Middleware;
4
5
use BrainExe\Core\Annotations\Middleware;
6
use BrainExe\Core\Traits\IdGeneratorTrait;
7
use BrainExe\Core\Traits\TimeTrait;
8
use Symfony\Component\HttpFoundation\Cookie;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\HttpFoundation\Session\SessionInterface;
12
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
13
use Symfony\Component\Routing\Route;
14
15
/**
16
 * @Middleware("Middleware.Csrf")
17
 */
18
class Csrf extends AbstractMiddleware
19
{
20
21
    const CSRF   = 'csrf';
22
    const HEADER = 'X-XSRF-TOKEN';
23
    const COOKIE = 'XSRF-TOKEN';
24
25
    const LIFETIME = 0;
26
27
    use IdGeneratorTrait;
28
    use TimeTrait;
29
30
    /**
31
     * @var string
32
     */
33
    private $newToken;
34
35
    /**
36
     * {@inheritdoc}
37
     * @throws MethodNotAllowedException
38
     */
39 3
    public function processRequest(Request $request, Route $route)
40
    {
41 3
        $givenToken = $request->headers->get(self::HEADER);
42
43 3
        $session = $request->getSession();
44 3
        $expectedToken = $session->get(self::CSRF);
45 3
        if ($request->isMethod('GET') && (!$route->hasOption(self::CSRF)) || $route->hasDefault('_guest')) {
46 1
            if (empty($expectedToken)) {
47 1
                $this->renewCsrfToken();
48
            }
49 1
            return;
50
        }
51
52 2
        if (empty($givenToken) || $givenToken !== $expectedToken) {
53 1
            throw new MethodNotAllowedException(['POST'], 'invalid CSRF token');
54
        }
55
56 1
        $this->generateNewTokenWhenNeeded($session);
0 ignored issues
show
Bug introduced by
It seems like $session defined by $request->getSession() on line 43 can be null; however, BrainExe\Core\Middleware...ateNewTokenWhenNeeded() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
57 1
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 2
    public function processResponse(Request $request, Response $response)
63
    {
64 2
        if ($this->newToken) {
65 2
            $session = $request->getSession();
66 2
            $session->set(self::CSRF, $this->newToken);
67 2
            $session->set('csrf_timestamp', $this->now());
68 2
            $response->headers->setCookie(
69 2
                new Cookie(
70 2
                    self::COOKIE,
71 2
                    $this->newToken,
72 2
                    0,
73 2
                    '/',
74 2
                    null,
75 2
                    false,
76 2
                    false
77
                )
78
            );
79 2
            $this->newToken = null;
80
        }
81 2
    }
82
83
    /**
84
     * @return void
85
     */
86 2
    private function renewCsrfToken()
87
    {
88 2
        $this->newToken = $this->generateRandomId(20);
89 2
    }
90
91
    /**
92
     * @param SessionInterface $session
93
     */
94 1
    private function generateNewTokenWhenNeeded(SessionInterface $session)
95
    {
96 1
        $now        = $this->now();
97 1
        $lastUpdate = $session->get('csrf_timestamp');
98 1
        if ($lastUpdate + self::LIFETIME < $now) {
99 1
            $this->renewCsrfToken();
100
        }
101 1
    }
102
}
103