Files
laravel-manager/src/Concerns/HasManagerAccess.php
T
Matthijs Iriks 69ed8c742a
PR CI / ledger (pull_request) Successful in 4s
PR CI / flow (pull_request) Successful in 5s
PR CI / ui (pull_request) Successful in 17s
PR CI / test (lowest) (pull_request) Successful in 39s
PR CI / security (pull_request) Successful in 48s
PR CI / test (stable) (pull_request) Successful in 53s
PR CI / pr-ci (pull_request) Successful in 2s
PR CI / release-automerge (pull_request) Successful in 4s
Let the roles of the host decide next to the groups
2026-12-04 05:40:02 +01:00

74 lines
2.5 KiB
PHP

<?php
namespace IriksIT\Manager\Concerns;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permissions\Sources;
/**
* Put this on the User model of the host app (needs the Users module).
*
* A super admin may do everything of the manager. Everyone else may do what any of their
* groups allows, or (config `manager.permissions`) what the roles of the site say. `is_super_admin` is never fillable and no form sets it: only
* `manager:create-user` makes one. Keep it out of `$fillable` in the host model.
*/
trait HasManagerAccess
{
/** @return BelongsToMany<Group, $this> */
public function managerGroups(): BelongsToMany
{
return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id');
}
public function isManagerSuperAdmin(): bool
{
return (bool) $this->getAttribute('is_super_admin');
}
/**
* Everything this account may do in the manager.
*
* @return list<string>
*/
public function managerPermissions(): array
{
$registry = app(ModuleRegistry::class);
if ($this->isManagerSuperAdmin()) {
return $registry->permissionValues();
}
$fromGroups = Sources::usesGroups() ? $this->managerGroups->flatMap(fn (Group $group) => $group->allowed())->all() : [];
return $registry->complete([...$fromGroups, ...Sources::fromHost($this)]);
}
public function hasManagerPermission(string $permission): bool
{
return in_array($permission, $this->managerPermissions(), true);
}
/**
* Whether this account may do everything $other may. Someone who manages accounts only
* touches accounts that stay within their own rights; otherwise a new password for a
* mightier account would be a way up.
*/
public function managerOutranks(self $other): bool
{
if ($this->isManagerSuperAdmin()) {
return true;
}
return ! $other->isManagerSuperAdmin() && array_diff($other->managerPermissions(), $this->managerPermissions()) === [];
}
/** Whether this account may put someone in $group: only when the group gives nothing it lacks itself. */
public function managerMayGive(Group $group): bool
{
return $this->isManagerSuperAdmin() || array_diff($group->allowed(), $this->managerPermissions()) === [];
}
}