Skip to content

Commit 187ed50

Browse files
authored
Allow using nested role config. (#157)
* Allow using nested role config. * Add test. * Add test.
1 parent 1518a82 commit 187ed50

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

docs/Authorization.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,9 @@ Multi words like `Super Admin` would be `super-admin` etc.
118118
### Single-role
119119

120120
When using the single-role-per-user model TinyAuth expects your Users model to
121-
contain an column named ``role_id``. If you prefer to use another column name
121+
contain a column named ``role_id``. If you prefer to use another column name
122122
simply specify it using the ``roleColumn`` configuration option.
123+
If it is a nested relationship of sort, you can use the dot notation to specify the path, e.g. `Role.id`.
123124

124125
The ``roleColumn`` option is also used on pivot table in a multi-role setup.
125126

src/Auth/AclTrait.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,16 @@ protected function _getUserRoles(ArrayAccess|array $user) {
524524
throw new CakeException('Invalid TinyAuth config, `roleColumn` config missing.');
525525
}
526526

527+
// Check if the roleColumn is a dot notation path
528+
if (str_contains($roleColumn, '.')) {
529+
$role = Hash::get($user, $roleColumn);
530+
if (!$role) {
531+
throw new CakeException(sprintf('Missing TinyAuth role id field (%s) in user session', 'Auth.User.' . $roleColumn));
532+
}
533+
534+
return $this->_mapped([$role]);
535+
}
536+
527537
if (!array_key_exists($roleColumn, (array)$user)) {
528538
throw new CakeException(sprintf('Missing TinyAuth role id field (%s) in user session', 'Auth.User.' . $this->getConfig('roleColumn')));
529539
}

tests/TestCase/Controller/Component/AuthUserComponentTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,4 +490,18 @@ public function testHasRoles() {
490490
$this->assertTrue($this->AuthUser->hasRoles([1, 3, 5], false, [1, 3, 5]));
491491
}
492492

493+
/**
494+
* @return void
495+
*/
496+
public function testHasRoleHash() {
497+
$this->AuthUser->setConfig('roleColumn', 'Role.id');
498+
499+
$user = ['id' => '1', 'Role' => ['id' => '1']];
500+
$identity = new Identity($user);
501+
$this->AuthUser->getController()->setRequest($this->AuthUser->getController()->getRequest()->withAttribute('identity', $identity));
502+
503+
$this->assertTrue($this->AuthUser->hasRole(1));
504+
$this->assertFalse($this->AuthUser->hasRole(3));
505+
}
506+
493507
}

0 commit comments

Comments
 (0)