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'];
32 * The roles that belong to the role.
34 public function users(): BelongsToMany
36 return $this->belongsToMany(User::class)->orderBy('name', 'asc');
40 * Get all related JointPermissions.
42 public function jointPermissions(): HasMany
44 return $this->hasMany(JointPermission::class);
48 * The RolePermissions that belong to the role.
50 public function permissions(): BelongsToMany
52 return $this->belongsToMany(RolePermission::class, 'permission_role', 'role_id', 'permission_id');
56 * Check if this role has a permission.
58 public function hasPermission(string $permissionName): bool
60 $permissions = $this->getRelationValue('permissions');
61 foreach ($permissions as $permission) {
62 if ($permission->getRawAttribute('name') === $permissionName) {
71 * Add a permission to this role.
73 public function attachPermission(RolePermission $permission)
75 $this->permissions()->attach($permission->id);
79 * Detach a single permission from this role.
81 public function detachPermission(RolePermission $permission)
83 $this->permissions()->detach([$permission->id]);
87 * Get the role of the specified display name.
89 public static function getRole(string $displayName): ?self
91 return static::query()->where('display_name', '=', $displayName)->first();
95 * Get the role object for the specified system role.
97 public static function getSystemRole(string $systemName): ?self
99 return static::query()->where('system_name', '=', $systemName)->first();
103 * Get all visible roles.
105 public static function visible(): Collection
107 return static::query()->where('hidden', '=', false)->orderBy('name')->get();
111 * Get the roles that can be restricted.
113 public static function restrictable(): Collection
115 return static::query()
116 ->where('system_name', '!=', 'admin')
117 ->orderBy('display_name', 'asc')
124 public function logDescriptor(): string
126 return "({$this->id}) {$this->display_name}";