Files
hyperf_service/app/Aspect/Admin/AdminOperationAspect.php
2024-10-27 21:54:35 +08:00

91 lines
2.3 KiB
PHP

<?php
namespace App\Aspect\Admin;
use App\Exception\AdminException;
use App\Lib\Log;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Di\Exception\Exception;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
#[Aspect]
class AdminOperationAspect extends AbstractAspect
{
/**
* 需要切入的类
* @var array|\class-string[]
*/
public array $classes = [
'App\\Service\\Admin\\User\\*Service',
];
/**
* 需要切入的注解
* @var array
*/
public array $annotations = [];
public function __construct(
protected Log $log,
protected RequestInterface $request,
){}
/**
* @param ProceedingJoinPoint $proceedingJoinPoint
* @return mixed
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface|Exception
*/
public function process(ProceedingJoinPoint $proceedingJoinPoint): mixed
{
// 鉴权
$this->checkAuthentication();
// 写操作日志
$this->writeOperationLog();
// 在调用前进行处理
return $proceedingJoinPoint->process();
}
/**
* @return void
*/
private function checkAuthentication(): void
{
$adminId = Context::get('admin_id');
$roleId = Context::get('role_id');
//如果没有id 说明没有登录 抛出异常
if (empty($adminId) || empty($roleId)) {
throw new AdminException('请先登录');
}
//超级管理员不需要鉴权
if ($roleId == 1) return;
//todo 其他角色需要鉴权
}
/**
* 写入请求日志
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function writeOperationLog(): void
{
$post = $this->request->all();
$logParam = !$post ? '{}' : json_encode($post);
$userId = Context::get('user_id',0);
$header = json_encode($this->request->getHeaders());
// 写静态日志
$this->log->requestAdminLog("\nadmin==path:{$this->request->getPathInfo()}\nuserId:$userId\nrequestData:$logParam\nheader:$header");
}
}