AuthenticateAdmin.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace App\Http\Middleware\V3;
  3. use App\Models\UserInfo;
  4. use Closure;
  5. use Illuminate\Auth\Access\AuthorizationException;
  6. use Illuminate\Http\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. /**
  9. * v3 管理员闸:只放行 root 与 administrator。必须排在 `auth.v3` 之后(用户已解好放在
  10. * request attributes 里),所以「没登录」是 401、「登录了但不是管理员」是 403。
  11. *
  12. * 角色口径与 v2 一致:root 账号(config('mint.admin.root_uuid'))固定是 root;
  13. * 其余看 user_infos.role(JSON 数组)里有没有 administrator / root。
  14. *
  15. * 别名 `auth.v3.admin`(在 bootstrap/app.php 注册)。
  16. */
  17. class AuthenticateAdmin
  18. {
  19. public const ROLES = ['root', 'administrator'];
  20. /**
  21. * @throws AuthorizationException 不是管理员
  22. */
  23. public function handle(Request $request, Closure $next): Response
  24. {
  25. $uid = $request->attributes->get(Authenticate::USER)['user_uid'] ?? null;
  26. if (! $uid || ! $this->isAdmin($uid)) {
  27. throw new AuthorizationException;
  28. }
  29. return $next($request);
  30. }
  31. private function isAdmin(string $uid): bool
  32. {
  33. if ($uid === config('mint.admin.root_uuid')) {
  34. return true;
  35. }
  36. $roles = json_decode((string) UserInfo::where('userid', $uid)->value('role'), true);
  37. return is_array($roles) && array_intersect(self::ROLES, $roles) !== [];
  38. }
  39. }