add user manager and auth for backend

This commit is contained in:
2025-11-10 10:45:43 +08:00
parent bf57db57f1
commit 0cfecab68f
9 changed files with 1014 additions and 8 deletions
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Middleware;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Qbhy\HyperfAuth\AuthManager;
use Qbhy\HyperfAuth\Exception\UnauthorizedException;
class AuthMiddleware implements MiddlewareInterface
{
public function __construct(
protected AuthManager $auth,
protected HttpResponse $response
) {
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
try {
// 验证 token
$user = $this->auth->guard('jwt')->user();
if (!$user) {
return $this->response->json([
'code' => 401,
'message' => '未授权,请先登录',
])->withStatus(401);
}
// @attention check here!
// 检查用户状态
if (method_exists($user, '__get') && $user->status !== 1) {
return $this->response->json([
'code' => 403,
'message' => '账号已被禁用',
])->withStatus(403);
}
} catch (UnauthorizedException $e) {
return $this->response->json([
'code' => 401,
'message' => 'Token 无效或已过期',
])->withStatus(401);
} catch (\Throwable $e) {
return $this->response->json([
'code' => 500,
'message' => '认证失败: ' . $e->getMessage(),
])->withStatus(500);
}
return $handler->handle($request);
}
}