| 12345678910111213141516171819202122232425262728293031323334353637 |
- <?php
- namespace App\Http\Middleware;
- use App\Constants\HttpStatus;
- use App\Models\Agent\Agent;
- use App\Models\Agent\AgentToken;
- use Closure;
- use Illuminate\Http\Request;
- class AgentAuthMiddleware
- {
- public function handle(Request $request, Closure $next)
- {
- $plainToken = preg_replace('/^Bearer\s+/i', '', (string) $request->header('Authorization'));
- if ($plainToken === '') {
- return response()->json(['code' => HttpStatus::AUTHORIZATION_HEADER_NOT_FOUND, 'timestamp' => time(), 'msg' => '请先登录', 'data' => []]);
- }
- $token = AgentToken::query()
- ->where('token_hash', hash('sha256', $plainToken))
- ->where('expires_at', '>', now())
- ->first();
- $agent = $token ? Agent::query()->find($token->agent_id) : null;
- if (!$token || !$agent || (int) $agent->status !== Agent::STATUS_ENABLED) {
- return response()->json(['code' => HttpStatus::AUTHORIZATION_HEADER_NOT_FOUND, 'timestamp' => time(), 'msg' => '登录已失效', 'data' => []]);
- }
- if (!$token->last_used_at || $token->last_used_at->lt(now()->subMinute())) {
- $token->last_used_at = now();
- $token->save();
- }
- $request->attributes->set('agent', $agent);
- $request->attributes->set('agent_token', $token);
- return $next($request);
- }
- }
|