Files
ulthon_information/app/middleware/ApiKeyAuth.php

43 lines
1.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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