1 <?php namespace BookStack\Auth;
3 use BookStack\Auth\Permissions\JointPermission;
4 use BookStack\Auth\Permissions\RolePermission;
5 use BookStack\Interfaces\Loggable;
7 use Illuminate\Database\Eloquent\Collection;
8 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
9 use Illuminate\Database\Eloquent\Relations\HasMany;
14 * @property string $display_name
15 * @property string $description
16 * @property string $external_auth_id
17 * @property string $system_name
19 class Role extends Model implements Loggable
22 protected $fillable = ['display_name', 'description', 'external_auth_id'];
25 * The roles that belong to the role.
27 public function users(): BelongsToMany
29 return $this->belongsToMany(User::class)->orderBy('name', 'asc');
33 * Get all related JointPermissions.
35 public function jointPermissions(): HasMany
37 return $this->hasMany(JointPermission::class);
41 * The RolePermissions that belong to the role.
43 public function permissions(): BelongsToMany
45 return $this->belongsToMany(RolePermission::class, 'permission_role', 'role_id', 'permission_id');
49 * Check if this role has a permission.
51 public function hasPermission(string $permissionName): bool
53 $permissions = $this->getRelationValue('permissions');
54 foreach ($permissions as $permission) {
55 if ($permission->getRawAttribute('name') === $permissionName) {
63 * Add a permission to this role.
65 public function attachPermission(RolePermission $permission)
67 $this->permissions()->attach($permission->id);
71 * Detach a single permission from this role.
73 public function detachPermission(RolePermission $permission)
75 $this->permissions()->detach([$permission->id]);
79 * Get the role of the specified display name.
81 public static function getRole(string $displayName): ?Role
83 return static::query()->where('display_name', '=', $displayName)->first();
87 * Get the role object for the specified system role.
89 public static function getSystemRole(string $systemName): ?Role
91 return static::query()->where('system_name', '=', $systemName)->first();
95 * Get all visible roles
97 public static function visible(): Collection
99 return static::query()->where('hidden', '=', false)->orderBy('name')->get();
103 * Get the roles that can be restricted.
105 public static function restrictable(): Collection
107 return static::query()->where('system_name', '!=', 'admin')->get();
113 public function logDescriptor(): string
115 return "({$this->id}) {$this->display_name}";