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', 'mfa_enforced'];
32 protected $hidden = ['pivot'];
35 'mfa_enforced' => 'boolean',
39 * The roles that belong to the role.
41 public function users(): BelongsToMany
43 return $this->belongsToMany(User::class)->orderBy('name', 'asc');
47 * Get all related JointPermissions.
49 public function jointPermissions(): HasMany
51 return $this->hasMany(JointPermission::class);
55 * The RolePermissions that belong to the role.
57 public function permissions(): BelongsToMany
59 return $this->belongsToMany(RolePermission::class, 'permission_role', 'role_id', 'permission_id');
63 * Get the entity permissions assigned to this role.
65 public function entityPermissions(): HasMany
67 return $this->hasMany(EntityPermission::class);
71 * Check if this role has a permission.
73 public function hasPermission(string $permissionName): bool
75 $permissions = $this->getRelationValue('permissions');
76 foreach ($permissions as $permission) {
77 if ($permission->getRawAttribute('name') === $permissionName) {
86 * Add a permission to this role.
88 public function attachPermission(RolePermission $permission)
90 $this->permissions()->attach($permission->id);
94 * Detach a single permission from this role.
96 public function detachPermission(RolePermission $permission)
98 $this->permissions()->detach([$permission->id]);
102 * Get the role of the specified display name.
104 public static function getRole(string $displayName): ?self
106 return static::query()->where('display_name', '=', $displayName)->first();
110 * Get the role object for the specified system role.
112 public static function getSystemRole(string $systemName): ?self
114 return static::query()->where('system_name', '=', $systemName)->first();
120 public function logDescriptor(): string
122 return "({$this->id}) {$this->display_name}";