cornernote/yii2-audit

Yii2的审计组件

安装: 47

依赖项: 0

建议者: 0

安全: 0

星标: 1

关注者: 2

分支: 111

类型:yii2-extension

0.1.6 2015-06-12 16:53 UTC

This package is auto-updated.

Last update: 2024-09-19 18:13:14 UTC


README

Join Chat Latest Version Software License Build Status Coverage Status Quality Score Total Downloads

又一个审计模块。这个模块基于其他几个现有的项目

特性

作为简单的模块安装,因此无需太多麻烦即可添加。

  • 跟踪所有页面访问,并能够将自定义数据添加到视图中。它记录用户ID(如果有)、IP、超全局变量 ($_GET/$_POST/$_SERVER/$_FILES/$_COOKIES)、内存使用情况、引用者和来源。您可以跟踪特定的操作而不记录其他内容,或者排除特定的路由以进行记录(支持通配符)。

  • 跟踪数据库更改。通过实现 AuditingBehavior,这可以通过修改版本的 Sammayes Yii2 Audit Trail 来轻松实现。

  • 自动记录javascript错误。如果激活了该功能,错误和警告将自动记录,但javascript组件还提供了手动添加记录条目的方法。

  • 查看数据。该模块包含一个漂亮的查看器,当您将其添加到配置中时,它将自动提供。它具有可配置的权限来限制对此功能的访问,既可以按角色也可以按用户ID。

安装

  • 运行 composer.phar require --prefer-dist bedezign/yii2-audit "*" 或在您的 composer.json 中添加一个 require 行: 'bedezign/yii2-audit: "*"
  • 运行 migrations 文件夹中的迁移来创建相关表: yii migrate --migrationPath=@bedezign/yii2/audit/migrations
  • 将模块添加到您的配置(带有可选的额外设置),如果需要自动触发,也请将其添加到引导程序

示例

'bootstrap' => ['log', 'auditing', ...],
'controllerNamespace' => 'frontend\controllers',

'modules' => [
    'auditing' => [
        'class' => 'bedezign\yii2\audit\Auditing',
        'ignoreActions' => 'debug/*',
    ],
],

此示例安装了模块并自动加载,指示它不要记录任何调试相关的信息。

附加选项

'modules' => [
    'auditing' => [
        'class' => 'bedezign\yii2\audit\Auditing',
        'db' => 'db', // Name of the component to use for database access
        'trackActions' => ['*'], // List of actions to track. '*' is allowed as the last character to use as wildcard
        'ignoreActions' => 'debug/*', // Actions to ignore. '*' is allowed as the last character to use as wildcard (eg 'debug/*')
        'truncateChance' => 75, // Chance in % that the truncate operation will run, false to not run at all
        'maxAge' => 'debug', // Maximum age (in days) of the audit entries before they are truncated
        'accessUsers' => [1, 2], // (List of) user(s) IDs with access to the viewer, null for everyone (if the role matches)
        'accessRoles' => ['admin'], // (List of) role(s) with access to the viewer, null for everyone (if the user matches)
    ],
],

注意:默认情况下,该模块配置为仅允许具有“admin”角色的用户查看。此功能仅在Yii中启用时可用,您已通过 authManager-组件启用了RBAC(如果未启用,请将此选项设置为 null)。如果您这样做,请考虑激活 accessUsers-选项,您不希望让每个人都访问您的审计数据!

错误记录

如果您想记录错误,则必须在您的配置中注册包含的错误处理器。

'errorHandler' => [
   'class' => '\bedezign\yii2\audit\components\web\ErrorHandler',
   'errorAction' => 'site/error',
],

数据库更改

如果您想记录数据库更改,则必须将 AuditingBehavior 添加到您想要记录的模型。

public function behaviors()
{
    return [
        'bedezign\yii2\audit\AuditingBehavior'
    ];
}

附加选项

public function behaviors()
{
    return [
        'LoggableBehavior' => [
            'class' => 'sammaye\audittrail\LoggableBehavior',
            'allowed' => ['some_field'], // Array with fields to save. You don't need to configure both `allowed` and `ignored`
            'ignored' => ['another_field'], // Array with fields to ignore. You don't need to configure both `allowed` and `ignored`
            'ignoredClasses' => ['common\models\Model'], // Array with classes to ignore
            'skipNulls' => false, // Skip fields where bouth old and new values are NULL
            'active' => true // Is the behavior is active or not
        ]
    ];
}

