Failed Conditions
Pull Request — master (#262)
by Guilherme
10:25 queued 04:26
created

SecurityHelperTest   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 402
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 402
rs 10
c 0
b 0
f 0
wmc 21
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\CoreBundle\Tests\Helper;
12
13
use LoginCidadao\APIBundle\Entity\ActionLogRepository;
14
use LoginCidadao\CoreBundle\Entity\Person;
15
use LoginCidadao\CoreBundle\Helper\ExtremeNotificationsHelper;
16
use LoginCidadao\CoreBundle\Helper\SecurityHelper;
17
use LoginCidadao\CoreBundle\Model\PersonInterface;
18
use PHPUnit\Framework\TestCase;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
22
use Symfony\Component\HttpFoundation\Session\SessionInterface;
23
use Symfony\Component\Routing\RouterInterface;
24
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
25
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
26
use Symfony\Component\Security\Core\User\User;
27
28
class SecurityHelperTest extends TestCase
29
{
30
    public function testGetLoggedInUserLevelNonDefault()
31
    {
32
        $authChecker = $this->getAuthChecker();
33
        $authChecker->expects($this->atLeastOnce())
34
            ->method('isGranted')
35
            ->willReturnMap([
36
                ['ROLE_SUPER_ADMIN', null, false],
37
                ['ROLE_ADMIN', null, false],
38
                ['ROLE_SUPER_USER', null, true],
39
                ['ROLE_DEV', null, false],
40
                ['ROLE_USER', null, false],
41
            ]);
42
43
        $helper = new SecurityHelper(
44
            $authChecker,
45
            $this->getTokenStorage(),
46
            $this->getActionLogRepository(),
47
            $this->getExtremeNotificationsHelper(),
48
            $this->getRouter(),
49
            'cookieName'
50
        );
51
52
        $this->assertSame(2, $helper->getLoggedInUserLevel());
53
    }
54
55
    public function testGetLoggedInUserLevelDefault()
56
    {
57
        $authChecker = $this->getAuthChecker();
58
        $authChecker->expects($this->atLeastOnce())
59
            ->method('isGranted');
60
61
        $helper = new SecurityHelper(
62
            $authChecker,
63
            $this->getTokenStorage(),
64
            $this->getActionLogRepository(),
65
            $this->getExtremeNotificationsHelper(),
66
            $this->getRouter(),
67
            'cookieName'
68
        );
69
70
        $this->assertSame(0, $helper->getLoggedInUserLevel());
71
    }
72
73
    public function testCheckNoPendingImpersonateReport()
74
    {
75
        $person = new Person();
76
77
        $repo = $this->getActionLogRepository();
78
        $repo->expects($this->once())
79
            ->method('countImpersonatonsWithoutReports')->with($person)
80
            ->willReturn(0);
81
82
        $helper = new SecurityHelper(
83
            $this->getAuthChecker(),
84
            $this->getTokenStorage(),
85
            $repo,
86
            $this->getExtremeNotificationsHelper(),
87
            $this->getRouter(),
88
            'cookieName'
89
        );
90
91
        $helper->checkPendingImpersonateReport($person);
92
    }
93
94
    public function testCheckPendingImpersonateReport()
95
    {
96
        $count = 2;
97
        $url = 'https://example.com';
98
        $person = new Person();
99
100
        $repo = $this->getActionLogRepository();
101
        $repo->expects($this->once())
102
            ->method('countImpersonatonsWithoutReports')
103
            ->willReturn($count);
104
105
        $router = $this->getRouter();
106
        $router->expects($this->once())
107
            ->method('generate')->with('lc_admin_impersonation_report_index')
108
            ->willReturn($url);
109
110
        $parameters = ['%url%' => $url, '%count%' => $count];
111
112
        $extremeNotifHelper = $this->getExtremeNotificationsHelper();
113
        $extremeNotifHelper->expects($this->once())
114
            ->method('addTransChoice')->with('admin.impersonation_report.pending.notification', $count, $parameters);
115
116
        $helper = new SecurityHelper(
117
            $this->getAuthChecker(),
118
            $this->getTokenStorage(),
119
            $repo,
120
            $extremeNotifHelper,
121
            $router,
122
            'cookieName'
123
        );
124
125
        $helper->checkPendingImpersonateReport($person);
126
    }
127
128
    public function testGetRoleLevel()
129
    {
130
        $helper = new SecurityHelper(
131
            $this->getAuthChecker(),
132
            $this->getTokenStorage(),
133
            $this->getActionLogRepository(),
134
            $this->getExtremeNotificationsHelper(),
135
            $this->getRouter(),
136
            'cookieName'
137
        );
138
139
        $roles = [
140
            'ROLE_SUPER_ADMIN' => 4,
141
            'ROLE_ADMIN' => 3,
142
            'ROLE_SUPER_USER' => 2,
143
            'ROLE_DEV' => 1,
144
            'ROLE_USER' => 0,
145
        ];
146
147
        foreach ($roles as $role => $expected) {
148
            $this->assertSame($expected, $helper->getRoleLevel($role));
149
        }
150
151
        $this->assertSame(4, $helper->getRoleLevel('OTHER_ROLE'));
152
    }
153
154
    public function testGetUser()
155
    {
156
        $person = new Person();
157
158
        $token = $this->createMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
159
        $token->expects($this->once())->method('getUser')->willReturn($person);
160
161
        $tokenStorage = $this->getTokenStorage();
162
        $tokenStorage->expects($this->once())
163
            ->method('getToken')
164
            ->willReturn($token);
165
166
        $helper = new SecurityHelper(
167
            $this->getAuthChecker(),
168
            $tokenStorage,
169
            $this->getActionLogRepository(),
170
            $this->getExtremeNotificationsHelper(),
171
            $this->getRouter(),
172
            'cookieName'
173
        );
174
175
        $this->assertSame($person, $helper->getUser());
176
    }
177
178
    public function testGetUserNotPersonInterface()
179
    {
180
        $user = new User('username', 'password');
181
182
        $token = $this->createMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
183
        $token->expects($this->once())->method('getUser')->willReturn($user);
184
185
        $tokenStorage = $this->getTokenStorage();
186
        $tokenStorage->expects($this->once())
187
            ->method('getToken')
188
            ->willReturn($token);
189
190
        $helper = new SecurityHelper(
191
            $this->getAuthChecker(),
192
            $tokenStorage,
193
            $this->getActionLogRepository(),
194
            $this->getExtremeNotificationsHelper(),
195
            $this->getRouter(),
196
            'cookieName'
197
        );
198
199
        $this->assertNull($helper->getUser());
200
    }
201
202
    public function testGetUserException()
203
    {
204
        $token = $this->createMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
205
        $token->expects($this->once())->method('getUser')->willThrowException(new \RuntimeException());
206
207
        $tokenStorage = $this->getTokenStorage();
208
        $tokenStorage->expects($this->once())
209
            ->method('getToken')
210
            ->willReturn($token);
211
212
        $helper = new SecurityHelper(
213
            $this->getAuthChecker(),
214
            $tokenStorage,
215
            $this->getActionLogRepository(),
216
            $this->getExtremeNotificationsHelper(),
217
            $this->getRouter(),
218
            'cookieName'
219
        );
220
221
        $this->assertNull($helper->getUser());
222
    }
223
224
    public function testGetUserNoToken()
225
    {
226
        $tokenStorage = $this->getTokenStorage();
227
        $tokenStorage->expects($this->once())
228
            ->method('getToken')
229
            ->willReturn(null);
230
231
        $helper = new SecurityHelper(
232
            $this->getAuthChecker(),
233
            $tokenStorage,
234
            $this->getActionLogRepository(),
235
            $this->getExtremeNotificationsHelper(),
236
            $this->getRouter(),
237
            'cookieName'
238
        );
239
240
        $this->assertNull($helper->getUser());
241
    }
242
243
    public function testGetTargetPersonLevel()
244
    {
245
        $personLvl3 = new Person();
246
        $personLvl3->setRoles([
247
            'ROLE_DEV',
248
            'ROLE_ADMIN',
249
        ]);
250
251
        /** @var PersonInterface|\PHPUnit_Framework_MockObject_MockObject $personLvlDefault */
252
        $personLvlDefault = $this->createMock('LoginCidadao\CoreBundle\Model\PersonInterface');
253
        $personLvlDefault->expects($this->once())
254
            ->method('getRoles')
255
            ->willReturn(['OTHER_ROLE']);
256
257
        $helper = new SecurityHelper(
258
            $this->getAuthChecker(),
259
            $this->getTokenStorage(),
260
            $this->getActionLogRepository(),
261
            $this->getExtremeNotificationsHelper(),
262
            $this->getRouter(),
263
            'cookieName'
264
        );
265
266
        $this->assertSame(3, $helper->getTargetPersonLevel($personLvl3));
267
        $this->assertSame(0, $helper->getTargetPersonLevel($personLvlDefault));
268
    }
269
270
    public function testLogout()
271
    {
272
        $rememberMe = 'cookieName';
273
274
        /** @var SessionInterface|\PHPUnit_Framework_MockObject_MockObject $session */
275
        $session = $this->createMock('Symfony\Component\HttpFoundation\Session\SessionInterface');
276
        $session->expects($this->once())->method('invalidate');
277
278
        $request = new Request();
279
        $request->setSession($session);
280
281
        /** @var ResponseHeaderBag|\PHPUnit_Framework_MockObject_MockObject $headers */
282
        $headers = $this->createMock('Symfony\Component\HttpFoundation\ResponseHeaderBag');
283
        $headers->expects($this->once())->method('clearCookie')->with($rememberMe);
284
285
        $response = new Response();
286
        $response->headers = $headers;
287
288
        $tokenStorage = $this->getTokenStorage();
289
        $tokenStorage->expects($this->once())->method('setToken')->with(null);
290
291
        $helper = new SecurityHelper(
292
            $this->getAuthChecker(),
293
            $tokenStorage,
294
            $this->getActionLogRepository(),
295
            $this->getExtremeNotificationsHelper(),
296
            $this->getRouter(),
297
            $rememberMe
298
        );
299
300
        $helper->logout($request, $response);
301
    }
302
303
    public function testIsGranted()
304
    {
305
        $attributes = ['THE_ROLE'];
306
        $object = new \stdClass();
307
308
        $authChecker = $this->getAuthChecker();
309
        $authChecker->expects($this->atLeastOnce())
310
            ->method('isGranted')->with($attributes, $object)
311
            ->willReturn(true);
312
313
        $helper = new SecurityHelper(
314
            $authChecker,
315
            $this->getTokenStorage(),
316
            $this->getActionLogRepository(),
317
            $this->getExtremeNotificationsHelper(),
318
            $this->getRouter(),
319
            'cookieName'
320
        );
321
322
        $this->assertTrue($helper->isGranted($attributes, $object));
323
    }
324
325
    public function testGetTokenRoles()
326
    {
327
        $token = $this->createMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
328
        $token->expects($this->once())->method('getRoles')->willReturn([]);
329
330
        $tokenStorage = $this->getTokenStorage();
331
        $tokenStorage->expects($this->once())
332
            ->method('getToken')
333
            ->willReturn($token);
334
335
        $helper = new SecurityHelper(
336
            $this->getAuthChecker(),
337
            $tokenStorage,
338
            $this->getActionLogRepository(),
339
            $this->getExtremeNotificationsHelper(),
340
            $this->getRouter(),
341
            'cookieName'
342
        );
343
344
        $this->assertEmpty($helper->getTokenRoles());
345
    }
346
347
    public function testHasToken()
348
    {
349
        $token = $this->createMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
350
351
        $tokenStorage = $this->getTokenStorage();
352
        $tokenStorage->expects($this->once())
353
            ->method('getToken')
354
            ->willReturn($token);
355
356
        $helper = new SecurityHelper(
357
            $this->getAuthChecker(),
358
            $tokenStorage,
359
            $this->getActionLogRepository(),
360
            $this->getExtremeNotificationsHelper(),
361
            $this->getRouter(),
362
            'cookieName'
363
        );
364
365
        $this->assertTrue($helper->hasToken());
366
    }
367
368
    public function testIsOAuthToken()
369
    {
370
        $token = $this->getMockBuilder('FOS\OAuthServerBundle\Security\Authentication\Token\OAuthToken')
371
            ->disableOriginalConstructor()->getMock();
372
373
        $tokenStorage = $this->getTokenStorage();
374
        $tokenStorage->expects($this->once())
375
            ->method('getToken')
376
            ->willReturn($token);
377
378
        $helper = new SecurityHelper(
379
            $this->getAuthChecker(),
380
            $tokenStorage,
381
            $this->getActionLogRepository(),
382
            $this->getExtremeNotificationsHelper(),
383
            $this->getRouter(),
384
            'cookieName'
385
        );
386
387
        $this->assertTrue($helper->isOAuthToken());
388
    }
389
390
    /**
391
     * @return AuthorizationCheckerInterface|\PHPUnit_Framework_MockObject_MockObject
392
     */
393
    private function getAuthChecker()
394
    {
395
        return $this->createMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
396
    }
397
398
    /**
399
     * @return TokenStorageInterface|\PHPUnit_Framework_MockObject_MockObject
400
     */
401
    private function getTokenStorage()
402
    {
403
        return $this->createMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface');
404
    }
405
406
    /**
407
     * @return ActionLogRepository|\PHPUnit_Framework_MockObject_MockObject
408
     */
409
    private function getActionLogRepository()
410
    {
411
        return $this->getMockBuilder('LoginCidadao\APIBundle\Entity\ActionLogRepository')
412
            ->disableOriginalConstructor()->getMock();
413
    }
414
415
    /**
416
     * @return ExtremeNotificationsHelper|\PHPUnit_Framework_MockObject_MockObject
417
     */
418
    private function getExtremeNotificationsHelper()
419
    {
420
        return $this->getMockBuilder('LoginCidadao\CoreBundle\Helper\ExtremeNotificationsHelper')
421
            ->disableOriginalConstructor()->getMock();
422
    }
423
424
    /**
425
     * @return RouterInterface|\PHPUnit_Framework_MockObject_MockObject
426
     */
427
    private function getRouter()
428
    {
429
        return $this->createMock('Symfony\Component\Routing\RouterInterface');
430
    }
431
}
432