I am using Laravel 8 and Jetstream. As I can see my user can login to my website from multiple devices and access the contents. So I want to stop them. If a user is successfully logged in to a second device then they will logout from the first device. In short- users can access my content from one device at a time. No multiple device login. In my earlier project with Laravel Breeze I have done it easily because the controller is present there. In Laravel Jetstream I am confused. Anyone, please suggest.
--- Update ------
Tried this but had no luck. Still, my user can login from two different devices
In FortifyServiceProvider:
public function boot()
{
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->email.$request->ip());
});
RateLimiter::for('two-factor', function (Request $request) {
return Limit::perMinute(5)->by($request->session()->get('login.id'));
});
//This is what I added
Fortify::authenticateUsing(function (Request $request) {
$user = User::where('email', $request->email)->first();
if ($user &&
Hash::check($request->password, $user->password)) {
auth()->logoutOtherDevices($request->password);
return $user;
}
});
}
I have tried many other methods and finally, I came to the conclusion that "logoutOtherDevices
" will never work if you are using Laravel Jetstream. It may work if you apply non-standard hacks which I don't want.
So in my case, I tackled it in my way. After a user successfully logged in, they were redirected to their dashboard page. In the dashboard controller, I check the session table (in the database) and remove users' session records skipping the session of their current device.
Anyone facing such a problem can use my 100% working method. This is the example -
$this_device_session = \Session::getId(); //user's current session id is stored
//check in sessions table. If record exist then delete it skipping the current session.
if(DB::table('sessions')->where('id','!=',$this_device_session)->where('user_id',Auth::user()->id)->exists()) {
//delete their session
DB::table('sessions')->where('id','!=',$this_device_session)->where('user_id',Auth::user()->id)->delete();
}
return view('dashboard'); //user's dashboard page or any page you want