Single Session Login in Laravel

后端 未结 6 1596
囚心锁ツ
囚心锁ツ 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 05:47

    What i did in Laravel 5.7 is similar to Somwang's solution, however this will keep the newly logged in user active and logout the old user.

    Start with creating a middleware class:

    php artisan make:middleware CheckSingleSession
    

    Add the following:

    use Illuminate\Support\Facades\Session;
    use Illuminate\Support\Facades\Auth;
    

    And write out the handle like this:

    public function handle($request, Closure $next)
    {
    
        $previous_session = Auth::User()->session_id;
        if ($previous_session !== Session::getId()) {
    
            Session::getHandler()->destroy($previous_session);
    
            $request->session()->regenerate();
            Auth::user()->session_id = Session::getId();
    
            Auth::user()->save();
        }
        return $next($request);
    }
    

    Make sure you also add it in your users migration file:

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('firstName');
        $table->string('lastName');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->string('session_id')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
    

    Then you should be able to add it to your routeMiddleware in the Kernel: project\app\Http\Kernel.php

    'checksinglesession' => \App\Http\Middleware\CheckSingleSession::class,
    

    (make sure you check the comma's)

    And we are done, now you can use it as route middleware. This way there is an active check on single sessions.

    Route::group(['middleware' => ['auth' ,'checksinglesession'], 'prefix' => 'app'], function () {
        Route::get('/dashboard', 'DashboardController@index')->name('dashboard.index');
    });
    

提交回复
热议问题