php laravel preventing multiple logins of a user from different devices/browser tabs at a given time

半腔热情 提交于 2021-02-04 21:33:54

问题


Does laravel provide a way to prevent multiple logins of a user from different devices / browsers at a given time? If yes then how can i force a user to logged in from a single device at a single time. I am developing a online quiz app using laravel 5.6 where users can logged in from a single place and take test.


回答1:


laravel provide this method to invalidating and "logging out" a user's sessions that are active on other devices logoutOtherDevices() to work with this method you need also to make sure that the

Illuminate\Session\Middleware\AuthenticateSession

middleware is present and un-commented in your app/Http/Kernel.php class' web middleware group:

'web' => [
    // ...
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    // ...
],

then you can use it like this

 use Illuminate\Support\Facades\Auth;
    
 Auth::logoutOtherDevices($password);



回答2:


Perhaps this should get you started:

Add a column in users_table.php

$table->boolean('is_logged_in')->default(false);

When a user logs in: LoginController.php

public function postLogin()
{
   // your validation

   // authentication check

   // if authenticated, update the is_logged_in attribute to true in users table
   auth()->user()->update(['is_logged_in' => true]);

   // redirect...
}

Now, whenever a user tries to login from another browser or device, it should check if that user is already logged in. So, again in LoginController.php

public function index()
{
    if (auth()->check() && auth()->user()->is_logged_in == true) {
        // your error logic or redirect
    }

    return view('path.to.login');
}

When a user logs out: LogoutController.php

public function logout()
{
    auth()->user()->update(['is_logged_in' => false]);

    auth()->logout();

    // redirect to login page...
}


来源:https://stackoverflow.com/questions/49938593/php-laravel-preventing-multiple-logins-of-a-user-from-different-devices-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!