- added a ImmuatableId field in manage roles - Generate ImmutableId using user Id if not available
70 lines
1.8 KiB
PHP
70 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
|
use Spatie\Activitylog\Support\LogOptions;
|
|
use Spatie\Permission\Models\{Permission, Role as SpatieRole};
|
|
|
|
/**
|
|
* @property int $priority
|
|
* @property AppRole $pivot
|
|
* @property ConnectedApp $apps
|
|
*
|
|
* @method static Builder<Role> visible()
|
|
*/
|
|
#[Fillable(['name', 'guard_name', 'priority'])]
|
|
class Role extends SpatieRole
|
|
{
|
|
use LogsActivity;
|
|
|
|
public function apps(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(
|
|
ConnectedApp::class,
|
|
'app_roles',
|
|
'role_id',
|
|
'app_id'
|
|
)
|
|
->using(AppRole::class)
|
|
->withPivot('id', 'duration');
|
|
}
|
|
|
|
public function getActivitylogOptions(): LogOptions
|
|
{
|
|
return LogOptions::defaults()
|
|
->logOnly(['name', 'priority'])
|
|
->logOnlyDirty()
|
|
->useLogName('role_management');
|
|
}
|
|
|
|
/**
|
|
* Override the Spatie permissions relationship to provide precise type-hinting for Larastan.
|
|
*
|
|
* @return BelongsToMany<Permission, Role>
|
|
*/
|
|
public function permissions(): BelongsToMany
|
|
{
|
|
return parent::permissions();
|
|
}
|
|
|
|
/**
|
|
* Scope a query to only include roles with priority strictly greater than the logged in user's priority (lower privilege).
|
|
*/
|
|
public function scopeVisible(Builder $query): Builder
|
|
{
|
|
if (! auth()->check()) {
|
|
return $query;
|
|
}
|
|
|
|
$userPriority = auth()->user()?->roles()->min('priority') ?? 999999;
|
|
|
|
return $query->where('priority', '>', $userPriority);
|
|
}
|
|
}
|