skip to Main Content

Im trying to implement single device login, meaning that if a user is logged in another device and tries to log to a new device, than he will be logged out from the previous device,
for this end, after successful login i call the following method

Auth::logoutOtherDevices($request['password']);

while this works, after i log out and try to log in again, i get invalid credentials,
i tried to debug and see that Auth::validate($credentials) returns false, and that Hash::check($credentials['password'], $user->password) is also false

i know that internally the logoutOtherDevices rehashes the password and also noticed that if i provide wrong password, it throws exception, but i dont understand what im doing incorrectly, if it matters my session driver is redis

2

Answers


  1. Rather than re-hash the password, you can delete all the current sessions for the user, which effectively logs they out of every device.

    The following code checks if the app is running in production and then deletes all the sessions for the user $user:

    if (app()->environment('production')) {
        $sessions = Session::where('user_id', $user->id)->delete();
    }
    

    You might need to create a model called Session, and check that SESSION_DRIVER in the .env file is set to database. Also, check that you have a table called sessions in the database.

    For redis, I’m sure a similar approach would work. You would need to delete the user’s sessions from redis to log them out from every device.

    Login or Signup to reply.
  2. Jetsream uses something like this. you can do the same.

    use IlluminateContractsAuthStatefulGuard;
    
    public function destroy(Request $request, StatefulGuard $guard)
    {
       
        $guard->logoutOtherDevices($request->password);
    
        $this->deleteOtherSessionRecords($request);
    
        return back(303);
    }
    
    protected function deleteOtherSessionRecords(Request $request)
    {
        if (config('session.driver') !== 'database') {
            return;
        }
    
        DB::connection(config('session.connection'))->table(config('session.table', 'sessions'))
            ->where('user_id', $request->user()->getAuthIdentifier())
            ->where('id', '!=', $request->session()->getId())
            ->delete();
    }
    

    logoutOtherDevices : will rehash your password and send logout event for other devices
    deleteOtherSessionRecords : deletes session data for other devices

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search