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