mirror of
https://gitee.com/ulthon/ulthon_information.git
synced 2026-07-06 10:12:48 +08:00
feat(api-key): add api_key table, source fields, model and auth middleware
This commit is contained in:
42
app/middleware/ApiKeyAuth.php
Normal file
42
app/middleware/ApiKeyAuth.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace app\middleware;
|
||||
|
||||
use app\model\ApiKey;
|
||||
|
||||
class ApiKeyAuth
|
||||
{
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
$raw_key = '';
|
||||
|
||||
// 优先从 Authorization: Bearer {key} 提取
|
||||
$authorization = $request->header('authorization', '');
|
||||
if (strpos($authorization, 'Bearer ') === 0) {
|
||||
$raw_key = substr($authorization, 7);
|
||||
}
|
||||
|
||||
// 若无 Bearer,尝试从 X-API-Key 请求头获取
|
||||
if (empty($raw_key)) {
|
||||
$raw_key = $request->header('x-api-key', '');
|
||||
}
|
||||
|
||||
if (empty($raw_key)) {
|
||||
return json(['code' => 401, 'msg' => '缺少 API Key', 'data' => null])->code(401);
|
||||
}
|
||||
|
||||
$api_key = ApiKey::verifyKey($raw_key);
|
||||
if (empty($api_key)) {
|
||||
return json(['code' => 401, 'msg' => 'API Key 无效或已禁用', 'data' => null])->code(401);
|
||||
}
|
||||
|
||||
// 注入权限到 Request
|
||||
$request->admin_id = $api_key->admin_id;
|
||||
$request->api_key_id = $api_key->id;
|
||||
$request->can_write_own = $api_key->can_write_own;
|
||||
$request->can_write_other = $api_key->can_write_other;
|
||||
$request->can_delete = $api_key->can_delete;
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user