-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathAclTrait.php
More file actions
653 lines (554 loc) · 16.3 KB
/
Copy pathAclTrait.php
File metadata and controls
653 lines (554 loc) · 16.3 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
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
<?php
namespace TinyAuth\Auth;
use ArrayAccess;
use BackedEnum;
use Cake\Core\Configure;
use Cake\Core\Exception\CakeException;
use Cake\Database\Type\EnumLabelInterface;
use Cake\Datasource\ResultSetInterface;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
use Cake\Utility\Inflector;
use InvalidArgumentException;
use RuntimeException;
use TinyAuth\Auth\AclAdapter\AclAdapterInterface;
use TinyAuth\Utility\Cache;
use TinyAuth\Utility\Utility;
trait AclTrait {
/**
* @var array|null
*/
protected $_acl;
/**
* @var array<int>|null
*/
protected $_roles;
/**
* @var array<string>|null
*/
protected $_prefixMap;
/**
* @var array|null
*/
protected $_userRoles;
/**
* @var \TinyAuth\Auth\AclAdapter\AclAdapterInterface|null
*/
protected $_aclAdapter;
/**
* @var array|null
*/
protected $auth;
/**
* Finds the authorization adapter to use for this request.
*
* @param string $adapter Acl adapter to load.
* @throws \Cake\Core\Exception\CakeException
* @throws \InvalidArgumentException
* @return \TinyAuth\Auth\AclAdapter\AclAdapterInterface
*/
protected function _loadAclAdapter($adapter) {
if ($this->_aclAdapter !== null) {
return $this->_aclAdapter;
}
if (!class_exists($adapter)) {
throw new CakeException(sprintf('The Acl Adapter class "%s" was not found.', $adapter));
}
$adapterInstance = new $adapter();
if (!($adapterInstance instanceof AclAdapterInterface)) {
throw new InvalidArgumentException(sprintf(
'TinyAuth Acl adapters have to implement %s.',
AclAdapterInterface::class,
));
}
$this->_aclAdapter = $adapterInstance;
return $adapterInstance;
}
/**
* Checks the URL to the role(s).
*
* Allows single or multi role based authorization
*
* @param \ArrayAccess|array<string, mixed> $user User data
* @param array<string, mixed> $params Request params
* @throws \Cake\Core\Exception\CakeException
* @return bool Success
*/
protected function _checkUser(ArrayAccess|array $user, array $params): bool {
if ($this->getConfig('includeAuthentication') && $this->_isPublic($params)) {
return true;
}
if (!$user) {
return false;
}
if ($this->getConfig('superAdmin')) {
$superAdminColumn = $this->getConfig('superAdminColumn');
if (!$superAdminColumn) {
$superAdminColumn = $this->getConfig('idColumn');
}
if (!isset($user[$superAdminColumn])) {
throw new CakeException('Missing super admin column `' . $superAdminColumn . '` in user table');
}
if ($user[$superAdminColumn] === $this->getConfig('superAdmin')) {
return true;
}
}
// Give any logged-in user access to ALL actions when `allowLoggedIn` is
// enabled except when the `protectedPrefix` is being used.
if ($this->getConfig('allowLoggedIn')) {
if (empty($params['prefix'])) {
return true;
}
$protectedPrefixes = (array)$this->getConfig('protectedPrefix');
if (!$this->_isProtectedPrefix($params['prefix'], $protectedPrefixes)) {
return true;
}
}
$userRoles = $this->_getUserRoles($user);
return $this->_check($userRoles, $params);
}
/**
* @param string $prefix
* @param array<string> $protectedPrefixes
*
* @return bool
*/
protected function _isProtectedPrefix($prefix, array $protectedPrefixes) {
foreach ($protectedPrefixes as $protectedPrefix) {
if ($prefix === $protectedPrefix || strpos($prefix, $protectedPrefix . '/') === 0) {
return true;
}
}
return false;
}
/**
* @param array<string, int|string> $userRoles
* @param array $params
*
* @return bool
*/
protected function _check(array $userRoles, array $params) {
// Allow access to all prefixed actions for users belonging to
// the specified role that matches the prefix.
$prefixMap = $this->getConfig('authorizeByPrefix');
if (!empty($params['prefix']) && $prefixMap) {
$roles = $this->_getAvailableRoles();
$prefixMap = $this->_prefixMap($roles);
if ($prefixMap && $this->_isAuthorizedByPrefix($params['prefix'], $prefixMap, $userRoles, $roles)) {
return true;
}
}
// Allow logged in super admins access to all resources
if ($this->getConfig('superAdminRole')) {
foreach ($userRoles as $userRole) {
if ($userRole === $this->getConfig('superAdminRole')) {
return true;
}
}
}
if ($this->_acl === null) {
$this->_acl = $this->_getAcl($this->getConfig('aclFilePath'));
}
$iniKey = $this->_constructIniKey($params);
if (empty($this->_acl[$iniKey])) {
return false;
}
$action = $params['action'];
if (!empty($this->_acl[$iniKey]['deny'][$action])) {
$matchArray = $this->_acl[$iniKey]['deny'][$action];
foreach ($userRoles as $userRole) {
if (in_array($userRole, $matchArray, true)) {
return false;
}
}
}
// Allow access if user has a role with wildcard access to the resource
if (isset($this->_acl[$iniKey]['allow']['*'])) {
$matchArray = $this->_acl[$iniKey]['allow']['*'];
foreach ($userRoles as $userRole) {
if (in_array($userRole, $matchArray, true)) {
return true;
}
}
}
// Allow access if user has been granted access to the specific resource
if (array_key_exists($action, $this->_acl[$iniKey]['allow']) && !empty($this->_acl[$iniKey]['allow'][$action])) {
$matchArray = $this->_acl[$iniKey]['allow'][$action];
foreach ($userRoles as $userRole) {
if (in_array($userRole, $matchArray, true)) {
return true;
}
}
}
return false;
}
/**
* @param array $roles
* @return array<string>
*/
protected function _prefixMap(array $roles): array {
if ($this->_prefixMap !== null) {
return $this->_prefixMap;
}
/** @var array<string>|bool $prefixMap */
$prefixMap = $this->getConfig('authorizeByPrefix');
if (!$prefixMap) {
return [];
}
if ($prefixMap === true) {
$prefixMap = $this->_prefixesFromRoles($roles);
} else {
$prefixMap = $this->_normalizePrefixes($prefixMap);
}
$this->_prefixMap = $prefixMap;
return $this->_prefixMap;
}
/**
* Gets the [PrefixName => roleName] pairs from existing roles.
*
* @param array $roles
*
* @return array<string>
*/
protected function _prefixesFromRoles(array $roles) {
$names = array_keys($roles);
$prefixMap = [];
foreach ($names as $name) {
$prefix = Inflector::camelize(Inflector::underscore($name));
$prefixMap[$prefix] = $name;
}
return $prefixMap;
}
/**
* @param string $prefix
* @param array<string> $prefixMap
* @param array<string, int|string> $userRoles
* @param array<int> $availableRoles
*
* @return bool
*/
protected function _isAuthorizedByPrefix($prefix, array $prefixMap, array $userRoles, array $availableRoles) {
if (!$userRoles || !$prefixMap || !$availableRoles) {
return false;
}
if (empty($prefixMap[$prefix])) {
return false;
}
$prefixRoleSlugs = (array)$prefixMap[$prefix];
foreach ($prefixRoleSlugs as $prefixRoleSlug) {
$role = $availableRoles[$prefixRoleSlug] ?? null;
if ($role && in_array($role, $userRoles, true)) {
return true;
}
}
return false;
}
/**
* Can be [PrefixOne, PrefixTwo => roleOne, PrefixTwo => [roleOne, roleTwo]]
*
* @param array<string> $prefixes
*
* @return array<string, mixed>
*/
protected function _normalizePrefixes(array $prefixes) {
$normalized = [];
foreach ($prefixes as $prefix => $role) {
if (is_int($prefix)) {
$prefix = $role;
$role = Inflector::dasherize(Inflector::underscore($role));
}
$normalized[$prefix] = $role;
}
return $normalized;
}
/**
* @param array $params
*
* @return bool
*/
protected function _isPublic(array $params) {
$authentication = $this->_getAuth();
foreach ($authentication as $rule) {
if ($params['plugin'] && $params['plugin'] !== $rule['plugin']) {
continue;
}
if (!empty($params['prefix']) && $params['prefix'] !== $rule['prefix']) {
continue;
}
if ($params['controller'] !== $rule['controller']) {
continue;
}
$action = $params['action'];
if (!empty($rule['deny']) && in_array($action, $rule['deny'], true)) {
return false;
}
if (in_array('*', $rule['allow'], true)) {
return true;
}
return in_array($params['action'], $rule['allow'], true);
}
return false;
}
/**
* Hack to get the auth data here for hasAccess().
* We re-use the cached data for performance reasons.
*
* @throws \Cake\Core\Exception\CakeException
* @return array
*/
protected function _getAuth() {
if ($this->auth) {
return $this->auth;
}
$authAllow = $this->_getAllow();
$this->auth = $authAllow;
return $authAllow;
}
/**
* Parses INI file and returns the allowed roles per action.
*
* Uses cache for maximum performance.
* Improved speed by several actions before caching:
* - Resolves role slugs to their primary key / identifier
* - Resolves wildcards to their verbose translation
*
* @param array|string|null $path
* @return array
*/
protected function _getAcl($path = null) {
if ($this->getConfig('autoClearCache') && Configure::read('debug')) {
Cache::clear(Cache::KEY_ACL);
}
$acl = Cache::read(Cache::KEY_ACL);
if ($acl !== null) {
return $acl;
}
if ($path === null) {
$path = $this->getConfig('aclFilePath');
}
$config = $this->getConfig();
$config['filePath'] = $path;
$config['file'] = $config['aclFile'];
unset($config['aclFilePath']);
unset($config['aclFile']);
$acl = $this->_loadAclAdapter($config['aclAdapter'])->getAcl($this->_getAvailableRoles(), $config);
Cache::write(Cache::KEY_ACL, $acl);
return $acl;
}
/**
* Returns the found INI file(s) as an array.
*
* @param array|string|null $paths Paths to look for INI files.
* @param string $file INI file name.
* @return array List with all found files.
*/
protected function _parseFiles($paths, $file) {
return Utility::parseFiles($paths, $file);
}
/**
* Deconstructs an ACL INI section key into a named array with ACL parts.
*
* @param string $key INI section key as found in acl.ini
* @return array<string, mixed> Array with named keys for controller, plugin and prefix
*/
protected function _deconstructIniKey($key) {
return Utility::deconstructIniKey($key);
}
/**
* Constructs an ACL INI section key from a given Request.
*
* @param array $params The request params
* @return string Hash with named keys for controller, plugin and prefix
*/
protected function _constructIniKey($params) {
$res = $params['controller'];
if (!empty($params['prefix'])) {
$res = $params['prefix'] . "/$res";
}
if (!empty($params['plugin'])) {
$res = $params['plugin'] . ".$res";
}
return $res;
}
/**
* Returns a list of all available roles.
*
* Will look for a roles array in
* Configure first, tries database roles table next.
*
* @throws \Cake\Core\Exception\CakeException
* @return array<string, int> List with all available roles
*/
protected function _getAvailableRoles() {
if ($this->_roles !== null) {
return $this->_roles;
}
$rolesTableKey = $this->getConfig('rolesTable');
if (!$rolesTableKey) {
throw new CakeException('Invalid/missing rolesTable config');
}
$roles = Configure::read($rolesTableKey);
if (is_array($roles)) {
if ($this->getConfig('superAdminRole')) {
$key = $this->getConfig('superAdmin') ?: 'superadmin';
$roles[$key] = $this->getConfig('superAdminRole');
}
if (!$roles) {
throw new CakeException('Invalid roles config: No roles found in config.');
}
return $roles;
}
$roles = $this->_getRolesFromDb($rolesTableKey);
if ($this->getConfig('superAdminRole')) {
$key = $this->getConfig('superAdmin') ?: 'superadmin';
/** @var int $value */
$value = $this->getConfig('superAdminRole');
$roles[$key] = $value;
}
if (count($roles) < 1) {
throw new CakeException('Invalid TinyAuth role setup (roles table `' . $rolesTableKey . '` has no roles)');
}
$this->_roles = $roles;
return $roles;
}
/**
* @param string $rolesTableKey
*
* @throws \Cake\Core\Exception\CakeException
*
* @return array<int>
*/
protected function _getRolesFromDb(string $rolesTableKey): array {
try {
$rolesTable = TableRegistry::getTableLocator()->get($rolesTableKey);
$result = $rolesTable->find()->formatResults(function (ResultSetInterface $results) {
return $results->combine($this->getConfig('aliasColumn'), 'id');
});
} catch (RuntimeException $e) {
throw new CakeException('Invalid roles config: DB table `' . $rolesTableKey . '` cannot be found/accessed (`' . $e->getMessage() . '`).', null, $e);
}
/** @var array<int> */
return $result->toArray();
}
/**
* Returns a list of all roles belonging to the authenticated user.
*
* Lookup in the following order:
* - single role id using the roleColumn in single-role mode
* - direct lookup in the pivot table (to support both Configure and Model
* in multi-role mode)
*
* @param \ArrayAccess|array $user The user to get the roles for
* @return array<string, int|string> List with all role ids belonging to the user
*/
protected function _getUserRoles(ArrayAccess|array $user) {
// Single-role from session
if (!$this->getConfig('multiRole')) {
$roleColumn = $this->getConfig('roleColumn');
if (!$roleColumn) {
throw new CakeException('Invalid TinyAuth config, `roleColumn` config missing.');
}
// Check if the roleColumn is a dot notation path
if (str_contains($roleColumn, '.')) {
$role = Hash::get($user, $roleColumn);
if (!$role) {
throw new CakeException(sprintf('Missing TinyAuth role id field (%s) in user session', 'Auth.User.' . $roleColumn));
}
return $this->_mapped([$role]);
}
if (!array_key_exists($roleColumn, (array)$user)) {
throw new CakeException(sprintf('Missing TinyAuth role id field (%s) in user session', 'Auth.User.' . $this->getConfig('roleColumn')));
}
if (!isset($user[$this->getConfig('roleColumn')])) {
return [];
}
$role = $user[$this->getConfig('roleColumn')];
return $this->_mapped([$role]);
}
// Multi-role from session
if (isset($user[$this->getConfig('rolesTable')])) {
$userRoles = $user[$this->getConfig('rolesTable')];
if (isset($userRoles[0]['id'])) {
$userRoles = Hash::extract($userRoles, '{n}.id');
}
return $this->_mapped((array)$userRoles);
}
// Multi-role from session via pivot table
$pivotTableName = $this->_pivotTableName();
if (isset($user[$pivotTableName])) {
$userRoles = $user[$pivotTableName];
if (isset($userRoles[0][$this->getConfig('roleColumn')])) {
$userRoles = Hash::extract($userRoles, '{n}.' . $this->getConfig('roleColumn'));
}
return $this->_mapped((array)$userRoles);
}
// Multi-role from DB: load the pivot table
$roles = $this->_getRolesFromJunction($pivotTableName, $user[$this->getConfig('idColumn')]);
if (!$roles) {
return [];
}
return $this->_mapped($roles);
}
/**
* @return string
*/
protected function _pivotTableName() {
$pivotTableName = $this->getConfig('pivotTable');
if (!$pivotTableName) {
[, $rolesTableName] = pluginSplit($this->getConfig('rolesTable'));
[, $usersTableName] = pluginSplit($this->getConfig('usersTable'));
$tables = [
$usersTableName,
$rolesTableName,
];
asort($tables);
$pivotTableName = implode('', $tables);
}
return $pivotTableName;
}
/**
* @param string $pivotTableName
* @param int $id User ID
* @return array
*/
protected function _getRolesFromJunction($pivotTableName, $id) {
if (isset($this->_userRoles[$id])) {
return $this->_userRoles[$id];
}
$pivotTable = TableRegistry::getTableLocator()->get($pivotTableName);
$roleColumn = $this->getConfig('roleColumn');
$roles = $pivotTable->find()
->select($roleColumn)
->where([$this->getConfig('userColumn') => $id])
->all()
->extract($roleColumn)
->toArray();
$this->_userRoles[$id] = $roles;
return $roles;
}
/**
* Returns current roles as [alias => id] pairs.
*
* @param array<int|string|\BackedEnum> $roles
* @return array<string, int|string>
*/
protected function _mapped(array $roles) {
$availableRoles = $this->_getAvailableRoles();
$array = [];
foreach ($roles as $role) {
if ($role instanceof BackedEnum) {
$alias = $role instanceof EnumLabelInterface ? $role->label() : $role->name;
$value = $role->value;
$array[$alias] = $value;
continue;
}
$alias = array_keys($availableRoles, $role);
$alias = array_shift($alias);
if (!$alias || !is_string($alias)) {
continue;
}
$array[$alias] = $role;
}
return $array;
}
}