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
22 * @property Collection $users
24 class Role extends Model implements Loggable
26 protected $fillable = ['display_name', 'description', 'external_auth_id'];
29 * The roles that belong to the role.
31 public function users(): BelongsToMany
33 return $this->belongsToMany(User::class)->orderBy('name', 'asc');
37 * Get all related JointPermissions.
39 public function jointPermissions(): HasMany
41 return $this->hasMany(JointPermission::class);
45 * The RolePermissions that belong to the role.
47 public function permissions(): BelongsToMany
49 return $this->belongsToMany(RolePermission::class, 'permission_role', 'role_id', 'permission_id');
53 * Check if this role has a permission.
55 public function hasPermission(string $permissionName): bool
57 $permissions = $this->getRelationValue('permissions');
58 foreach ($permissions as $permission) {
59 if ($permission->getRawAttribute('name') === $permissionName) {
68 * Add a permission to this role.
70 public function attachPermission(RolePermission $permission)
72 $this->permissions()->attach($permission->id);
76 * Detach a single permission from this role.
78 public function detachPermission(RolePermission $permission)
80 $this->permissions()->detach([$permission->id]);
84 * Get the role of the specified display name.
86 public static function getRole(string $displayName): ?Role
88 return static::query()->where('display_name', '=', $displayName)->first();
92 * Get the role object for the specified system role.
94 public static function getSystemRole(string $systemName): ?Role
96 return static::query()->where('system_name', '=', $systemName)->first();
100 * Get all visible roles.
102 public static function visible(): Collection
104 return static::query()->where('hidden', '=', false)->orderBy('name')->get();
108 * Get the roles that can be restricted.
110 public static function restrictable(): Collection
112 return static::query()
113 ->where('system_name', '!=', 'admin')
114 ->orderBy('display_name', 'asc')
121 public function logDescriptor(): string
123 return "({$this->id}) {$this->display_name}";