AgentAuthMiddleware.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Constants\HttpStatus;
  4. use App\Models\Agent\Agent;
  5. use App\Models\Agent\AgentToken;
  6. use Closure;
  7. use Illuminate\Http\Request;
  8. class AgentAuthMiddleware
  9. {
  10. public function handle(Request $request, Closure $next)
  11. {
  12. $plainToken = preg_replace('/^Bearer\s+/i', '', (string) $request->header('Authorization'));
  13. if ($plainToken === '') {
  14. return response()->json(['code' => HttpStatus::AUTHORIZATION_HEADER_NOT_FOUND, 'timestamp' => time(), 'msg' => '请先登录', 'data' => []]);
  15. }
  16. $token = AgentToken::query()
  17. ->where('token_hash', hash('sha256', $plainToken))
  18. ->where('expires_at', '>', now())
  19. ->first();
  20. $agent = $token ? Agent::query()->find($token->agent_id) : null;
  21. if (!$token || !$agent || (int) $agent->status !== Agent::STATUS_ENABLED) {
  22. return response()->json(['code' => HttpStatus::AUTHORIZATION_HEADER_NOT_FOUND, 'timestamp' => time(), 'msg' => '登录已失效', 'data' => []]);
  23. }
  24. if (!$token->last_used_at || $token->last_used_at->lt(now()->subMinute())) {
  25. $token->last_used_at = now();
  26. $token->save();
  27. }
  28. $request->attributes->set('agent', $agent);
  29. $request->attributes->set('agent_token', $token);
  30. return $next($request);
  31. }
  32. }