multi-store/app/admin/middleware/OperationLogMiddleware.php

71 lines
2.3 KiB
PHP

<?php
namespace app\admin\middleware;
use Exception;
use ReflectionClass;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
class OperationLogMiddleware implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
//需要登录的接口,无效访问时不记录
if (!$request->controllerObject->isNotNeedLogin() && empty($request->adminInfo)) {
return $handler($request);
}
//不记录日志操作
if (strtolower(str_replace('.', '\\', $request->controller)) === 'setting\system\log') {
return $handler($request);
}
//获取操作注解
$notes = '';
try {
$re = new ReflectionClass($request->controllerObject);
$doc = $re->getMethod($request->action)->getDocComment();
if (empty($doc)) {
throw new Exception('请给控制器方法注释');
}
preg_match('/\s(\w+)/u', $re->getMethod($request->action)->getDocComment(), $values);
$notes = $values[0];
} catch (Exception $e) {
$notes = $notes ?: '无法获取操作名称,请给控制器方法注释';
}
$params = $request->all();
//过滤密码参数
if (isset($params['password'])) {
$params['password'] = "******";
}
//过滤密钥参数
if(isset($params['app_secret'])){
$params['app_secret'] = "******";
}
//导出数据操作进行记录
if (isset($params['export']) && $params['export'] == 2) {
$notes .= '-数据导出';
}
//记录日志
$systemLog = new \app\common\model\OperationLog();
$systemLog->admin_id = $request->adminInfo['admin_id'] ?? 0;
$systemLog->admin_name = $request->adminInfo['name'] ?? '';
$systemLog->action = $notes;
$systemLog->account = $request->adminInfo['account'] ?? '';
$systemLog->url = $request->url(true);
$systemLog->type = $request->post()?'POST':'GET';
$systemLog->params = json_encode($params, true);
$systemLog->ip = $request->getRemoteIp();
// $systemLog->result = $response->getContent();
$systemLog->save();
return $handler($request);
}
}