Created
November 17, 2020 17:59
-
-
Save imam932/a3fae2fd7af2315780e369cdea5fed40 to your computer and use it in GitHub Desktop.
Limit one session per user in Laravel 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- 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 :) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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