Skip to content

Commit

Permalink
New $app->role() method
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasbestle committed Dec 17, 2024
1 parent 3832c97 commit 023eace
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Cms/AppUsers.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,25 @@ public function roles(): Roles
return $this->roles ??= Roles::load($this->root('roles'));
}

/**
* Returns a specific user role by id
* or the role of the current user if no id is given
*
* @param bool $allowImpersonation If set to false, only the role of the
* actually logged in user will be returned
* (when `$id` is passed as `null`)
*/
public function role(
string|null $id = null,
bool $allowImpersonation = true
): Role|null {
if ($id !== null) {
return $this->roles()->find($id);
}

return $this->user(null, $allowImpersonation)?->role();
}

/**
* Set the currently active user id
*
Expand Down
61 changes: 61 additions & 0 deletions tests/Cms/App/AppUsersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,67 @@ public function testRolesLoad()
$this->assertSame('editor', $app->roles()->last()->name());
}

public function testRoleManual()
{
$app = new App([
'roles' => [
[
'name' => 'editor',
'title' => 'Editor'
]
]
]);

$this->assertSame('editor', $app->role('editor')->name());
$this->assertNull($app->role('something'));
}

public function testRoleFromUser()
{
$app = new App([
'roles' => [
[
'name' => 'editor',
'title' => 'Editor'
]
],
'users' => [
[
'email' => '[email protected]',
'role' => 'editor'
]
]
]);

$app->auth()->setUser($app->user('[email protected]'));

$this->assertSame('editor', $app->role()->name());
$this->assertSame('editor', $app->role(null, false)->name());
}

public function testRoleFromImpersonatedUser()
{
$app = new App([
'roles' => [
[
'name' => 'editor',
'title' => 'Editor'
]
],
'users' => [
[
'email' => '[email protected]',
'role' => 'editor'
]
]
]);

$app->impersonate('[email protected]');

$this->assertSame('editor', $app->role()->name());
$this->assertNull($app->role(null, false));
}

public function testUsersLoad()
{
$app = $this->app->clone([
Expand Down

0 comments on commit 023eace

Please sign in to comment.