WaterAccess.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. declare(strict_types=1);
  3. namespace plugin\saiadmin\app\service;
  4. use plugin\saiadmin\app\model\water\{WaterAgent, WaterOperator, WaterOperatorRole};
  5. use plugin\saiadmin\exception\ApiException;
  6. /** Current database permissions, never stored on a reusable controller or in a user cache. */
  7. final class WaterAccess
  8. {
  9. public const MODULES = ['overview', 'alerts', 'dispatch', 'inventory', 'devices', 'enterprises', 'packages', 'agents', 'finance', 'content'];
  10. public function authorize(int $actor, string $module, string $action): void
  11. {
  12. if (!in_array($module, self::MODULES, true)) throw new ApiException('业务模块不存在');
  13. $user = WaterOperator::query()->where('id', $actor)->whereNull('delete_time')->first();
  14. if (!$user || (int) $user->status !== 1) throw new ApiException('账号已停用', 401);
  15. if ($actor === 1) return;
  16. if (WaterAgent::query()->where('user_id', $actor)->where('status', '<>', 1)->exists()) {
  17. throw new ApiException('代理已停用,无法访问供水业务', 403);
  18. }
  19. $allowed = WaterOperatorRole::query()->alias('ur')
  20. ->join('sa_system_role as r', 'r.id', '=', 'ur.role_id')->join('sa_system_role_menu as rm', 'rm.role_id', '=', 'r.id')
  21. ->join('sa_system_menu as m', 'm.id', '=', 'rm.menu_id')->where('ur.user_id', $actor)
  22. ->where('r.status', 1)->whereNull('r.delete_time')->where('m.status', 1)->whereNull('m.delete_time')
  23. ->where('m.slug', 'water:' . $module . ':' . $action)->exists();
  24. if (!$allowed) throw new ApiException('没有该供水业务的操作权限', 403);
  25. }
  26. public function allows(int $actor, string $module, string $action): bool
  27. {
  28. try { $this->authorize($actor, $module, $action); return true; }
  29. catch (ApiException) { return false; }
  30. }
  31. }