3 namespace BookStack\Auth;
5 use BookStack\Auth\Permissions\EntityPermission;
6 use BookStack\Auth\Permissions\JointPermission;
7 use BookStack\Auth\Permissions\RolePermission;
8 use BookStack\Interfaces\Loggable;
10 use Illuminate\Database\Eloquent\Collection;
11 use Illuminate\Database\Eloquent\Factories\HasFactory;
12 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
13 use Illuminate\Database\Eloquent\Relations\HasMany;
19 * @property string $display_name
20 * @property string $description
21 * @property string $external_auth_id
22 * @property string $system_name
23 * @property bool $mfa_enforced
24 * @property Collection $users
26 class Role extends Model implements Loggable
30 protected $fillable = ['display_name', 'description', 'external_auth_id'];
32 protected $hidden = ['pivot'];
35 * The roles that belong to the role.
37 public function users(): BelongsToMany
39 return $this->belongsToMany(User::class)->orderBy('name', 'asc');
43 * Get all related JointPermissions.
45 public function jointPermissions(): HasMany
47 return $this->hasMany(JointPermission::class);
51 * The RolePermissions that belong to the role.
53 public function permissions(): BelongsToMany
55 return $this->belongsToMany(RolePermission::class, 'permission_role', 'role_id', 'permission_id');
59 * Get the entity permissions assigned to this role.
61 public function entityPermissions(): HasMany
63 return $this->hasMany(EntityPermission::class);
67 * Check if this role has a permission.
69 public function hasPermission(string $permissionName): bool
71 $permissions = $this->getRelationValue('permissions');
72 foreach ($permissions as $permission) {
73 if ($permission->getRawAttribute('name') === $permissionName) {
82 * Add a permission to this role.
84 public function attachPermission(RolePermission $permission)
86 $this->permissions()->attach($permission->id);
90 * Detach a single permission from this role.
92 public function detachPermission(RolePermission $permission)
94 $this->permissions()->detach([$permission->id]);
98 * Get the role of the specified display name.
100 public static function getRole(string $displayName): ?self
102 return static::query()->where('display_name', '=', $displayName)->first();
106 * Get the role object for the specified system role.
108 public static function getSystemRole(string $systemName): ?self
110 return static::query()->where('system_name', '=', $systemName)->first();
114 * Get all visible roles.
116 public static function visible(): Collection
118 return static::query()->where('hidden', '=', false)->orderBy('name')->get();
124 public function logDescriptor(): string
126 return "({$this->id}) {$this->display_name}";