Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Logout Specific User

Tags:

php

session

yii2

How can I tell yii2 to logged out specific user who has login to system?

Let say, there is 2 user is logged in on system, userA and userB.

How can I specified logged out userB?

What I know is userB has to trigger this command to logout.

Yii::$app->user->logout();
return $this->goHome();

But maybe we can use some command like Yii::$app->user->logout('userB');?

Or is it has some other way?

like image 732
24 revs, 19 users 31% Avatar asked Dec 10 '15 17:12

24 revs, 19 users 31%


1 Answers

Well, the problem is about how to kill all sessions of the user.

Flag user to force relogin

You can add an additional column force_relogin to User identity class and set it to true when you need to logout someone:

$user = User::findByLogin('userB');
$user->force_logout = 1;
$user->save();

Then add the event handler beforeLogin() on user component like so:

'user' => [
    'class' => 'yii\web\User',
    'on beforeLogin' => function ($event) {
        if ($event->identity->force_logout && $event->cookieBased) {
            $event->isValid = false;
        }
    },
    'on afterLogin' => function ($event) {
        if ($event->identity->force_logout) {
            $event->identity->force_logout = false;
            $event->identity->save();
        }
    }
]

Check, whether $cookieBased and $identity->force_logout are so on...

But that's a bad idea, because the user may have more than one session (logged in in different browsers)

Store list user's sessions in DB

Create table user_sessions with user_id and session_id columns and save each session, you open for that user in the DB. That you can find all sessions of the user and drop them one by one. Something like: (code is not tested, just as an idea)

$sessionId = Yii::$app->session->getId();
session_commit();
foreach (UserSessions::findByUserLogin('userB') as $session) {
   session_id($session->id);
   session_start();
   session_destroy();
   session_commit();
}

session_id($sessionId); // Restore original session
session_start();
session_commit();

The idea is weak because you always should take care about consistence of sessions on the server and in the DB.

Store sessions in DB

Store sessions is the database, as described in the Yii2 Guide for Session handling

Then you can just find session in the DB and delete it directly. You shouldn't take care about the consistence and session rotation, because DB is the only place, where the sessions are being stored. As a free bonus you get a non-blocking work with sessions.

like image 154
SilverFire Avatar answered Sep 16 '22 12:09

SilverFire