Yii2 Logout Specific User

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.

Tags:

Php

Session

Yii2