2017 © Pedro Peláez
 

yii2-extension yii2-audit

Auditing component for Yii2

image

cornernote/yii2-audit

Auditing component for Yii2

  • Monday, June 22, 2015
  • by cornernote
  • Repository
  • 1 Watchers
  • 1 Stars
  • 12 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 63 Forks
  • 0 Open issues
  • 8 Versions
  • 0 % Grown

The README.md

Yii2 Audit

Join Chat Latest Version Software License Build Status Coverage Status Quality Score Total Downloads, (*1)

Yet another auditing module. This is based on a couple of other projects out there:, (*2)

Features

Installs as a simple module so it can be added without too much hassle., (*3)

  • Tracks all incoming pageviews with the ability to add custom data to a view. It logs the user-id (if any), IP, superglobals ($_GET/$_POST/$_SERVER/$_FILES/$_COOKIES), memory usage, referrer and origin. You can either track specific actions and nothing else or exclude specific routes from logging (wildcard supported)., (*4)

  • Track database changes. By implementing the AuditingBehavior this is easily realized thanks to a modified version of Sammayes Yii2 Audit Trail., (*5)

  • Automatically log javascript errors. Errors and warning are logged automatically (if you activate the functionality), but the javascript component also provides methods to manually add logging entries., (*6)

  • View your data. The module contains a nice viewer that is automatically made available when you add it to your configuration. It has configurable permissions to limit access to this functionality, both by roles or by user-id., (*7)

Installing

  • Run composer.phar require --prefer-dist bedezign/yii2-audit "*" or add a require line to your composer.json: 'bedezign/yii2-audit: "*".
  • Run the migrations from the migrations folder to create the relevant tables: yii migrate --migrationPath=@bedezign/yii2/audit/migrations
  • Add a module to your configuration (with optional extra settings) and if it needs to auto trigger, also add it to the bootstrap:

Example:, (*8)

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

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

This installs the module with auto loading, instructing it to not log anything debug related., (*9)

Additional options

'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)
    ],
],

Word of caution: The module is configured by default to only allow viewing access to users with the role 'admin'. This functionality is only available in Yii if you have enabled RBAC (via the authManager-component). If not, please set this option to null. If you do so you should consider activating the accessUsers-option, you don't want to give everyone access to your auditing data!, (*10)

Error Logging

If you want errors to be logged, you have to register the included errorhandler as well in you configuration:, (*11)

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

Database changes

If you want database changes to be logged, you have to add the AuditingBehavior to the models you want to log., (*12)

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

Additional options

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
        ]
    ];
}

Only log database changes

If you only want to log the database changes you should use the following module setting. All pageview logging will be ignored., (*13)

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

There is a grid for only database changes available at:, (*14)

http://localhost/path/to/index.php?r=auditing/default/trail, (*15)

Render Audit Log for a Model

Model:, (*16)

    /** 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',
            ]);
    }

Controller:, (*17)

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

View, (*18)

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 Logging

The module also supports logging of javascript errors, warnings and even regular log entries. To activate, register the assets\JSLoggingAsset in any of your views:, (*19)

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

This will activate the logger automatically. By default all warnings and errors are transmitted to the backend., (*20)

The default configuration assumes that the module was added as "auditing" (so the log url would be "/auditing/javascript/log"). If that is not the case, please make sure to update the setting somewhere in your javascript:, (*21)

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

All javascript logging will be linked to the entry associated with the page entry created when you performed the initial request. This is accomplished by adding the ID of that entry in the window-object (window.auditEntry)., (*22)

Beware: If you use ajax or related technologies to load data from the backend, these requests might generate their own auditing entries. If those cause backend errors they will be linked to that new entry. This might be a bit weird with the javascript logging being linked to the older entry., (*23)

Extra Data

It is possible to add extra custom data to the current audit entry by simply calling:, (*24)

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

Or if you prefer:, (*25)

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

Emailing Errors

A command is available to email errors which can be added to your cron., (*26)

php yii auditing/error-email

You should ensure you have setup a mailer component and have a scriptUrl property in the urlManager component in your console configuration. For example:, (*27)

$console = [
    'components' => [
        'mailer' => [
            // see http://www.yiiframework.com/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/',
        ],
    ],
]

Render AuditEntry.id in Layout

It is often useful for users to be able to report the AuditEntry.id to the developer. To render the ID to the page include the partial provided:, (*28)

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

Viewing the audit data

Assuming you named the module "auditing" you can then access the auditing module through the following URL:, (*29)

http://localhost/path/to/index.php?r=auditing

If you would like to see all database changes individually you can access:, (*30)

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

Screenshots

Index example View example Diff example, (*31)

The Versions

22/06 2015

dev-master

9999999-dev

Auditing component for Yii2

  Sources   Download

BSD 3-Clause

The Requires

 

The Development Requires

yii2 module audit trail

12/06 2015

0.1.6

0.1.6.0

Auditing component for Yii2

  Sources   Download

BSD 3-Clause

The Requires

 

yii2 module audit trail

12/06 2015

0.1.5

0.1.5.0

Auditing component for Yii2

  Sources   Download

BSD 3-Clause

The Requires

 

yii2 module audit trail

10/06 2015

0.1.4

0.1.4.0

Auditing component for Yii2

  Sources   Download

BSD 3-Clause

The Requires

 

yii2 module audit trail

02/06 2015

0.1.3

0.1.3.0

Auditing component for Yii2

  Sources   Download

BSD 3-Clause

The Requires

 

yii2 module audit trail

02/06 2015

0.1.2

0.1.2.0

Auditing component for Yii2

  Sources   Download

BSD 3-Clause

The Requires

 

yii2 module audit trail

29/05 2015

0.1.1

0.1.1.0

Auditing component for Yii2

  Sources   Download

BSD 3-Clause

The Requires

 

yii2 module audit trail

22/05 2015

0.1

0.1.0.0

Auditing component for Yii2

  Sources   Download

BSD 3-Clause

The Requires

 

yii2 module audit trail