Completed
Push — master ( 13edef...d5b56b )
by Jeroen
85:52 queued 71:18
created

SessionSecurityListener::onKernelRequest()   C

Complexity

Conditions 14
Paths 7

Size

Total Lines 35

Duplication

Lines 19
Ratio 54.29 %

Code Coverage

Tests 19
CRAP Score 14

Importance

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

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 3
     */
45
    public function __construct($ipCheck, $userAgentCheck, LoggerInterface $logger)
46 3
    {
47 3
        $this->ipCheck = $ipCheck;
48 3
        $this->userAgentCheck = $userAgentCheck;
49 3
        $this->logger = $logger;
50
    }
51
52
    /**
53
     * @param FilterResponseEvent|ResponseEvent $event
54 2
     */
55
    public function onKernelResponse($event)
56 2
    {
57 1 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 2
            return;
63 2
        }
64 2
65 2
        // Make sure the ip and user agent is stored in the session
66
        $request = $event->getRequest();
67 2
        if ($request->hasSession() && $request->getSession()->isStarted()) {
68 2
            $session = $request->getSession();
69
            if ($this->ipCheck && !$session->has('kuma_ip')) {
70
                $session->set('kuma_ip', $this->getIp($request));
71 2
            }
72
            if ($this->userAgentCheck && !$session->has('kuma_ua')) {
73
                $session->set('kuma_ua', $this->getUserAgent($request));
74
            }
75
        }
76 1
    }
77
78 1
    /**
79 1
     * @param GetResponseEvent $event
80
     */
81
    public function onKernelRequest(GetResponseEvent $event)
82 1
    {
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 1
            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 1
        }
90 1
91 1
        $request = $event->getRequest();
92
        if ($request->hasSession() && $request->getSession()->isStarted()) {
93 1
            $session = $request->getSession();
94
95
            // Check that the ip matches
96 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 1
                ));
102
                $this->invalidateSession($session, $request);
103 1
            }
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
                $this->logger->error(sprintf(
108
                    "Session user agent '%s' does not match with request user agent '%s', invalidating the current session",
109
                    $session->get('kuma_ua'),
110
                    $this->getUserAgent($request)
111
                ));
112 1
                $this->invalidateSession($session, $request);
113
            }
114 1
        }
115 1
    }
116 1
117 1
    /**
118
     * @param SessionInterface $session
119
     * @param Request          $request
120
     */
121
    private function invalidateSession(SessionInterface $session, Request $request)
122
    {
123
        $session->invalidate();
124 3
        $session->set('kuma_ip', $this->getIp($request));
125
        $session->set('kuma_ua', $this->getUserAgent($request));
126 3
    }
127 3
128 3
    /**
129 2
     * @param Request $request
130 2
     *
131 2
     * @return string
132 2
     */
133 2
    private function getIp(Request $request)
134
    {
135
        if (!$this->ip) {
136 3
            $forwarded = $request->server->get('HTTP_X_FORWARDED_FOR');
137 1
            if (strlen($forwarded) > 0) {
138
                $parts = explode(',', $forwarded);
139 3
                $parts = array_map('trim', $parts);
140
                $parts = array_filter($parts);
141
                if (count($parts) > 0) {
142 3
                    $ip = $parts[0];
143
                }
144
            }
145
            if (empty($ip)) {
146
                $ip = $request->getClientIp();
147
            }
148
            $this->ip = $ip;
149
        }
150 3
151
        return $this->ip;
152 3
    }
153 3
154
    /**
155
     * @param Request $request
156 3
     *
157
     * @return array|string
158
     */
159
    private function getUserAgent(Request $request)
160
    {
161
        if (!$this->userAgent) {
162
            $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
        return $this->userAgent;
166
    }
167
}
168