Skip to content

Instantly share code, notes, and snippets.

@imam932
Created November 17, 2020 17:59
Show Gist options
  • Save imam932/a3fae2fd7af2315780e369cdea5fed40 to your computer and use it in GitHub Desktop.
Save imam932/a3fae2fd7af2315780e369cdea5fed40 to your computer and use it in GitHub Desktop.
Limit one session per user in Laravel 5
- nambah field sessionid di table user
$ php artisan make:migration add_session_id_to_users_table --table=users
- lakukan migration
$ php artisan migrate
- method sendLoginResponse() ini akan mereplace method yang ada di trait “AuthenticatesUsers”
- tambahkan library berikut
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
- tambahkan method sendLoginResponse() di Http>ontroller>Auth>LoginController.php
-coba tes sekarang(tes nya harus beda device ya :)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddSessionIdToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->text('session_id')
->after('remember_token')
->nullable()
->default(null)
->comment('Stores the id of the user session');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('session_id');
});
}
}
/**
* Send the response after the user was authenticated.
* Remove the other sessions of this user
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$previous_session = Auth::User()->session_id;
if ($previous_session) {
Session::getHandler()->destroy($previous_session);
}
Auth::user()->session_id = Session::getId();
Auth::user()->save();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment