diff --git a/src/Cms/AppUsers.php b/src/Cms/AppUsers.php index 23b8470dee..f2b63990e3 100644 --- a/src/Cms/AppUsers.php +++ b/src/Cms/AppUsers.php @@ -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 * diff --git a/tests/Cms/App/AppUsersTest.php b/tests/Cms/App/AppUsersTest.php index 5acaf187a2..0a296a86a5 100644 --- a/tests/Cms/App/AppUsersTest.php +++ b/tests/Cms/App/AppUsersTest.php @@ -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' => 'user@getkirby.com', + 'role' => 'editor' + ] + ] + ]); + + $app->auth()->setUser($app->user('user@getkirby.com')); + + $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' => 'user@getkirby.com', + 'role' => 'editor' + ] + ] + ]); + + $app->impersonate('user@getkirby.com'); + + $this->assertSame('editor', $app->role()->name()); + $this->assertNull($app->role(null, false)); + } + public function testUsersLoad() { $app = $this->app->clone([