-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathAuthorizable.php
427 lines (343 loc) · 11 KB
/
Authorizable.php
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Shield\Authorization\Traits;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authorization\AuthorizationException;
use CodeIgniter\Shield\Exceptions\LogicException;
use CodeIgniter\Shield\Models\GroupModel;
use CodeIgniter\Shield\Models\PermissionModel;
trait Authorizable
{
protected ?array $groupCache = null;
protected ?array $permissionsCache = null;
/**
* Adds one or more groups to the current User.
*
* @return $this
*/
public function addGroup(string ...$groups): self
{
$this->populateGroups();
$groupCount = count($this->groupCache);
foreach ($groups as $group) {
$group = strtolower($group);
// don't allow dupes
if (in_array($group, $this->groupCache, true)) {
continue;
}
/** @var GroupModel $groupModel */
$groupModel = model(GroupModel::class);
// make sure it's a valid group
if (! $groupModel->isValidGroup($group)) {
throw AuthorizationException::forUnknownGroup($group);
}
$this->groupCache[] = $group;
}
// Only save the results if there's anything new.
if (count($this->groupCache) > $groupCount) {
$this->saveGroups();
}
return $this;
}
/**
* Removes one or more groups from the user.
*
* @return $this
*/
public function removeGroup(string ...$groups): self
{
$this->populateGroups();
foreach ($groups as &$group) {
$group = strtolower($group);
}
// Remove from local cache
$this->groupCache = array_diff($this->groupCache, $groups);
// Update the database.
$this->saveGroups();
return $this;
}
/**
* Given an array of groups, will update the database
* so only those groups are valid for this user, removing
* all groups not in this list.
*
* @return $this
*
* @throws AuthorizationException
*/
public function syncGroups(string ...$groups): self
{
$this->populateGroups();
/** @var GroupModel $groupModel */
$groupModel = model(GroupModel::class);
foreach ($groups as $group) {
if (! $groupModel->isValidGroup($group)) {
throw AuthorizationException::forUnknownGroup($group);
}
}
$this->groupCache = $groups;
$this->saveGroups();
return $this;
}
/**
* Set groups cache manually
*/
public function setGroupsCache(array $groups): void
{
$this->groupCache = $groups === [] ? null : $groups;
}
/**
* Set permissions cache manually
*/
public function setPermissionsCache(array $permissions): void
{
$this->permissionsCache = $permissions === [] ? null : $permissions;
}
/**
* Returns all groups this user is a part of.
*/
public function getGroups(): ?array
{
$this->populateGroups();
return $this->groupCache;
}
/**
* Returns all permissions this user has
* assigned directly to them.
*/
public function getPermissions(): ?array
{
$this->populatePermissions();
return $this->permissionsCache;
}
/**
* Adds one or more permissions to the current user.
*
* @return $this
*
* @throws AuthorizationException
*/
public function addPermission(string ...$permissions): self
{
$this->populatePermissions();
$configPermissions = $this->getConfigPermissions();
$permissionCount = count($this->permissionsCache);
foreach ($permissions as $permission) {
$permission = strtolower($permission);
// don't allow dupes
if (in_array($permission, $this->permissionsCache, true)) {
continue;
}
// make sure it's a valid group
if (! in_array($permission, $configPermissions, true)) {
throw AuthorizationException::forUnknownPermission($permission);
}
$this->permissionsCache[] = $permission;
}
// Only save the results if there's anything new.
if (count($this->permissionsCache) > $permissionCount) {
$this->savePermissions();
}
return $this;
}
/**
* Removes one or more permissions from the current user.
*
* @return $this
*/
public function removePermission(string ...$permissions): self
{
$this->populatePermissions();
foreach ($permissions as &$permission) {
$permission = strtolower($permission);
}
// Remove from local cache
$this->permissionsCache = array_diff($this->permissionsCache, $permissions);
// Update the database.
$this->savePermissions();
return $this;
}
/**
* Given an array of permissions, will update the database
* so only those permissions are valid for this user, removing
* all permissions not in this list.
*
* @return $this
*
* @throws AuthorizationException
*/
public function syncPermissions(string ...$permissions): self
{
$this->populatePermissions();
$configPermissions = $this->getConfigPermissions();
foreach ($permissions as $permission) {
if (! in_array($permission, $configPermissions, true)) {
throw AuthorizationException::forUnknownPermission($permission);
}
}
$this->permissionsCache = $permissions;
$this->savePermissions();
return $this;
}
/**
* Checks to see if the user has the permission set
* directly on themselves. This disregards any groups
* they are part of.
*/
public function hasPermission(string $permission): bool
{
$this->populatePermissions();
$permission = strtolower($permission);
return in_array($permission, $this->permissionsCache, true);
}
/**
* Checks user permissions and their group permissions
* to see if the user has a specific permission or group
* of permissions.
*
* @param string $permissions string(s) consisting of a scope and action, like `users.create`
*/
public function can(string ...$permissions): bool
{
// Get user's permissions and store in cache
$this->populatePermissions();
// Check the groups the user belongs to
$this->populateGroups();
// Get the group matrix
$matrix = setting('AuthGroups.matrix');
foreach ($permissions as $permission) {
// Permission must contain a scope and action
if (! str_contains($permission, '.')) {
throw new LogicException(
'A permission must be a string consisting of a scope and action, like `users.create`.'
. ' Invalid permission: ' . $permission,
);
}
$permission = strtolower($permission);
// Check user's permissions
if (in_array($permission, $this->permissionsCache, true)) {
return true;
}
if (count($this->groupCache) === 0) {
return false;
}
foreach ($this->groupCache as $group) {
// Check exact match
if (isset($matrix[$group]) && in_array($permission, $matrix[$group], true)) {
return true;
}
// Check wildcard match
$check = substr($permission, 0, strpos($permission, '.')) . '.*';
if (isset($matrix[$group]) && in_array($check, $matrix[$group], true)) {
return true;
}
}
}
return false;
}
/**
* Checks to see if the user is a member of one
* of the groups passed in.
*/
public function inGroup(string ...$groups): bool
{
$this->populateGroups();
foreach ($groups as $group) {
if (in_array(strtolower($group), $this->groupCache, true)) {
return true;
}
}
return false;
}
/**
* Used internally to populate the User groups
* so we hit the database as little as possible.
*/
private function populateGroups(): void
{
if (is_array($this->groupCache)) {
return;
}
/** @var GroupModel $groupModel */
$groupModel = model(GroupModel::class);
$this->groupCache = $groupModel->getForUser($this);
}
/**
* Used internally to populate the User permissions
* so we hit the database as little as possible.
*/
private function populatePermissions(): void
{
if (is_array($this->permissionsCache)) {
return;
}
/** @var PermissionModel $permissionModel */
$permissionModel = model(PermissionModel::class);
$this->permissionsCache = $permissionModel->getForUser($this);
}
/**
* Inserts or Updates the current groups.
*/
private function saveGroups(): void
{
/** @var GroupModel $model */
$model = model(GroupModel::class);
$cache = $this->groupCache;
$this->saveGroupsOrPermissions('group', $model, $cache);
}
/**
* Inserts or Updates either the current permissions.
*/
private function savePermissions(): void
{
/** @var PermissionModel $model */
$model = model(PermissionModel::class);
$cache = $this->permissionsCache;
$this->saveGroupsOrPermissions('permission', $model, $cache);
}
/**
* @phpstan-param 'group'|'permission' $type
* @param GroupModel|PermissionModel $model
*/
private function saveGroupsOrPermissions(string $type, $model, array $cache): void
{
$existing = $model->getForUser($this);
$new = array_diff($cache, $existing);
// Delete any not in the cache
if ($cache !== []) {
$model->deleteNotIn($this->id, $cache);
}
// Nothing in the cache? Then make sure
// we delete all from this user
else {
$model->deleteAll($this->id);
}
// Insert new ones
if ($new !== []) {
$inserts = [];
foreach ($new as $item) {
$inserts[] = [
'user_id' => $this->id,
$type => $item,
'created_at' => Time::now(),
];
}
$model->insertBatch($inserts);
}
}
/**
* @return list<string>
*/
private function getConfigPermissions(): array
{
return array_keys(setting('AuthGroups.permissions'));
}
}