PHPackages                             alshahari/laravel-auth-tracker - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. alshahari/laravel-auth-tracker

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

alshahari/laravel-auth-tracker
==============================

Track and manage sessions, Passport tokens and Sanctum tokens in Laravel.

v1.0.0(1y ago)211MITPHPPHP ^7.2.5|^8.0

Since Jun 13Pushed 9mo ago1 watchersCompare

[ Source](https://github.com/abobakeralshahari/laravel-auth-tracker)[ Packagist](https://packagist.org/packages/alshahari/laravel-auth-tracker)[ RSS](/packages/alshahari-laravel-auth-tracker/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (7)Versions (3)Used By (0)

Laravel Auth Tracker
====================

[](#laravel-auth-tracker)

#### Track and manage sessions, Passport tokens and Sanctum tokens in Laravel.

[](#track-and-manage-sessions-passport-tokens-and-sanctum-tokens-in-laravel)

This package allows you to track separately each login (session or token), attaching informations by parsing the User-Agent and saving the IP address.

Using a supported provider or creating your own custom providers, you can collect even more informations with an IP address lookup to get, for example, the geolocation.

You can revoke every single session/token or all at once. In case of sessions with remember tokens, every session has its own remember token. This way, you can revoke a session without affecting the others.

- [Compatibility](#compatibility)
- [Installation](#installation)
    - [Create the logins table](#create-the-logins-table)
    - [Prepare your authenticatable models](#prepare-your-authenticatable-models)
    - [Prepare your LoginController](#prepare-your-logincontroller)
    - [Choose and install a user-agent parser](#choose-and-install-a-user-agent-parser)
    - [Configure the user provider](#configure-the-user-provider)
    - [Generate the scaffolding](#generate-the-scaffolding)
    - [Laravel Sanctum](#laravel-sanctum)
- [Usage](#usage)
    - [Retrieving the logins](#retrieving-the-logins)
        - [Get all the logins](#get-all-the-logins)
        - [Get the current login](#get-the-current-login)
    - [Check for the current login](#check-for-the-current-login)
    - [Revoking logins](#revoking-logins)
        - [Revoke a specific login](#revoke-a-specific-login)
        - [Revoke all the logins](#revoke-all-the-logins)
        - [Revoke all the logins except the current one](#revoke-all-the-logins-except-the-current-one)
- [Routes](#routes)
- [Events](#events)
    - [Login](#login)
- [IP address lookup](#ip-address-lookup)
    - [Ip2Location Lite DB3](#ip2location-lite-db3)
    - [Custom provider](#custom-provider)
    - [Handle API errors](#handle-api-errors)
- [Blade directives](#blade-directives)
- [License](#license)

Compatibility
-------------

[](#compatibility)

- This package has been tested with **Laravel 5.8, 6.x and 7.x**.
- It works with all the session drivers supported by Laravel, except of course the cookie driver which saves the sessions only in the client browser and the array driver.
- To track API tokens, it supports the official **Laravel Passport (&gt;= 7.5)** and **Laravel Sanctum (v2)** packages.
- In case you want to use Passport with multiple user providers, this package works with the `sfelix-martins/passport-multiauth` package (see [here](https://github.com/sfelix-martins/passport-multiauth)).

Installation
------------

[](#installation)

Install the package with composer:

```
composer require alshahari/laravel-auth-tracker
```

Publish the configuration file (`config/auth_tracker.php`) with:

```
php artisan vendor:publish --provider="Alshahari\AuthTracker\AuthTrackerServiceProvider" --tag="config"
```

### Create the logins table

[](#create-the-logins-table)

Before running the migrations, you can change the name of the table that will be used to save the logins (named by default `logins`) with the `table_name` option of the configuration file.

Launch the database migrations to create the required table:

```
php artisan migrate
```

### Prepare your authenticatable models

[](#prepare-your-authenticatable-models)

In order to track the logins of your app's users, add the `Alshahari\AuthTracker\Traits\AuthTracking` trait on each of your authenticatable models that you want to track:

```
use Alshahari\AuthTracker\Traits\AuthTracking;
use Illuminate\Foundation\Auth\User as Authenticatable;
// ...

class User extends Authenticatable
{
    use AuthTracking;

    // ...
}
```

### Prepare your LoginController

[](#prepare-your-logincontroller)

Replace the `Illuminate\Foundation\Auth\AuthenticatesUsers` trait of your `App\Http\Controllers\Auth\LoginController`by the `Alshahari\AuthTracker\Traits\AuthenticatesWithTracking` trait provided by this package.

This trait overrides the `sendLoginResponse` method by removing the session regeneration. But don't worry, there's no security issue here. Instead, this package do the session regeneration in an event listener on the login event (before saving the informations of the new login). Because of the `sendLoginResponse` regenerating the session ID after the login event has been dispatched, this approach allows to get the right session ID generated by a new login.

### Choose and install a user-agent parser

[](#choose-and-install-a-user-agent-parser)

This package relies on a User-Agent parser to extract the informations.

Currently, it supports two of the most popular parsers:

- WhichBrowser ()
- Agent ()

Before using the Auth Tracker, you need to choose a supported parser, install it and indicate in the configuration file which one you want to use.

### Configure the user provider

[](#configure-the-user-provider)

This package comes with a modified Eloquent user provider that retrieve remembered users from the logins table instead of the users table.

In your `config/auth.php` configuration file, use the `eloquent-tracked` driver in the user providers list for the users you want to track:

```
'providers' => [
    'users' => [
        'driver' => 'eloquent-tracked',
        'model' => App\User::class,
    ],

    // ...
],
```

### Generate the scaffolding

[](#generate-the-scaffolding)

This step is optional but can help you getting started by generating the scaffolding of the Auth Tracker.

Launch this command:

```
php artisan tracker:install
```

This command will:

- publish the controller `AuthTrackingController` in `app/Http/Controllers/Auth`
- publish the view `list.blade.php` in `resources/views/auth`
- add routes in `routes/web.php` via the `Route::authTracker()` macro (see all the available [routes](#routes))

Now, log in with a tracked user and go to `/security`. You will find a page to manage the logins!

### Laravel Sanctum

[](#laravel-sanctum)

In the actual version (2.1.0) of the Laravel Sanctum package, there is no event allowing us to know when an API token is created.

If you are issuing API tokens with Laravel Sanctum and want to enable auth tracking, you will have to dispatch an event provided by the Auth Tracker.

Dispatch the `Alshahari\AuthTracker\Events\PersonalAccessTokenCreated` event passing the personal access token newly created by the `createToken` method of the Laravel Sanctum trait.

Based on the [example](https://laravel.com/docs/7.x/sanctum#issuing-mobile-api-tokens) provided by the Laravel Sanctum documentation, it might look like this:

```
use Alshahari\AuthTracker\Events\PersonalAccessTokenCreated;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

Route::post('/sanctum/token', function (Request $request) {
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
        'device_name' => 'required'
    ]);

    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }

    $newAccessToken = $user->createToken($request->device_name);

    event(new PersonalAccessTokenCreated($newAccessToken)); // Dispatch here the event

    return $newAccessToken->plainTextToken;
});
```

Usage
-----

[](#usage)

The `AuthTracking` trait provided by this package surcharge your users models with methods to list their logins and to give you full individual control on them.

### Retrieving the logins

[](#retrieving-the-logins)

#### Get all the logins

[](#get-all-the-logins)

```
$logins = request()->user()->logins;
```

#### Get the current login

[](#get-the-current-login)

```
$login = request()->user()->currentLogin();
```

### Check for the current login

[](#check-for-the-current-login)

Each login instance comes with a dynamic `is_current` attribute. It's a boolean that indicates if the login instance is the current login.

### Revoking logins

[](#revoking-logins)

#### Revoke a specific login

[](#revoke-a-specific-login)

To revoke a specific login, use the `logout` method with the ID of the login you want to revoke. If no parameter is given, the current login will be revoked.

```
request()->user()->logout(1); // Revoke the login where id=1
```

```
request()->user()->logout(); // Revoke the current login
```

#### Revoke all the logins

[](#revoke-all-the-logins)

We can destroy all the sessions and revoke all the Passport tokens by using the `logoutAll` method. Useful when, for example, the user's password is modified and we want to logout all the devices.

This feature destroys all sessions, even those remembered.

```
request()->user()->logoutAll();
```

#### Revoke all the logins except the current one

[](#revoke-all-the-logins-except-the-current-one)

The `logoutOthers` method acts in the same way as the `logoutAll` method except that it keeps the current session / Passport token alive.

```
request()->user()->logoutOthers();
```

Routes
------

[](#routes)

Here are the routes added by the scaffolding command:

```
Route::prefix($prefix)->group(function () {

    // Route to manage logins
    Route::get('/', 'Auth\AuthTrackingController@listLogins')->name('login.list');

    // Logout routes
    Route::middleware('auth')->group(function () {
        Route::post('logout/all', 'Auth\AuthTrackingController@logoutAll')->name('logout.all');
        Route::post('logout/others', 'Auth\AuthTrackingController@logoutOthers')->name('logout.others');
        Route::post('logout/{id}', 'Auth\AuthTrackingController@logoutById')->where('id', '[0-9]+')->name('logout.id');
    });
});
```

Events
------

[](#events)

### Login

[](#login)

On a new login, you can listen to the event `Alshahari\AuthTracker\Events\Login`. It receives a `RequestContext` object containing all the informations collected on the request, accessible on the event with the `context` property.

Properties available:

```
$this->context->userAgent; // The full, unparsed, User-Agent header
$this->context->ip; // The IP address
```

Methods available:

```
$this->context->parser(); // Returns the parser used to parse the User-Agent header
$this->context->ip(); // Returns the IP address lookup provider
```

Methods available in the parser:

```
$this->context->parser()->getDevice(); // The name of the device (MacBook...)
$this->context->parser()->getDeviceType(); // The type of the device (desktop, mobile, tablet, phone...)
$this->context->parser()->getPlatform(); // The name of the platform (macOS...)
$this->context->parser()->getBrowser(); // The name of the browser (Chrome...)
```

Methods available in the IP address lookup provider:

```
$this->context->ip()->getCountry(); // The name of the country
$this->context->ip()->getRegion(); // The name of the region
$this->context->ip()->getCity(); // The name of the city
$this->context->ip()->getResult(); // The entire result of the API call as a Laravel collection

// And all your custom methods in the case of a custom provider
```

IP address lookup
-----------------

[](#ip-address-lookup)

By default, the Auth Tracker collects the IP address and the informations given by the User-Agent header.

But you can go even further and collect other informations about the IP address, like the geolocation.

To do so, you first have to enable the IP lookup feature in the configuration file.

This package comes with two officially supported providers for IP address lookup (see the IP Address Lookup section in the `config/auth_tracker.php` configuration file).

### Ip2Location Lite DB3

[](#ip2location-lite-db3)

This package officially support the IP address geolocation with the Ip2Location Lite DB3.

Here are the steps to enable and use it:

- Download the current version of the database and import it in your database as explained in the documentation:
- Set the name of the `ip_lookup.provider` option to `ip2location-lite` in the `config/auth_tracker.php` configuration file
- Indicate the name of the tables used in your database for IPv4 and IPv6 in the `config/auth_tracker.php` configuration file (by default it uses the same names as the documentation: `ip2location_db3` and `ip2location_db3_ipv6`)

### Custom provider

[](#custom-provider)

You can add your own providers by creating a class that implements the `Alshahari\AuthTracker\Interfaces\IpProvider` interface and use the `Alshahari\AuthTracker\Traits\MakesApiCalls` trait.

Your custom class have to be registered in the `custom_providers` array of the configuration file.

Let's see an example of an IP lookup provider with the built-in `IpApi` provider:

```
use Alshahari\AuthTracker\Interfaces\IpProvider;
use Alshahari\AuthTracker\Traits\MakesApiCalls;
use GuzzleHttp\Psr7\Request;

class IpApi implements IpProvider
{
    use MakesApiCalls;

    /**
     * Get the Guzzle request.
     *
     * @return Request
     */
    public function getRequest()
    {
        return new Request('GET', 'http://ip-api.com/json/'.request()->ip().'?fields=25');
    }

    /**
     * Get the country name.
     *
     * @return string
     */
    public function getCountry()
    {
        return $this->result->get('country');
    }

    /**
     * Get the region name.
     *
     * @return string
     */
    public function getRegion()
    {
        return $this->result->get('regionName');
    }

    /**
     * Get the city name.
     *
     * @return string
     */
    public function getCity()
    {
        return $this->result->get('city');
    }
}
```

As you can see, the class have a `getRequest` method that must return a `GuzzleHttp\Psr7\Request` instance.

Guzzle utilizes PSR-7 as the HTTP message interface. Check its documentation:

The `IpProvider` interface comes with required methods related to the geolocation. All keys of the API response are accessible in your provider via `$this->result`, which is a Laravel collection.

If you want to collect other informations, you can add a `getCustomData` method in your custom provider. This custom data will be saved in the logins table in the `ip_data` JSON column. Let's see an example of additional data:

```
public function getCustomData()
{
    return [
        'country_code' => $this->result->get('countryCode'),
        'latitude' => $this->result->get('lat'),
        'longitude' => $this->result->get('lon'),
        'timezone' => $this->result->get('timezone'),
        'isp_name' => $this->result->get('isp'),
    ];
}
```

### Handle API errors

[](#handle-api-errors)

In case of an exception throwed during the API call of your IP address lookup provider, the FailedApiCall event is fired by this package.

This event has an exception attribute containing the GuzzleHttp\\Exception\\TransferException (see [Guzzle documentation](http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions)).

You can listen to this event to add your own logic.

Blade directives
----------------

[](#blade-directives)

Check if the auth tracking is enabled for the current user:

```
@tracked
    Security
@endtracked
```

Check if the IP lookup feature is enabled:

```
@ipLookup
    {{ $login->location }}
@endipLookup
```

License
-------

[](#license)

Open source, licensed under the [MIT license](LICENSE).

###  Health Score

29

—

LowBetter than 57% of packages

Maintenance52

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

387d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/77795241aca86b1eaf1d0ddf25b09bc7f6a53e18109b093bafbb1f6311ea9140?d=identicon)[abobakerMohsan](/maintainers/abobakerMohsan)

---

Top Contributors

[![abobakeralshahari](https://avatars.githubusercontent.com/u/42132849?v=4)](https://github.com/abobakeralshahari "abobakeralshahari (9 commits)")

---

Tags

authauth-trackerdevices-loginlaravelloginsession

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/alshahari-laravel-auth-tracker/health.svg)

```
[![Health](https://phpackages.com/badges/alshahari-laravel-auth-tracker/health.svg)](https://phpackages.com/packages/alshahari-laravel-auth-tracker)
```

###  Alternatives

[kartik-v/yii2-password

Useful password strength validation utilities for Yii Framework 2.0

761.3M17](/packages/kartik-v-yii2-password)[vitalybaev/laravel5-dkim

Laravel 5/6 package for signing outgoing messages with DKIM.

3163.1k](/packages/vitalybaev-laravel5-dkim)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
