| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- namespace App\Models;
- /*
- * User — модель пользователя.
- *
- * role: superadmin | admin | editor | viewer | null (нет доступа в админку)
- * is_admin: legacy-флаг (оставлен, выставляется автоматически при установке роли)
- * userPermissions(): индивидуальные override-права
- * hasPermission(): быстрая проверка через PermissionService (без Gate)
- */
- use App\Services\PermissionService;
- use Database\Factories\UserFactory;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Relations\HasMany;
- use Illuminate\Foundation\Auth\User as Authenticatable;
- use Illuminate\Notifications\Notifiable;
- class User extends Authenticatable
- {
- use HasFactory, Notifiable;
- protected $fillable = ['name', 'email', 'password', 'is_admin', 'role'];
- protected $hidden = ['password', 'remember_token'];
- protected function casts(): array
- {
- return [
- 'email_verified_at' => 'datetime',
- 'password' => 'hashed',
- 'is_admin' => 'boolean',
- ];
- }
- public function userPermissions(): HasMany
- {
- return $this->hasMany(UserPermission::class);
- }
- // Проверка права (eager-load relation один раз на запрос)
- public function hasPermission(string $permission): bool
- {
- if (! $this->relationLoaded('userPermissions')) {
- $this->load('userPermissions');
- }
- return PermissionService::userCan($this, $permission);
- }
- // Может ли пользователь входить в админку
- public function isAdminUser(): bool
- {
- return (bool) $this->role || $this->is_admin;
- }
- // Может ли текущий пользователь управлять целевым
- public function canManage(self $target): bool
- {
- if ($this->role === 'superadmin') {
- return true;
- }
- if ($this->role === 'admin') {
- return ! in_array($target->role, ['superadmin', 'admin'], true);
- }
- return false;
- }
- public function roleBadge(): array
- {
- return PermissionService::roleLabels()[$this->role]
- ?? ['label' => 'Без роли', 'color' => 'secondary'];
- }
- protected static function newFactory(): UserFactory
- {
- return UserFactory::new();
- }
- }
|