You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.7 KiB
PHP
54 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Services\JwtService;
|
|
use App\Services\PatientAuthService;
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class CheckPatientToken
|
|
{
|
|
protected $jwtService;
|
|
protected $patientAuthService;
|
|
|
|
public function __construct(JwtService $jwtService, PatientAuthService $patientAuthService)
|
|
{
|
|
$this->jwtService = $jwtService;
|
|
$this->patientAuthService = $patientAuthService;
|
|
}
|
|
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$authHeader = $request->header('Authorization');
|
|
|
|
if (!$authHeader) {
|
|
return response()->json(['code' => 401, 'message' => '请先登录'], 401);
|
|
}
|
|
|
|
$token = str_replace('Bearer ', '', $authHeader);
|
|
|
|
if (!$token) {
|
|
return response()->json(['code' => 401, 'message' => 'Token无效'], 401);
|
|
}
|
|
|
|
try {
|
|
$payload = $this->jwtService->verifyToken($token);
|
|
|
|
if (!$this->patientAuthService->isPatient($payload)) {
|
|
return response()->json(['code' => 403, 'message' => '非患者身份'], 403);
|
|
}
|
|
|
|
$request->attributes->set('payload', $payload);
|
|
return $next($request);
|
|
} catch (\Firebase\JWT\ExpiredException $e) {
|
|
return response()->json(['code' => 401, 'message' => '登录已过期,请重新登录'], 401)
|
|
->setEncodingOptions(JSON_UNESCAPED_UNICODE);
|
|
} catch (\Exception $e) {
|
|
return response()->json(['code' => 400, 'message' => 'Token验证失败'], 400)
|
|
->setEncodingOptions(JSON_UNESCAPED_UNICODE);
|
|
}
|
|
}
|
|
}
|