This commit is contained in:
2025-03-25 13:47:17 +08:00
parent 81042c384c
commit f40c0ef6e7
18 changed files with 377 additions and 32 deletions

View 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);
}
}