I'm trying to figure out how to only allow one session per user. So if someone tries to log in when he already logged in his user account, the first session will be destroyed and will be logged out to allow the current session only.
I'm following this: How to keep single session per user in Laravel . But i don't know where I should put these lines of codes:
/**
* Swap a user session with a current one
*
* @param \App\User $user
* @return boolean
*/
protected function swapUserSession($user)
{
if (!($user instanceof \App\User)) {
return false;
}
$new_session_id = Session::getId(); //get new session_id after user sign in
$last_session = Session::getHandler()->read($user->last_session_id); // retrive last session
if ($last_session) {
Session::getHandler()->destroy($user->last_session_id);
}
$user->last_session_id = $new_session_id;
$user->save();
return true;
}
I'm currently using Laravel 5.1, so The only controller I can find for the Auth is AuthController.php but it says to put it on the LoginController.php
If you're running off of the latest laravel 5.3.15 or higher I would recommend checking out the following link I've posted about this issue I've ran into. Took me some time to figure out but I did and the fix is really simple.
First (assuming you've installed laravel 5.3 cleanly):
Get sessions table up and running-
Go to the session configuration file stored at config/session.php and scroll down to the driver configuration.
By default it should be set to 'file'.
Change this setting to 'database'. (Provided you want to store sessions in a database)
In your console, in the project directory, perform:
php artisan session:table
php artisan migrate
Then in the following link scroll down to the last comment and follow the steps to fix the session issue.
If you're using the file driver you can add the following method to App\Http\Controllers\Auth\AuthController.php (tested in Laravel 5.2)
/**
* Only allow one concurrent session per user
*
* @param Request $request
* @param User $user
* @return Response
*/
protected function authenticated(Request $request, User $user)
{
Session::put('user_id', $user->id);
$files = array_diff(scandir(storage_path('framework/sessions')), array('.', '..', '.gitignore'));
foreach ($files as $file) {
$filepath = storage_path('framework/sessions/' . $file);
$session = unserialize(file_get_contents($filepath));
if ($session['user_id'] === $user->id && $session['_token'] !== Session::get('_token')) {
unlink($filepath);
}
}
return redirect()->intended($this->redirectPath());
}