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\Factories\HasFactory;
11 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
12 use Illuminate\Database\Eloquent\Relations\HasMany;
18 * @property string $display_name
19 * @property string $description
20 * @property string $external_auth_id
21 * @property string $system_name
22 * @property bool $mfa_enforced
23 * @property Collection $users
25 class Role extends Model implements Loggable
29 protected $fillable = ['display_name', 'description', 'external_auth_id'];
31 protected $hidden = ['pivot'];
34 * The roles that belong to the role.
36 public function users(): BelongsToMany
38 return $this->belongsToMany(User::class)->orderBy('name', 'asc');
42 * Get all related JointPermissions.
44 public function jointPermissions(): HasMany
46 return $this->hasMany(JointPermission::class);
50 * The RolePermissions that belong to the role.
52 public function permissions(): BelongsToMany
54 return $this->belongsToMany(RolePermission::class, 'permission_role', 'role_id', 'permission_id');
58 * Check if this role has a permission.
60 public function hasPermission(string $permissionName): bool
62 $permissions = $this->getRelationValue('permissions');
63 foreach ($permissions as $permission) {
64 if ($permission->getRawAttribute('name') === $permissionName) {
73 * Add a permission to this role.
75 public function attachPermission(RolePermission $permission)
77 $this->permissions()->attach($permission->id);
81 * Detach a single permission from this role.
83 public function detachPermission(RolePermission $permission)
85 $this->permissions()->detach([$permission->id]);
89 * Get the role of the specified display name.
91 public static function getRole(string $displayName): ?self
93 return static::query()->where('display_name', '=', $displayName)->first();
97 * Get the role object for the specified system role.
99 public static function getSystemRole(string $systemName): ?self
101 return static::query()->where('system_name', '=', $systemName)->first();
105 * Get all visible roles.
107 public static function visible(): Collection
109 return static::query()->where('hidden', '=', false)->orderBy('name')->get();
113 * Get the roles that can be restricted.
115 public static function restrictable(): Collection
117 return static::query()
118 ->where('system_name', '!=', 'admin')
119 ->orderBy('display_name', 'asc')
126 public function logDescriptor(): string
128 return "({$this->id}) {$this->display_name}";