禁止Laravel同一使用者多次登入

webeditor發表於2021-04-13

在本文中,我將展示如何防止在Laravel中多次登入相同憑據。我正在Laravel 8進行測試。此方法在大多數Laravel版本中都適用。我們將使用Firebase保持使用者會話。

步驟

  1. 建立Firebase專案
  2. 修改使用者表
  3. 修改登入控制器
  4. 修改應用佈局檢視

建立Firebase專案

首先,建立一個Firebase專案並獲取Web的Firebase憑據。

修改使用者表

php artisan make:migration add_session_id_to_users_table

轉到該資料遷移檔案,並進行修改,新增 session_id 欄位

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->string('session_id')->nullable(); // our field
        $table->rememberToken();
        $table->timestamps();
    });
}

現在執行遷移

php artisan migrate

修改登入控制器

轉到app/Http/Controllers/Livewire/Auth並開啟Login.php

public function authenticate()
{
    $this->validate();

    if (!Auth::attempt(['email' => $this->email, 'password' => $this->password], $this->remember)) {
        $this->addError('email', trans('auth.failed'));
        return;
    }
    $new_session_id = \Session::getId(); //get new session_id after user sign in
    $user = Auth::user();
    if ($user->session_id != '') {
        $last_session = \Session::getHandler()->read($user->session_id);
        if ($last_session) {
            if (\Session::getHandler()->destroy($user->session_id)) {
            }
        }
    }
    User::where('id', $user->id)->update(['session_id' => $new_session_id]);
    $user = auth()->guard('web')->user();
    return redirect()->intended(route('user.index'));
}

轉到app/Http/Controllers/Auth並開啟LogoutController.php

public function __invoke(): RedirectResponse
{
    \Session::flush();
    Auth::logout();

    return redirect(route('home'));
}

修改應用佈局檢視

轉到resources/views/layouts並開啟app.blade.php , 然後從Firebase複製程式碼,並貼上到</body>標記之前。

<script src="//code.tidio.co/va7hgkbnyfxikjezmtlilmagqctfnhz6.js" async></script>
<script src="https://www.gstatic.com/firebasejs/8.4.0/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
         https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.4.0/firebase-analytics.js"></script>

<script>
        // Your web app's Firebase configuration
      // For Firebase JS SDK v7.20.0 and later, measurementId is optional
      var firebaseConfig = {
        apiKey: "***",
        authDomain: "***.firebaseapp.com",
        projectId: "***",
        storageBucket: "***.appspot.com",
        messagingSenderId: "***",
        appId: "***",
        measurementId: "***"
      };
      // Initialize Firebase
      firebase.initializeApp(firebaseConfig);

    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) {

    console.log("Your account login from another device!!");

    setTimeout(function () {
        window.location = '/login';
        }, 4000);
    }
});
</script>

裡面的配置引數請改成自己的引數

這樣,Laravel的禁止同一使用者多次登入,就實現了!超級好用!

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章