Initial commit: ThinkPHP refactor (tp)
Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\api\middleware;
|
||||
|
||||
use app\api\common\Jwt;
|
||||
use app\api\common\Response;
|
||||
|
||||
/**
|
||||
* JWT 认证中间件
|
||||
*/
|
||||
class Auth
|
||||
{
|
||||
/**
|
||||
* 处理请求
|
||||
* @param \think\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
// 获取 Token
|
||||
$token = Jwt::getTokenFromRequest();
|
||||
|
||||
if (!$token) {
|
||||
return Response::error('未提供认证令牌', 401);
|
||||
}
|
||||
|
||||
// 验证 Token
|
||||
$payload = Jwt::decode($token);
|
||||
|
||||
if (!$payload) {
|
||||
return Response::error('令牌无效或已过期', 401);
|
||||
}
|
||||
|
||||
// 将用户信息注入请求
|
||||
$request->payload = $payload;
|
||||
$request->userid = $payload['userid'] ?? null;
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
declare (strict_types = 1);
|
||||
|
||||
namespace app\api\middleware;
|
||||
|
||||
use think\Response;
|
||||
|
||||
/**
|
||||
* API 跨域中间件
|
||||
*/
|
||||
class CrossDomain
|
||||
{
|
||||
/**
|
||||
* 处理请求
|
||||
* @param \think\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
// OPTIONS 请求直接返回
|
||||
if ($request->method() == 'OPTIONS') {
|
||||
return Response::create('', 'html', 204)
|
||||
->header([
|
||||
'Access-Control-Allow-Origin' => '*',
|
||||
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
|
||||
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Request-With, token',
|
||||
'Access-Control-Allow-Credentials' => 'true',
|
||||
]);
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
// 设置跨域响应头
|
||||
$response->header([
|
||||
'Access-Control-Allow-Origin' => '*',
|
||||
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
|
||||
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Request-With, token',
|
||||
'Access-Control-Allow-Credentials' => 'true',
|
||||
]);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user