Prevent Block Multiple Logins Of Same Credentials in Laravel 5.7

In this blog, we learn how to prevent block multiple logins of same credentials in Laravel 5.7.

For the security reasons or some other reason, we can block multiple logins of same credentials in Laravel 5.7. this function is mostly used in applications. This amazing functionality we will do using Laravel session token key and google firebase.

When someone uses Laravel application and login with that in one PC than another login user automatic log out without page refresh.

Step:1 Create a new Laravel 5.7 Project 

composer create-project --prefer-dist laravel/laravel LaraLogin

Or

laravel new LaraLogin

After that run this following command to generate  Laravel auth files.

php artisan make:auth

We get two migration in the database folder. in users, migration table add one extra filed. if you already migrate users table then you need to add one extra field in the user table.

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('session_id');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

After that migrate table in the database using this following command.

php artisan migrate

In your Laravel application folder, LoginController.php and some other files created automatically. We use LoginController.php file. because all login methods are created in this file.

Edit app/Http/Controllers/Auth/LoginController.php  file.

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use DB;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required',
            'password' => 'required',
        ]);

        $user = \DB::table('users')->where('email', $request->input('email'))->first();

        if (auth()->guard('web')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {

            $new_sessid   = \Session::getId(); //get new session_id after user sign in

            if($user->session_id != '') {
                $last_session = \Session::getHandler()->read($user->session_id); 

                if ($last_session) {
                    if (\Session::getHandler()->destroy($user->session_id)) {
                        
                    }
                }
            }

            \DB::table('users')->where('id', $user->id)->update(['session_id' => $new_sessid]);
            
            $user = auth()->guard('web')->user();
            
            return redirect($this->redirectTo);
        }   
        \Session::put('login_error', 'Your email and password wrong!!');
        return back();

    }

    public function logout(Request $request)
    {
        \Session::flush();
        \Session::put('success','you are logout Successfully');
        return redirect()->to('/login');
    }
}

After that, we use google firebase code in the resources/views/layouts/app.blade.php file. this code will handle when others user logins with the same credentials then first account logout automatic without page refresh.

We Simply add following javascript google firebase code into the bottom of your app.blade.php file.

<script src=//www.gstatic.com/firebasejs/4.9.1/firebase.js></script>
<script type=text/javascript>
var session_id = "{!! (Session::getId())?Session::getId():'' !!}";
var user_id = "{!! (Auth::user())?Auth::user()->id:'' !!}";

// Initialize Firebase
var config = {
    apiKey: "firebase.api_key",
    authDomain: "firebase.auth_domain",
    databaseURL: "firebase.database_url",
    storageBucket: "firebase.storage_bucket",
};
firebase.initializeApp(config);

var database = firebase.database();

if({!! Auth::user() !!}) {
    firebase.database().ref('/users/' + user_id + '/session_id').set(session_id);
}

firebase.database().ref('/users/' + user_id).on('value', function(snapshot2) {
    var v = snapshot2.val();

    if(v.session_id != session_id) {
        toastr.warning('Your account login from another device!!', 'Warning Alert', {timeOut: 3000});
        setTimeout(function() {
           window.location = '/login';
        }, 4000);
    } 
});
</script>

Now, time to serve our application so run this following command to quick run.

php artisan serve

Now you can open this URL on your browser.

//localhost:8000/login

So, here we completed our tutorial Prevent Block Multiple Logins Of Same Credentials in Laravel 5.7