update
This commit is contained in:
47
front/application/api/middleware/AuthMiddleware.php
Normal file
47
front/application/api/middleware/AuthMiddleware.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
namespace app\api\middleware;
|
||||
|
||||
use app\common\service\AuthService;
|
||||
use think\Db;
|
||||
|
||||
class AuthMiddleware
|
||||
{
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
// 获取Authorization头
|
||||
$authHeader = $request->header('authorization');
|
||||
|
||||
if (!$authHeader) {
|
||||
return json(['code' => 401, 'error' => 'Missing Authorization header'], 401);
|
||||
}
|
||||
|
||||
// 解析Bearer Token
|
||||
if (!preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
|
||||
return json(['code' => 401, 'error' => 'Invalid token format'], 401);
|
||||
}
|
||||
|
||||
$apiKey = $matches[1];
|
||||
$authService = new AuthService($apiKey);
|
||||
|
||||
// 验证密钥有效性
|
||||
if (!$authService->verifyApiKey()) {
|
||||
return json(['code' => 403, 'error' => 'Invalid API key'], 403);
|
||||
}
|
||||
|
||||
// 将开发者信息注入请求对象
|
||||
$request->developer = $authService->getDeveloperInfo();
|
||||
|
||||
//默认不限流
|
||||
|
||||
// 在中间件最后记录
|
||||
Db::name('api_logs')->insert([
|
||||
'api_key' => $apiKey,
|
||||
'endpoint' => $request->url(),
|
||||
'ip' => $request->ip(),
|
||||
//'created_at' => time()
|
||||
]);
|
||||
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user