User.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Contracts\Auth\MustVerifyEmail;
  4. use Illuminate\Database\Eloquent\Builder;
  5. use Illuminate\Database\Eloquent\Factories\HasFactory;
  6. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  7. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  8. use Illuminate\Database\Eloquent\Relations\HasMany;
  9. use Illuminate\Database\Eloquent\SoftDeletes;
  10. use Illuminate\Foundation\Auth\User as Authenticatable;
  11. use Illuminate\Notifications\Notifiable;
  12. use Illuminate\Support\Facades\DB;
  13. class User extends Authenticatable implements MustVerifyEmail
  14. {
  15. use HasFactory, Notifiable, SoftDeletes;
  16. const DEFAULT_SORT_BY = 'created_at';
  17. /**
  18. * The attributes that are mass assignable.
  19. *
  20. * @var list<string>
  21. */
  22. protected $fillable = [
  23. 'name',
  24. 'email',
  25. 'notification_email',
  26. 'phone',
  27. 'password',
  28. 'role',
  29. 'role_id',
  30. 'color',
  31. 'token_fcm',
  32. ];
  33. /**
  34. * The attributes that should be hidden for serialization.
  35. *
  36. * @var list<string>
  37. */
  38. protected $hidden = [
  39. 'password',
  40. 'remember_token',
  41. ];
  42. /**
  43. * Get the attributes that should be cast.
  44. *
  45. * @return array<string, string>
  46. */
  47. protected function casts(): array
  48. {
  49. return [
  50. 'email_verified_at' => 'datetime',
  51. 'password' => 'hashed',
  52. ];
  53. }
  54. /**
  55. * Route notifications for the FCM channel.
  56. *
  57. * @return string
  58. */
  59. public function routeNotificationForFcm(): string
  60. {
  61. return (string)$this->token_fcm;
  62. }
  63. public function getAppInstalledAttribute(): string
  64. {
  65. return $this->token_fcm ? 'Да' : 'Нет';
  66. }
  67. public function userNotifications(): HasMany
  68. {
  69. return $this->hasMany(UserNotification::class);
  70. }
  71. public function unreadUserNotifications(): HasMany
  72. {
  73. return $this->userNotifications()->whereNull('read_at');
  74. }
  75. public function roleModel(): BelongsTo
  76. {
  77. return $this->belongsTo(Role::class, 'role_id');
  78. }
  79. public function permissions(): BelongsToMany
  80. {
  81. return $this->belongsToMany(Permission::class, 'user_permissions')
  82. ->withPivot(['effect', 'reason', 'expires_at'])
  83. ->withTimestamps();
  84. }
  85. public function scopeWithPermission(Builder $query, string $permission): Builder
  86. {
  87. return $query->where(function (Builder $query) use ($permission): void {
  88. $query
  89. ->whereHas('roleModel.permissions', function (Builder $query) use ($permission): void {
  90. $query
  91. ->where('slug', $permission)
  92. ->where('role_permissions.effect', 'allow');
  93. })
  94. ->orWhereExists(function ($query) use ($permission): void {
  95. $query
  96. ->selectRaw('1')
  97. ->from('roles')
  98. ->join('role_permissions', 'role_permissions.role_id', '=', 'roles.id')
  99. ->join('permissions', 'permissions.id', '=', 'role_permissions.permission_id')
  100. ->whereColumn('roles.slug', 'users.role')
  101. ->where('permissions.slug', $permission)
  102. ->where('role_permissions.effect', 'allow');
  103. })
  104. ->orWhereHas('permissions', function (Builder $query) use ($permission): void {
  105. $query
  106. ->where('slug', $permission)
  107. ->where('user_permissions.effect', 'allow')
  108. ->where(function (Builder $query): void {
  109. $query
  110. ->whereNull('user_permissions.expires_at')
  111. ->orWhere('user_permissions.expires_at', '>', now());
  112. });
  113. });
  114. });
  115. }
  116. public function scopeWithAnyPermission(Builder $query, array|string $permissions): Builder
  117. {
  118. $permissions = is_array($permissions) ? $permissions : explode(',', $permissions);
  119. $permissions = array_filter(array_map('trim', $permissions));
  120. return $query->where(function (Builder $query) use ($permissions): void {
  121. foreach ($permissions as $permission) {
  122. $query->orWhere(fn (Builder $query): Builder => $query->withPermission($permission));
  123. }
  124. });
  125. }
  126. public function hasRole(string|array $roles): bool
  127. {
  128. $roles = is_array($roles) ? $roles : explode(',', $roles);
  129. $roles = array_map('trim', $roles);
  130. $role = $this->resolvedRoleSlug();
  131. if (!$role) {
  132. return false;
  133. }
  134. return count(array_intersect($roles, Role::effectiveRoles($role))) > 0;
  135. }
  136. public function hasPermission(string $permission): bool
  137. {
  138. return app(\App\Services\Access\AccessService::class)->can($this, $permission);
  139. }
  140. public function hasAnyPermission(array|string $permissions): bool
  141. {
  142. $permissions = is_array($permissions) ? $permissions : explode(',', $permissions);
  143. return app(\App\Services\Access\AccessService::class)->canAny($this, $permissions);
  144. }
  145. public function visibilityScope(string $module): ?string
  146. {
  147. return app(\App\Services\Access\AccessService::class)->visibilityScope($this, $module);
  148. }
  149. public function hasVisibilityScope(string $module, string $scope): bool
  150. {
  151. return app(\App\Services\Access\AccessService::class)->hasVisibilityScope($this, $module, $scope);
  152. }
  153. public function canViewField(string $module, string $field, ?string $entity = null): bool
  154. {
  155. return app(\App\Services\Access\AccessService::class)->canViewField($this, $module, $field, $entity);
  156. }
  157. public function canUpdateField(string $module, string $field, ?string $entity = null): bool
  158. {
  159. return app(\App\Services\Access\AccessService::class)->canUpdateField($this, $module, $field, $entity);
  160. }
  161. public function getEffectivePermissions(): \Illuminate\Support\Collection
  162. {
  163. return app(\App\Services\Access\AccessService::class)->getEffectivePermissions($this);
  164. }
  165. public function resolvedRoleSlug(): ?string
  166. {
  167. if ($this->getAttribute('role_id')) {
  168. $role = $this->relationLoaded('roleModel')
  169. ? $this->roleModel
  170. : $this->roleModel()->first();
  171. if ($role) {
  172. return $role->slug;
  173. }
  174. }
  175. return $this->role;
  176. }
  177. public static function assignUniqueFcmToken(int $userId, string $token): void
  178. {
  179. DB::transaction(function () use ($userId, $token) {
  180. self::query()
  181. ->where('id', '!=', $userId)
  182. ->where('token_fcm', $token)
  183. ->update(['token_fcm' => null]);
  184. self::query()
  185. ->where('id', $userId)
  186. ->update(['token_fcm' => $token]);
  187. });
  188. }
  189. public static function clearFcmToken(int $userId): void
  190. {
  191. self::query()
  192. ->where('id', $userId)
  193. ->update(['token_fcm' => null]);
  194. }
  195. }