Passed
Push — issue#767 ( 25f84e...39899e )
by Guilherme
07:11
created

SecurityHelperTest::testIsOAuthToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 14
nc 1
nop 0
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
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 Symfony\Component\HttpFoundation\HeaderBag;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\HttpFoundation\Session\SessionInterface;
22
use Symfony\Component\Routing\RouterInterface;
23
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
24
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
25
use Symfony\Component\Security\Core\User\User;
26
27
class SecurityHelperTest extends \PHPUnit_Framework_TestCase
28
{
29
    public function testGetLoggedInUserLevelNonDefault()
30
    {
31
        $authChecker = $this->getAuthChecker();
32
        $authChecker->expects($this->atLeastOnce())
33
            ->method('isGranted')
34
            ->willReturnMap([
35
                ['ROLE_SUPER_ADMIN', null, false],
36
                ['ROLE_ADMIN', null, false],
37
                ['ROLE_SUPER_USER', null, true],
38
                ['ROLE_DEV', null, false],
39
                ['ROLE_USER', null, false],
40
            ]);
41
42
        $helper = new SecurityHelper(
43
            $authChecker,
44
            $this->getTokenStorage(),
45
            $this->getActionLogRepository(),
46
            $this->getExtremeNotificationsHelper(),
47
            $this->getRouter(),
48
            'cookieName'
49
        );
50
51
        $this->assertSame(2, $helper->getLoggedInUserLevel());
52
    }
53
54
    public function testGetLoggedInUserLevelDefault()
55
    {
56
        $authChecker = $this->getAuthChecker();
57
        $authChecker->expects($this->atLeastOnce())
58
            ->method('isGranted');
59
60
        $helper = new SecurityHelper(
61
            $authChecker,
62
            $this->getTokenStorage(),
63
            $this->getActionLogRepository(),
64
            $this->getExtremeNotificationsHelper(),
65
            $this->getRouter(),
66
            'cookieName'
67
        );
68
69
        $this->assertSame(0, $helper->getLoggedInUserLevel());
70
    }
71
72
    public function testCheckNoPendingImpersonateReport()
73
    {
74
        $person = new Person();
75
76
        $repo = $this->getActionLogRepository();
77
        $repo->expects($this->once())
78
            ->method('countImpersonatonsWithoutReports')->with($person)
79
            ->willReturn(0);
80
81
        $helper = new SecurityHelper(
82
            $this->getAuthChecker(),
83
            $this->getTokenStorage(),
84
            $repo,
85
            $this->getExtremeNotificationsHelper(),
86
            $this->getRouter(),
87
            'cookieName'
88
        );
89
90
        $helper->checkPendingImpersonateReport($person);
91
    }
92
93
    public function testCheckPendingImpersonateReport()
94
    {
95
        $count = 2;
96
        $url = 'https://example.com';
97
        $person = new Person();
98
99
        $repo = $this->getActionLogRepository();
100
        $repo->expects($this->once())
101
            ->method('countImpersonatonsWithoutReports')
102
            ->willReturn($count);
103
104
        $router = $this->getRouter();
105
        $router->expects($this->once())
106
            ->method('generate')->with('lc_admin_impersonation_report_index')
107
            ->willReturn($url);
108
109
        $parameters = ['%url%' => $url, '%count%' => $count];
110
111
        $extremeNotifHelper = $this->getExtremeNotificationsHelper();
112
        $extremeNotifHelper->expects($this->once())
113
            ->method('addTransChoice')->with('admin.impersonation_report.pending.notification', $count, $parameters);
114
115
        $helper = new SecurityHelper(
116
            $this->getAuthChecker(),
117
            $this->getTokenStorage(),
118
            $repo,
119
            $extremeNotifHelper,
120
            $router,
121
            'cookieName'
122
        );
123
124
        $helper->checkPendingImpersonateReport($person);
125
    }
126
127
    public function testGetRoleLevel()
128
    {
129
        $helper = new SecurityHelper(
130
            $this->getAuthChecker(),
131
            $this->getTokenStorage(),
132
            $this->getActionLogRepository(),
133
            $this->getExtremeNotificationsHelper(),
134
            $this->getRouter(),
135
            'cookieName'
136
        );
137
138
        $roles = [
139
            'ROLE_SUPER_ADMIN' => 4,
140
            'ROLE_ADMIN' => 3,
141
            'ROLE_SUPER_USER' => 2,
142
            'ROLE_DEV' => 1,
143
            'ROLE_USER' => 0,
144
        ];
145
146
        foreach ($roles as $role => $expected) {
147
            $this->assertSame($expected, $helper->getRoleLevel($role));
148
        }
149
150
        $this->assertSame(4, $helper->getRoleLevel('OTHER_ROLE'));
151
    }
152
153
    public function testGetUser()
154
    {
155
        $person = new Person();
156
157
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
158
        $token->expects($this->once())->method('getUser')->willReturn($person);
159
160
        $tokenStorage = $this->getTokenStorage();
161
        $tokenStorage->expects($this->once())
162
            ->method('getToken')
163
            ->willReturn($token);
164
165
        $helper = new SecurityHelper(
166
            $this->getAuthChecker(),
167
            $tokenStorage,
168
            $this->getActionLogRepository(),
169
            $this->getExtremeNotificationsHelper(),
170
            $this->getRouter(),
171
            'cookieName'
172
        );
173
174
        $this->assertSame($person, $helper->getUser());
175
    }
176
177
    public function testGetUserNotPersonInterface()
178
    {
179
        $user = new User('username', 'password');
180
181
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
182
        $token->expects($this->once())->method('getUser')->willReturn($user);
183
184
        $tokenStorage = $this->getTokenStorage();
185
        $tokenStorage->expects($this->once())
186
            ->method('getToken')
187
            ->willReturn($token);
188
189
        $helper = new SecurityHelper(
190
            $this->getAuthChecker(),
191
            $tokenStorage,
192
            $this->getActionLogRepository(),
193
            $this->getExtremeNotificationsHelper(),
194
            $this->getRouter(),
195
            'cookieName'
196
        );
197
198
        $this->assertNull($helper->getUser());
199
    }
200
201
    public function testGetUserException()
202
    {
203
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
204
        $token->expects($this->once())->method('getUser')->willThrowException(new \RuntimeException());
205
206
        $tokenStorage = $this->getTokenStorage();
207
        $tokenStorage->expects($this->once())
208
            ->method('getToken')
209
            ->willReturn($token);
210
211
        $helper = new SecurityHelper(
212
            $this->getAuthChecker(),
213
            $tokenStorage,
214
            $this->getActionLogRepository(),
215
            $this->getExtremeNotificationsHelper(),
216
            $this->getRouter(),
217
            'cookieName'
218
        );
219
220
        $this->assertNull($helper->getUser());
221
    }
222
223
    public function testGetUserNoToken()
224
    {
225
        $tokenStorage = $this->getTokenStorage();
226
        $tokenStorage->expects($this->once())
227
            ->method('getToken')
228
            ->willReturn(null);
229
230
        $helper = new SecurityHelper(
231
            $this->getAuthChecker(),
232
            $tokenStorage,
233
            $this->getActionLogRepository(),
234
            $this->getExtremeNotificationsHelper(),
235
            $this->getRouter(),
236
            'cookieName'
237
        );
238
239
        $this->assertNull($helper->getUser());
240
    }
241
242
    public function testGetTargetPersonLevel()
243
    {
244
        $personLvl3 = new Person();
245
        $personLvl3->setRoles([
246
            'ROLE_DEV',
247
            'ROLE_ADMIN',
248
        ]);
249
250
        /** @var PersonInterface|\PHPUnit_Framework_MockObject_MockObject $personLvlDefault */
251
        $personLvlDefault = $this->getMock('LoginCidadao\CoreBundle\Model\PersonInterface');
252
        $personLvlDefault->expects($this->once())
253
            ->method('getRoles')
254
            ->willReturn(['OTHER_ROLE']);
255
256
        $helper = new SecurityHelper(
257
            $this->getAuthChecker(),
258
            $this->getTokenStorage(),
259
            $this->getActionLogRepository(),
260
            $this->getExtremeNotificationsHelper(),
261
            $this->getRouter(),
262
            'cookieName'
263
        );
264
265
        $this->assertSame(3, $helper->getTargetPersonLevel($personLvl3));
266
        $this->assertSame(0, $helper->getTargetPersonLevel($personLvlDefault));
267
    }
268
269
    public function testLogout()
270
    {
271
        $rememberMe = 'cookieName';
272
273
        /** @var SessionInterface|\PHPUnit_Framework_MockObject_MockObject $session */
274
        $session = $this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface');
275
        $session->expects($this->once())->method('invalidate');
276
277
        $request = new Request();
278
        $request->setSession($session);
279
280
        $headers = $this->getMock('Symfony\Component\HttpFoundation\ResponseHeaderBag');
281
        $headers->expects($this->once())->method('clearCookie')->with($rememberMe);
282
283
        $response = new Response();
284
        $response->headers = $headers;
0 ignored issues
show
Documentation Bug introduced by
It seems like $headers of type PHPUnit_Framework_MockObject_MockObject is incompatible with the declared type Symfony\Component\HttpFoundation\ResponseHeaderBag of property $headers.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
285
286
        $tokenStorage = $this->getTokenStorage();
287
        $tokenStorage->expects($this->once())->method('setToken')->with(null);
288
289
        $helper = new SecurityHelper(
290
            $this->getAuthChecker(),
291
            $tokenStorage,
292
            $this->getActionLogRepository(),
293
            $this->getExtremeNotificationsHelper(),
294
            $this->getRouter(),
295
            $rememberMe
296
        );
297
298
        $helper->logout($request, $response);
299
    }
300
301
    public function testIsGranted()
302
    {
303
        $attributes = ['THE_ROLE'];
304
        $object = new \stdClass();
305
306
        $authChecker = $this->getAuthChecker();
307
        $authChecker->expects($this->atLeastOnce())
308
            ->method('isGranted')->with($attributes, $object)
309
            ->willReturn(true);
310
311
        $helper = new SecurityHelper(
312
            $authChecker,
313
            $this->getTokenStorage(),
314
            $this->getActionLogRepository(),
315
            $this->getExtremeNotificationsHelper(),
316
            $this->getRouter(),
317
            'cookieName'
318
        );
319
320
        $this->assertTrue($helper->isGranted($attributes, $object));
321
    }
322
323
    public function testGetTokenRoles()
324
    {
325
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
326
        $token->expects($this->once())->method('getRoles')->willReturn([]);
327
328
        $tokenStorage = $this->getTokenStorage();
329
        $tokenStorage->expects($this->once())
330
            ->method('getToken')
331
            ->willReturn($token);
332
333
        $helper = new SecurityHelper(
334
            $this->getAuthChecker(),
335
            $tokenStorage,
336
            $this->getActionLogRepository(),
337
            $this->getExtremeNotificationsHelper(),
338
            $this->getRouter(),
339
            'cookieName'
340
        );
341
342
        $this->assertEmpty($helper->getTokenRoles());
343
    }
344
345
    public function testHasToken()
346
    {
347
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
348
349
        $tokenStorage = $this->getTokenStorage();
350
        $tokenStorage->expects($this->once())
351
            ->method('getToken')
352
            ->willReturn($token);
353
354
        $helper = new SecurityHelper(
355
            $this->getAuthChecker(),
356
            $tokenStorage,
357
            $this->getActionLogRepository(),
358
            $this->getExtremeNotificationsHelper(),
359
            $this->getRouter(),
360
            'cookieName'
361
        );
362
363
        $this->assertTrue($helper->hasToken());
364
    }
365
366
    public function testIsOAuthToken()
367
    {
368
        $token = $this->getMockBuilder('FOS\OAuthServerBundle\Security\Authentication\Token\OAuthToken')
369
            ->disableOriginalConstructor()->getMock();
370
371
        $tokenStorage = $this->getTokenStorage();
372
        $tokenStorage->expects($this->once())
373
            ->method('getToken')
374
            ->willReturn($token);
375
376
        $helper = new SecurityHelper(
377
            $this->getAuthChecker(),
378
            $tokenStorage,
379
            $this->getActionLogRepository(),
380
            $this->getExtremeNotificationsHelper(),
381
            $this->getRouter(),
382
            'cookieName'
383
        );
384
385
        $this->assertTrue($helper->isOAuthToken());
386
    }
387
388
    /**
389
     * @return AuthorizationCheckerInterface|\PHPUnit_Framework_MockObject_MockObject
390
     */
391
    private function getAuthChecker()
392
    {
393
        return $this->getMock('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface');
394
    }
395
396
    /**
397
     * @return TokenStorageInterface|\PHPUnit_Framework_MockObject_MockObject
398
     */
399
    private function getTokenStorage()
400
    {
401
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface');
402
    }
403
404
    /**
405
     * @return ActionLogRepository|\PHPUnit_Framework_MockObject_MockObject
406
     */
407
    private function getActionLogRepository()
408
    {
409
        return $this->getMockBuilder('LoginCidadao\APIBundle\Entity\ActionLogRepository')
410
            ->disableOriginalConstructor()->getMock();
411
    }
412
413
    /**
414
     * @return ExtremeNotificationsHelper|\PHPUnit_Framework_MockObject_MockObject
415
     */
416
    private function getExtremeNotificationsHelper()
417
    {
418
        return $this->getMockBuilder('LoginCidadao\CoreBundle\Helper\ExtremeNotificationsHelper')
419
            ->disableOriginalConstructor()->getMock();
420
    }
421
422
    /**
423
     * @return RouterInterface|\PHPUnit_Framework_MockObject_MockObject
424
     */
425
    private function getRouter()
426
    {
427
        return $this->getMock('Symfony\Component\Routing\RouterInterface');
428
    }
429
}
430