Laravel: Only allowing one session per user at a time
Yeah, I did similar for my project.
So, you need add to your user model another attribute in this case: last_sessid.
public function swapping($user) {
$new_sessid = \Session::getId(); //get new session_id after user sign in
$last_session = \Session::getHandler()->read($user->last_sessid); // retrive last session
if ($last_session) {
if (\Session::getHandler()->destroy($user->last_sessid)) {
// session was destroyed
}
}
$user->last_sessid = $new_sessid;
$user->save();
}
Now, if the user has an active session, and signs in another browser, the first session will be removed.
P.S. Sorry for my bad english :)
For laravel 5.2 after executing the make:auth
command you can create the method:public function authenticated(Request $request,User $user)
in the AuthController.php and in that method you can do what you want after login.
For a single session per user we add to the AuthController at top:
use Illuminate\Http\Request;
use Auth;
And add the function:
public function authenticated(Request $request,User $user){
$previous_session = $user->session_id;
if ($previous_session) {
\Session::getHandler()->destroy($previous_session);
}
Auth::user()->session_id = \Session::getId();
Auth::user()->save();
return redirect()->intended($this->redirectPath());
}
Remember to add the migration for altering your users table with the session_id column.