How to invalidate particular session in Laravel (with user using remember me feature)

廉价感情. 提交于 2019-12-22 10:49:25

问题


Using Laravel 5.1 & 'file' Session Driver,

I'm trying to provide facility to user to track their sessions and invalidate them anytime they wish by keeping a record of their session_id within the database. With Database, I mean, I maintain a table called user_sessions which associates user_id with their session_id (obtained by Session::getId()).

So, to invalidate Session, I tried the following code,

$sessionId = Session::getId();
Session::setId($sessionId);
Session::invalidate();

and it works perfectly fine, for the case where, where user does not uses Remember Me feature.

For the case where user uses Remember Me feature, this above code does not work, So, I additionally, tried setting remember_token field to null as specified here in this answer, but with this, all sessions of the user get destroyed including the current one.


回答1:


You can simply use

use Illuminate\Support\Facades\Session;

Session::forget('YOUR_SESSION_ID');

If you want to get the current session Id:

Session::driver()->getId();

I hope it helps




回答2:


Sessions are meant to be short-lived. If you want something a bit more permanent you can use some sort of a long term user settings table.

Create a table user_settings:

id (PK), user_id(FK users table), settings(BLOB?), created_at, updated_at

Add a model:

class UserSetting extends Model {
      public function user() {
            return $this->belongsTo(User::class);
      }
}

You can also associate the user with these via :

 class User extends Model {
 //...
     public function settings() {
         $this->hasMany(UserSetting::class);
     }
 }

You can then get all user sessions via:

 User::find($u)->settings();

When a user logs in regularly or automatically via a remember token a Login event is fired.

You can listen to this in your event service provider:

\Event::listen(\Illuminate\Auth\Events\Login::class, function ($event) {
       // Here you can load the last settings in the session if you want e.g. 
       session(['current_settings' => $event->user->settings()->latest()->value('id') ]); 
        // or you can just make a new entry: 
        $settings = new UserSettings();
        $event->user->settings()->save($settings);
        session(['current_settings' => $settings->id ]);
});

Note that you will have to manually persist things that need persisting instead of just putting them in the session.



来源:https://stackoverflow.com/questions/50147632/how-to-invalidate-particular-session-in-laravel-with-user-using-remember-me-fea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!