forked from nette/security
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUser.authorization.phpt
More file actions
101 lines (72 loc) · 2.14 KB
/
Copy pathUser.authorization.phpt
File metadata and controls
101 lines (72 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
/**
* Test: Nette\Security\User authorization.
*/
declare(strict_types=1);
use Nette\Security\IIdentity;
use Nette\Security\Role;
use Nette\Security\SimpleIdentity;
use Tester\Assert;
require __DIR__ . '/../bootstrap.php';
require __DIR__ . '/MockUserStorage.php';
// Setup environment
$_COOKIE = [];
ob_start();
class Authenticator implements Nette\Security\Authenticator
{
public function authenticate(string $username, string $password): IIdentity
{
if ($username !== 'john') {
throw new Nette\Security\AuthenticationException('Unknown user', self::IdentityNotFound);
} elseif ($password !== 'xxx') {
throw new Nette\Security\AuthenticationException('Password not match', self::InvalidCredential);
} else {
return new SimpleIdentity('John Doe', ['admin', new TesterRole]);
}
}
}
class Authorizator implements Nette\Security\Authorizator
{
public function isAllowed($role = self::All, $resource = self::All, $privilege = self::All): bool
{
return $role === 'admin' && !str_contains($resource, 'jany');
}
}
class TesterRole implements Role
{
public function getRoleId(): string
{
return 'tester';
}
}
$user = new Nette\Security\User(new MockUserStorage);
// guest
Assert::false($user->isLoggedIn());
Assert::same(['guest'], $user->getRoles());
Assert::false($user->isInRole('admin'));
Assert::false($user->isInRole('tester'));
Assert::true($user->isInRole('guest'));
// authenticated
$handler = new Authenticator;
$user->setAuthenticator($handler);
// login as john
$user->login('john', 'xxx');
Assert::true($user->isLoggedIn());
Assert::equal(['admin', new TesterRole], $user->getRoles());
Assert::true($user->isInRole('admin'));
Assert::true($user->isInRole('tester'));
Assert::false($user->isInRole('guest'));
// authorization
Assert::exception(
fn() => $user->isAllowed('delete_file'),
Nette\InvalidStateException::class,
'Authorizator has not been set.',
);
$handler = new Authorizator;
$user->setAuthorizator($handler);
Assert::true($user->isAllowed('delete_file'));
Assert::false($user->isAllowed('sleep_with_jany'));
// log out
// logging out...
$user->logout(false);
Assert::false($user->isAllowed('delete_file'));