I\'m trying to implement a user policy whereby only one user can login at a time. I\'m trying to build this on top of Laravel\'s Auth driver.
I\'ve thought of using
my solution was extended from @Albin N for Laravel 5.* onward
add "last_session" column into table users
make sure you allow this column is fill-able by adding "last_session" into $fillable on User model (User.php)
protected $fillable = [
'name', 'email', 'password','last_session'
];
add authenticated() function into App/Http/Controllers/Auth/LoginController.php if you can't find it just make sure you have run php artisan make:auth
protected function authenticated()
{
// Update last_session after logged-in
User::find(Auth::id())->update(['last_session'=>Session::getId()]);
}
create new middleware class php artisan make:middleware SingleSession
if(Auth::check())
{
// If current session id is not same with last_session column
if(Auth::user()->last_session != Session::getId())
{
// do logout
Auth::logout();
// Redirecto login page
return Redirect::to('login');
}
}
finally call you SingleSession middleware class in kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\SingleSession::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
it will check every time before routes are being executed that's it! happy coding..!