User.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace App\Models;
  3. /*
  4. * User — модель пользователя.
  5. *
  6. * role: superadmin | admin | editor | viewer | null (нет доступа в админку)
  7. * is_admin: legacy-флаг (оставлен, выставляется автоматически при установке роли)
  8. * userPermissions(): индивидуальные override-права
  9. * hasPermission(): быстрая проверка через PermissionService (без Gate)
  10. */
  11. use App\Services\PermissionService;
  12. use Database\Factories\UserFactory;
  13. use Illuminate\Database\Eloquent\Factories\HasFactory;
  14. use Illuminate\Database\Eloquent\Relations\HasMany;
  15. use Illuminate\Foundation\Auth\User as Authenticatable;
  16. use Illuminate\Notifications\Notifiable;
  17. class User extends Authenticatable
  18. {
  19. use HasFactory, Notifiable;
  20. protected $fillable = ['name', 'email', 'password', 'is_admin', 'role'];
  21. protected $hidden = ['password', 'remember_token'];
  22. protected function casts(): array
  23. {
  24. return [
  25. 'email_verified_at' => 'datetime',
  26. 'password' => 'hashed',
  27. 'is_admin' => 'boolean',
  28. ];
  29. }
  30. public function userPermissions(): HasMany
  31. {
  32. return $this->hasMany(UserPermission::class);
  33. }
  34. // Проверка права (eager-load relation один раз на запрос)
  35. public function hasPermission(string $permission): bool
  36. {
  37. if (! $this->relationLoaded('userPermissions')) {
  38. $this->load('userPermissions');
  39. }
  40. return PermissionService::userCan($this, $permission);
  41. }
  42. // Может ли пользователь входить в админку
  43. public function isAdminUser(): bool
  44. {
  45. return (bool) $this->role || $this->is_admin;
  46. }
  47. // Может ли текущий пользователь управлять целевым
  48. public function canManage(self $target): bool
  49. {
  50. if ($this->role === 'superadmin') {
  51. return true;
  52. }
  53. if ($this->role === 'admin') {
  54. return ! in_array($target->role, ['superadmin', 'admin'], true);
  55. }
  56. return false;
  57. }
  58. public function roleBadge(): array
  59. {
  60. return PermissionService::roleLabels()[$this->role]
  61. ?? ['label' => 'Без роли', 'color' => 'secondary'];
  62. }
  63. protected static function newFactory(): UserFactory
  64. {
  65. return UserFactory::new();
  66. }
  67. }