AccessService.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. <?php
  2. namespace App\Services\Access;
  3. use App\Models\Permission;
  4. use App\Models\Role;
  5. use App\Models\User;
  6. use Illuminate\Database\QueryException;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Support\Facades\Schema;
  10. class AccessService
  11. {
  12. private const CACHE_VERSION_KEY = 'permissions:version';
  13. public function can(User $user, string $permission): bool
  14. {
  15. $effect = $this->getEffectivePermissions($user)->get($permission);
  16. return $effect === 'allow';
  17. }
  18. public function canAny(User $user, array $permissions): bool
  19. {
  20. foreach ($permissions as $permission) {
  21. if ($this->can($user, trim((string) $permission))) {
  22. return true;
  23. }
  24. }
  25. return false;
  26. }
  27. public function visibilityScope(User $user, string $module): ?string
  28. {
  29. $scopes = config("access_scopes.{$module}", []);
  30. if ($scopes === []) {
  31. return null;
  32. }
  33. $bestScope = null;
  34. $bestPriority = PHP_INT_MIN;
  35. foreach ($scopes as $scope => $priority) {
  36. if (!$this->can($user, "{$module}.scope.{$scope}")) {
  37. continue;
  38. }
  39. if ((int) $priority > $bestPriority) {
  40. $bestScope = (string) $scope;
  41. $bestPriority = (int) $priority;
  42. }
  43. }
  44. return $bestScope;
  45. }
  46. public function hasVisibilityScope(User $user, string $module, string $scope): bool
  47. {
  48. return $this->visibilityScope($user, $module) === $scope;
  49. }
  50. public function canViewField(User $user, string $module, string $field, ?string $entity = null): bool
  51. {
  52. return $this->can($user, $this->fieldPermissionSlug($module, $field, 'view'));
  53. }
  54. public function canUpdateField(User $user, string $module, string $field, ?string $entity = null): bool
  55. {
  56. return $this->can($user, $this->fieldPermissionSlug($module, $field, 'update'));
  57. }
  58. public function filterReadableFields(User $user, string $module, array $fields, ?string $entity = null): array
  59. {
  60. return array_values(array_filter(
  61. $fields,
  62. fn (string $field): bool => $this->canViewField($user, $module, $field, $entity)
  63. ));
  64. }
  65. public function filterWritableData(User $user, string $module, array $data, ?string $entity = null): array
  66. {
  67. return array_filter(
  68. $data,
  69. fn (string $field): bool => $this->canUpdateField($user, $module, $field, $entity),
  70. ARRAY_FILTER_USE_KEY
  71. );
  72. }
  73. public function assertCan(User $user, string $permission): void
  74. {
  75. abort_unless($this->can($user, $permission), 403);
  76. }
  77. public function routePermission(?string $routeName): array|string|bool|null
  78. {
  79. if (!$routeName) {
  80. return null;
  81. }
  82. $exact = config('access_routes.exact', [])[$routeName] ?? null;
  83. if ($exact) {
  84. return $exact;
  85. }
  86. foreach (config('access_routes.prefixes', []) as $prefix => $permissions) {
  87. if (!str_starts_with($routeName, $prefix)) {
  88. continue;
  89. }
  90. $suffix = substr($routeName, strlen($prefix));
  91. return $permissions[$suffix] ?? $permissions['*'] ?? null;
  92. }
  93. return null;
  94. }
  95. public function canAccessRoute(User $user, ?string $routeName): bool
  96. {
  97. $permission = $this->routePermission($routeName);
  98. if ($permission === true) {
  99. return true;
  100. }
  101. if ($permission === null) {
  102. return false;
  103. }
  104. return is_array($permission)
  105. ? $this->canAny($user, $permission)
  106. : $this->can($user, $permission);
  107. }
  108. public function roleHasPermission(Role $role, string $permission): bool
  109. {
  110. $permissionModel = $role->permissions()
  111. ->where('slug', $permission)
  112. ->first();
  113. return $permissionModel?->pivot?->effect === 'allow';
  114. }
  115. public function getEffectivePermissions(User $user): Collection
  116. {
  117. return Cache::remember(
  118. $this->cacheKey($user),
  119. now()->addHour(),
  120. fn (): Collection => $this->resolveEffectivePermissions($user)
  121. );
  122. }
  123. public function bumpCacheVersion(): void
  124. {
  125. Cache::forever(self::CACHE_VERSION_KEY, $this->cacheVersion() + 1);
  126. }
  127. private function resolveEffectivePermissions(User $user): Collection
  128. {
  129. if (!$this->tablesExist()) {
  130. return collect();
  131. }
  132. $effects = collect();
  133. $denied = collect();
  134. $role = $user->roleModel()->with('permissions')->first();
  135. if (!$role && $user->resolvedRoleSlug()) {
  136. $role = Role::query()
  137. ->where('slug', $user->resolvedRoleSlug())
  138. ->with('permissions')
  139. ->first();
  140. }
  141. if ($role) {
  142. foreach ($role->permissions as $permission) {
  143. $effect = $permission->pivot->effect;
  144. if ($effect === 'deny') {
  145. $denied->put($permission->slug, true);
  146. $effects->put($permission->slug, 'deny');
  147. continue;
  148. }
  149. if (!$denied->has($permission->slug)) {
  150. $effects->put($permission->slug, $effect);
  151. }
  152. }
  153. }
  154. $userPermissions = $user->permissions()
  155. ->where(function ($query) {
  156. $query->whereNull('expires_at')
  157. ->orWhere('expires_at', '>', now());
  158. })
  159. ->get();
  160. foreach ($userPermissions as $permission) {
  161. $effect = $permission->pivot->effect;
  162. if ($effect === 'deny') {
  163. $denied->put($permission->slug, true);
  164. $effects->put($permission->slug, 'deny');
  165. continue;
  166. }
  167. if (!$denied->has($permission->slug)) {
  168. $effects->put($permission->slug, $effect);
  169. }
  170. }
  171. return $effects;
  172. }
  173. private function fieldPermissionSlug(string $module, string $field, string $action): string
  174. {
  175. return "{$module}.fields.{$field}.{$action}";
  176. }
  177. private function cacheKey(User $user): string
  178. {
  179. $role = $user->relationLoaded('roleModel')
  180. ? $user->roleModel
  181. : $user->roleModel()->first();
  182. return implode(':', [
  183. 'permissions',
  184. 'user',
  185. $user->id,
  186. sha1((string) $user->email),
  187. $user->getAttribute('role_id') ?: 'legacy',
  188. $user->resolvedRoleSlug() ?: 'none',
  189. optional($user->updated_at)->timestamp ?: 0,
  190. optional($role?->updated_at)->timestamp ?: 0,
  191. 'v' . $this->cacheVersion(),
  192. ]);
  193. }
  194. private function cacheVersion(): int
  195. {
  196. return (int) Cache::get(self::CACHE_VERSION_KEY, 1);
  197. }
  198. private function tablesExist(): bool
  199. {
  200. return Schema::hasTable('roles')
  201. && Schema::hasTable('permissions')
  202. && Schema::hasTable('role_permissions')
  203. && Schema::hasTable('user_permissions');
  204. }
  205. }