Completed
Push — master ( 06c1ce...67d37c )
by Jeroen
06:20
created

SessionSecurityListener::onKernelRequest()   C

Complexity

Conditions 14
Paths 7

Size

Total Lines 35

Duplication

Lines 19
Ratio 54.29 %

Code Coverage

Tests 20
CRAP Score 14.0211

Importance

Changes 0
Metric Value
dl 19
loc 35
ccs 20
cts 21
cp 0.9524
rs 6.2666
c 0
b 0
f 0
cc 14
nc 7
nop 1
crap 14.0211

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Kunstmaan\AdminBundle\EventListener;
4
5
use Psr\Log\LoggerInterface;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpFoundation\Session\SessionInterface;
8
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
9
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
10
use Symfony\Component\HttpKernel\Event\ResponseEvent;
11
use Symfony\Component\HttpKernel\HttpKernelInterface;
12
13
class SessionSecurityListener
14
{
15
    /**
16
     * @var LoggerInterface
17
     */
18
    private $logger;
19
20
    /**
21
     * @var bool
22
     */
23
    private $ipCheck;
24
25
    /**
26
     * @var bool
27
     */
28
    private $userAgentCheck;
29
30
    /**
31
     * @var string
32
     */
33
    private $ip;
34
35
    /**
36
     * @var string
37
     */
38
    private $userAgent;
39
40
    /**
41
     * @param bool            $ipCheck
42
     * @param bool            $userAgentCheck
43
     * @param LoggerInterface $logger
44
     */
45 3
    public function __construct($ipCheck, $userAgentCheck, LoggerInterface $logger)
46
    {
47 3
        $this->ipCheck = $ipCheck;
48 3
        $this->userAgentCheck = $userAgentCheck;
49 3
        $this->logger = $logger;
50 3
    }
51
52
    /**
53
     * @param FilterResponseEvent|ResponseEvent $event
54
     */
55 2
    public function onKernelResponse($event)
56
    {
57 2 View Code Duplication
        if (!$event instanceof FilterResponseEvent && !$event instanceof ResponseEvent) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
58
            throw new \InvalidArgumentException(\sprintf('Expected instance of type %s, %s given', \class_exists(ResponseEvent::class) ? ResponseEvent::class : FilterResponseEvent::class, \is_object($event) ? \get_class($event) : \gettype($event)));
59
        }
60
61 2
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
62 1
            return;
63
        }
64
65
        // Make sure the ip and user agent is stored in the session
66 2
        $request = $event->getRequest();
67 2
        if ($request->hasSession() && $request->getSession()->isStarted()) {
68 2
            $session = $request->getSession();
69 2
            if ($this->ipCheck && !$session->has('kuma_ip')) {
70 2
                $session->set('kuma_ip', $this->getIp($request));
71
            }
72 2
            if ($this->userAgentCheck && !$session->has('kuma_ua')) {
73 2
                $session->set('kuma_ua', $this->getUserAgent($request));
74
            }
75
        }
76 2
    }
77
78
    /**
79
     * @param GetResponseEvent $event
80
     */
81 1
    public function onKernelRequest(GetResponseEvent $event)
82
    {
83 1 View Code Duplication
        if (!$event instanceof GetResponseEvent && !$event instanceof ResponseEvent) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
            throw new \InvalidArgumentException(\sprintf('Expected instance of type %s, %s given', \class_exists(ResponseEvent::class) ? ResponseEvent::class : GetResponseEvent::class, \is_object($event) ? \get_class($event) : \gettype($event)));
85
        }
86
87 1
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
88 1
            return;
89
        }
90
91 1
        $request = $event->getRequest();
92 1
        if ($request->hasSession() && $request->getSession()->isStarted()) {
93 1
            $session = $request->getSession();
94
95
            // Check that the ip matches
96 1 View Code Duplication
            if ($this->ipCheck && $session->has('kuma_ip') && $session->get('kuma_ip') != $this->getIp($request)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
97 1
                $this->logger->error(sprintf(
98 1
                    "Session ip '%s' does not match with request ip '%s', invalidating the current session",
99 1
                    $session->get('kuma_ip'),
100 1
                    $this->getIp($request)
101
                ));
102 1
                $this->invalidateSession($session, $request);
103
            }
104
105
            // Check that the user agent matches
106 1 View Code Duplication
            if ($this->userAgentCheck && $session->has('kuma_ua') && $session->get('kuma_ua') != $this->getUserAgent($request)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107 1
                $this->logger->error(sprintf(
108 1
                    "Session user agent '%s' does not match with request user agent '%s', invalidating the current session",
109 1
                    $session->get('kuma_ua'),
110 1
                    $this->getUserAgent($request)
111
                ));
112 1
                $this->invalidateSession($session, $request);
113
            }
114
        }
115 1
    }
116
117
    /**
118
     * @param SessionInterface $session
119
     * @param Request          $request
120
     */
121 1
    private function invalidateSession(SessionInterface $session, Request $request)
122
    {
123 1
        $session->invalidate();
124 1
        $session->set('kuma_ip', $this->getIp($request));
125 1
        $session->set('kuma_ua', $this->getUserAgent($request));
126 1
    }
127
128
    /**
129
     * @param Request $request
130
     *
131
     * @return string
132
     */
133 3
    private function getIp(Request $request)
134
    {
135 3
        if (!$this->ip) {
136 3
            $forwarded = $request->server->get('HTTP_X_FORWARDED_FOR');
137 3
            if (\strlen($forwarded) > 0) {
138 2
                $parts = explode(',', $forwarded);
139 2
                $parts = array_map('trim', $parts);
140 2
                $parts = array_filter($parts);
141 2
                if (\count($parts) > 0) {
142 2
                    $ip = $parts[0];
143
                }
144
            }
145 3
            if (empty($ip)) {
146 1
                $ip = $request->getClientIp();
147
            }
148 3
            $this->ip = $ip;
149
        }
150
151 3
        return $this->ip;
152
    }
153
154
    /**
155
     * @param Request $request
156
     *
157
     * @return array|string
158
     */
159 3
    private function getUserAgent(Request $request)
160
    {
161 3
        if (!$this->userAgent) {
162 3
            $this->userAgent = $request->headers->get('User-Agent');
0 ignored issues
show
Documentation Bug introduced by
It seems like $request->headers->get('User-Agent') can also be of type array. However, the property $userAgent is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
163
        }
164
165 3
        return $this->userAgent;
166
    }
167
}
168