3 namespace BookStack\Auth;
5 use BookStack\Auth\Permissions\JointPermission;
6 use BookStack\Auth\Permissions\RolePermission;
7 use BookStack\Interfaces\Loggable;
9 use Illuminate\Database\Eloquent\Collection;
10 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
11 use Illuminate\Database\Eloquent\Relations\HasMany;
17 * @property string $display_name
18 * @property string $description
19 * @property string $external_auth_id
20 * @property string $system_name
21 * @property bool $mfa_enforced
23 class Role extends Model implements Loggable
25 protected $fillable = ['display_name', 'description', 'external_auth_id'];
28 * The roles that belong to the role.
30 public function users(): BelongsToMany
32 return $this->belongsToMany(User::class)->orderBy('name', 'asc');
36 * Get all related JointPermissions.
38 public function jointPermissions(): HasMany
40 return $this->hasMany(JointPermission::class);
44 * The RolePermissions that belong to the role.
46 public function permissions(): BelongsToMany
48 return $this->belongsToMany(RolePermission::class, 'permission_role', 'role_id', 'permission_id');
52 * Check if this role has a permission.
54 public function hasPermission(string $permissionName): bool
56 $permissions = $this->getRelationValue('permissions');
57 foreach ($permissions as $permission) {
58 if ($permission->getRawAttribute('name') === $permissionName) {
67 * Add a permission to this role.
69 public function attachPermission(RolePermission $permission)
71 $this->permissions()->attach($permission->id);
75 * Detach a single permission from this role.
77 public function detachPermission(RolePermission $permission)
79 $this->permissions()->detach([$permission->id]);
83 * Get the role of the specified display name.
85 public static function getRole(string $displayName): ?Role
87 return static::query()->where('display_name', '=', $displayName)->first();
91 * Get the role object for the specified system role.
93 public static function getSystemRole(string $systemName): ?Role
95 return static::query()->where('system_name', '=', $systemName)->first();
99 * Get all visible roles.
101 public static function visible(): Collection
103 return static::query()->where('hidden', '=', false)->orderBy('name')->get();
107 * Get the roles that can be restricted.
109 public static function restrictable(): Collection
111 return static::query()
112 ->where('system_name', '!=', 'admin')
113 ->orderBy('display_name', 'asc')
120 public function logDescriptor(): string
122 return "({$this->id}) {$this->display_name}";