Single Session Login in Laravel

后端 未结 6 1586
囚心锁ツ
囚心锁ツ 2020-12-03 05:35

I\'m trying to implement a user policy whereby only one user can login at a time. I\'m trying to build this on top of Laravel\'s Auth driver.

I\'ve thought of using

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 06:11

    my solution was extended from @Albin N for Laravel 5.* onward

    add "last_session" column into table users

    make sure you allow this column is fill-able by adding "last_session" into $fillable on User model (User.php)

    protected $fillable = [
        'name', 'email', 'password','last_session'
    ];
    

    add authenticated() function into App/Http/Controllers/Auth/LoginController.php if you can't find it just make sure you have run php artisan make:auth

    protected function authenticated()
    {
        // Update last_session after logged-in
        User::find(Auth::id())->update(['last_session'=>Session::getId()]);
    }
    

    create new middleware class php artisan make:middleware SingleSession

    if(Auth::check())
    {
       // If current session id is not same with last_session column
       if(Auth::user()->last_session != Session::getId())
       {
          // do logout
          Auth::logout();
    
          // Redirecto login page
         return Redirect::to('login');
       }
    }
    

    finally call you SingleSession middleware class in kernel.php

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\SingleSession::class,
        ],
    
        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
    

    it will check every time before routes are being executed that's it! happy coding..!

提交回复
热议问题