DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

Audit login and logout of the users using owen-it/laravel-auditing Package

To extend auditing in your Laravel application to include user login and logout events using the owen-it/laravel-auditing package, follow these steps:

Package link: Laravel Auditing

1. Install the Package:

If you haven't installed the owen-it/laravel-auditing package, run the following command:

composer require owen-it/laravel-auditing
Enter fullscreen mode Exit fullscreen mode

After installation, publish the config file:

php artisan vendor:publish --provider "OwenIt\Auditing\AuditingServiceProvider" --tag="config"
Enter fullscreen mode Exit fullscreen mode

2. Enable Auditing in the User Model:

In your User model, make sure to use the OwenIt\Auditing\Contracts\Auditable trait to enable auditing:

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use OwenIt\Auditing\Contracts\Auditable;

class User extends Authenticatable implements Auditable
{
    use \OwenIt\Auditing\Auditable;

    // Other User model properties and methods
}
Enter fullscreen mode Exit fullscreen mode

3. Customizing Auditable Events for Login and Logout:

By default, owen-it/laravel-auditing audits only the created, updated, deleted, and restored events. To audit login and logout, you will need to manually trigger the audit events on user authentication events (login, logout).

4. Listen to Login and Logout Events:

In Laravel, you can listen to authentication events like Login and Logout. Create event listeners to handle this:

  1. Create Event Listener for Login and Logout:

Run the following command to create listeners for user login and logout:

php artisan make:listener LogSuccessfulLogin
php artisan make:listener LogSuccessfulLogout
Enter fullscreen mode Exit fullscreen mode

In the app/Listeners/LogSuccessfulLogin.php file, add the following logic to audit login events:

namespace App\Listeners;

use Illuminate\Auth\Events\Login;

class LogSuccessfulLogin
{
    public function handle(Login $event)
    {
        // Log audit for user login
        $event->user->auditEvent('login');
    }
}
Enter fullscreen mode Exit fullscreen mode

In the app/Listeners/LogSuccessfulLogout.php file, add the following logic to audit logout events:

namespace App\Listeners;

use Illuminate\Auth\Events\Logout;

class LogSuccessfulLogout
{
    public function handle(Logout $event)
    {
        // Log audit for user logout
        $event->user->auditEvent('logout');
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Register the Event Listeners:

Open the app/Providers/EventServiceProvider.php and register the listeners for login and logout events:
Note: For laravel 11.x and above, the events are detected automatically

protected $listen = [
    \Illuminate\Auth\Events\Login::class => [
        \App\Listeners\LogSuccessfulLogin::class,
    ],
    \Illuminate\Auth\Events\Logout::class => [
        \App\Listeners\LogSuccessfulLogout::class,
    ],
];
Enter fullscreen mode Exit fullscreen mode
  1. Define Custom Audit Event Names:

To enable custom audit event names (like login and logout), modify the User model's getAuditEvent() method:

use OwenIt\Auditing\Models\Audit;

class User extends Authenticatable implements Auditable
{
    use \OwenIt\Auditing\Auditable;

    public function auditEvent($event)
    {
        // Create an audit entry with a custom event (e.g., login, logout)
        Audit::create([
            'auditable_type' => self::class,
            'auditable_id'   => $this->id,
            'event'          => $event,
            'url'            => request()->fullUrl(),
            'ip_address'     => request()->ip(),
            'user_agent'     => request()->userAgent(),
            'created_at'     => now(),
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Migrate the Audit Table:

Make sure you have migrated the audit table if you haven't done so already:

php artisan vendor:publish --provider "OwenIt\Auditing\AuditingServiceProvider" --tag="migrations"
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

6. Testing the Audit for Login and Logout:

Now, every time a user logs in or logs out, an audit event will be logged with a custom event name (login or logout) in the audits table.

7. View the Audit Logs:

You can check the audit logs by querying the audits table or by accessing it programmatically:

$audits = \OwenIt\Auditing\Models\Audit::where('auditable_type', App\Models\User::class)->get();
Enter fullscreen mode Exit fullscreen mode

This will log login and logout events along with the usual created, updated, deleted, and restored events.

Top comments (0)