Files
lgp-admin-plus-api/app/Http/Middleware/ApiAuthMiddleware.php
LQ bcf54c2727 初始化
缺陷:主题配色需要优化整体的同风格
2026-08-14 23:21:21 +08:00

69 lines
2.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\Http\Middleware;
use App\Enum\ErrorEnum;
use App\Service\common\JWTService;
use App\Service\PermissionService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* 登录态 + 接口级权限
*
* 原来鉴权只发生在 BaseService 的构造函数里,任何不经过 BaseService 的方法就是裸奔的;
* 而 autoRouteRegister 会把继承来的方法也注册成路由,等于白送一批未受保护的入口。
* 这里把校验前移到中间件路由一进来就拦BaseService 里那层保留做兜底。
*/
class ApiAuthMiddleware
{
public function handle(Request $request, Closure $next): Response
{
$path = $this->normalizePath($request->path());
if (in_array($path, (array) config('nl.api.white_list', []), true)) {
return $next($request);
}
try {
$userInfo = JWTService::getInstance()->getToken()->getUserInfo();
} catch (\Throwable $e) {
return $this->deny($e->getMessage() ?: '请先登录', ErrorEnum::NOT_AUTH);
}
if (empty($userInfo['id'])) {
return $this->deny('请先登录', ErrorEnum::NOT_AUTH);
}
$roleId = (int) ($userInfo['role_id'] ?? 0);
if (!PermissionService::getInstance()->allows($roleId, $path)) {
return $this->deny('没有该操作的权限,请联系管理员', ErrorEnum::NOT_PERMISSION);
}
// 后续无需再解 token 的地方可以直接取
$request->attributes->set('nl_user', $userInfo);
return $next($request);
}
private function normalizePath(string $path): string
{
$path = trim($path, '/');
if (str_starts_with($path, 'api/')) {
$path = substr($path, 4);
}
return trim($path, '/');
}
/**
* HTTP 恒 200、业务码表达失败与前端 request.ts 拦截器的约定一致
*/
private function deny(string $message, ErrorEnum $code): Response
{
return response()->json([
'code' => $code->value,
'message' => $message,
'result' => [],
'type' => 'error',
]);
}
}