Files

56 lines
1.4 KiB
PHP
Raw Permalink Normal View History

2025-11-05 16:34:40 +08:00
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Controller;
2026-04-16 13:16:43 +08:00
use App\Model\User;
2025-11-05 16:34:40 +08:00
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;
2026-04-16 13:16:43 +08:00
use Qbhy\HyperfAuth\AuthManager;
2025-11-05 16:34:40 +08:00
abstract class AbstractController
{
#[Inject]
protected ContainerInterface $container;
#[Inject]
protected RequestInterface $request;
#[Inject]
protected ResponseInterface $response;
2026-04-16 13:16:43 +08:00
/**
* 统一获取当前认证用户
*
* 优先从 request attribute 获取(JWT/API Key 中间件统一设置),
* 兜底通过 JWT guard 获取(过渡期兼容)。
*/
protected function getAuthUser(): ?User
{
$user = $this->request->getAttribute('auth_user');
if ($user instanceof User) {
return $user;
}
// 兜底:直接通过 JWT guard 获取
try {
$auth = $this->container->get(AuthManager::class);
$user = $auth->guard('jwt')->user();
return $user instanceof User ? $user : null;
} catch (\Throwable) {
return null;
}
}
2025-11-05 16:34:40 +08:00
}