仅记录数据库更改

如果您只想记录数据库更改,请使用以下模块设置。所有页面查看记录将被忽略。

'modules' => [
    'auditing' => [
        'class' => 'bedezign\yii2\audit\Auditing',
        'ignoreActions' => ['*'],
    ],
],

仅数据库更改的网格可在以下位置找到:

https:///path/to/index.php?r=auditing/default/trail

渲染模型审计日志

模型

    /** get trails for this model */
    public function getAuditTrails()
    {
        return $this->hasMany(AuditTrail::className(), ['model_id' => 'id'])
            ->andOnCondition(['model' => get_class($this)]);
    }
    /** get trails for this model and all related comment models */
    public function getAuditTrails()
    {
        return AuditTrail::find()
            ->orOnCondition([
                'audit_trail.model_id' => $this->id, 
                'audit_trail.model' => get_class($this),
              ])
            ->orOnCondition([
                'audit_trail.model_id' => ArrayHelper::map($this->getComments()->all(), 'id', 'id'), 
                'audit_trail.model' => 'app\models\Comment',
            ]);
    }

控制器

    public function actionLog($id)
    {
        $model = $this->findModel($id);
        return $this->render('log', ['model' => $model]);
    }

视图

echo $this->render('@vendor/bedezign/yii2-audit/views/_audit_trails', [
    // model to display audit trais for, must have a getAuditTrails() method
    'model' => $model,
    // params for the AuditTrailSearch::search() (optional)
    'params' => [
        'AuditTrailSearch' => [
            'field' => 'status', // in this case we only want to show trails for the "status" field
        ]
    ],
]);

JavaScript记录

该模块还支持记录javascript错误、警告甚至常规日志条目。要激活,在您的任何视图中注册 assets\JSLoggingAsset

 \bedezign\yii2\audit\assets\JSLoggingAsset::register($this);

这将自动激活记录器。默认情况下,所有警告和错误都传输到后端。

默认配置假定模块被添加为“auditing”(因此日志URL将是“/auditing/javascript/log”)。如果不是这种情况,请确保在您的javascript中的某个位置更新此设置。

window.jsLogger.logUrl = '/mymodulename/javascript/log';

所有JavaScript日志都将链接到与您进行初始请求时创建的页面入口关联的条目。这是通过在window对象中添加该条目的ID(window.auditEntry)来实现的。

注意:如果您使用ajax或相关技术从后端加载数据,这些请求可能会生成它们自己的审计条目。如果这些导致后端错误,它们将与新的条目关联。这可能有点奇怪,因为JavaScript日志与较旧的条目关联。

附加数据

您可以通过简单地调用来向当前的审计条目添加额外的自定义数据。

\bedezign\yii2\audit\Auditing::current()->data('name', 'extra data can be an integer, string, array, object or whatever', 'optional type');

或者如果您更喜欢

\Yii::$app->auditing->data(('name', 'extra data can be an integer, string, array, object or whatever', 'optional type');

通过电子邮件发送错误

有一个命令可以发送错误,您可以将其添加到cron中。

php yii auditing/error-email

您应确保已设置mailer组件,并在控制台配置中的urlManager组件中具有scriptUrl属性。例如

$console = [
    'components' => [
        'mailer' => [
            // see https://yiiframework.cn/doc-2.0/guide-tutorial-mailing.html
            'class' => 'yii\swiftmailer\Mailer',
        ],
        'urlManager' => [
            // required because the CLI script doesn't know the URL
            'scriptUrl' => 'http://example.com/',
        ],
    ],
]

在布局中渲染AuditEntry.id

对于用户能够向开发者报告AuditEntry.id来说,这通常很有用。要将ID渲染到页面中,请包含提供的部分

<?= $this->render('@vendor/bedezign/yii2-audit/views/_audit_entry_id', [
  'link' => false, // set to true to render the id as a link
]); ?>

查看审计数据

假设您将模块命名为"auditing",然后您可以通过以下URL访问审计模块

https:///path/to/index.php?r=auditing

如果您想单独查看所有数据库更改,您可以访问

https:///path/to/index.php?r=auditing/default/trail

屏幕截图

Index example View example Diff example