Search code examples
laravellaravel-5.4laravel-authorization

Prevent an already logged-in user to login in different machine


So I'm trying to prevent an already logged-in user to log-in in different browser or another computer. I'm thinking that I need to add an IP Address restriction, but I'm not sure how is that gonna work.

Here is my create_users_table.php migration file

Schema::create('users', function (Blueprint $table) {
     $table->increments('id');
     $table->string('name');
     $table->string('username')->unique();
     $table->string('email')->unique();
     $table->string('password');
     $table->timestamp('last_login');
     $table->boolean('isActive')->default(true);
     $table->rememberToken();
     $table->timestamps();
});

I'm also thinking that I need to create a restriction inside RedirectIfAuthenticated Middleware class.

So, here is my RedirectIfAuthenticated.php class

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
         return redirect('/');
    }

    return $next($request);
}

What is the optimal solution for that, and prevent an already logged-in user from logging-in from another computer? Thanks in advance !!!


Solution

  • The solution was to set the session value when a user logs in. Then I had a small class checking if the session ID stored is the same as the current user who is logged in.

    If the user logs in from somewhere else the session ID in the DB will update and the "older" user will be logged out.

    I didn't alter the Auth driver or anything, just put it on top when the user logs in. Below happens when login is successful:

    $user->last_session = session_id();
    $user->save();
    

    To check if the session is valid I used below

    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
          if(session_id() != Auth::user()->last_session){
            Auth::logout();
            return redirect('login');
          }
    
         return redirect('/');
    
        }
    
        return $next($request);
    }
    

    Reference This Link.