Prevent multiple User "usage"

Hello!

I am trying to prevent multiple logins with the same user (e.g. user sharing).

To solve this problem i attached a column to my users table “session_id” (nullable, FK to sessions table) which will be filled after login.

if($this->UserUtil->hasActiveSession(($user['id']))) {
                    $this->Flash->error(_('Der Benutzer ist bereits angemeldet!'));
                } else {
                    $this->Auth->setUser($user);

                    $this->request->session()->delete('user.active_channel');

                    $this->UserUtil->setSession($user['id'], $this->request->session()->id());


                    return $this->setAction('dashboard');
                }

Using an custom SessionHandler (extend DatabaseSession) I extended the “destroy” function to clear the session_id field on an users entry:

// Destroy a session.
public function destroy($id)
{
    $usersTable = TableRegistry::get('users');
    $users = $usersTable->find()->where(['session_id' => $id]);

    if($users->count() > 0) {
        foreach($users as $user) {

            $user->session_id = null;
            $usersTable->save($user);

        }
    }

    return parent::destroy($id);
}

This solution works fine except the first request after login --> i am getting an FK violation error. Somehow i refresh the early sent request, the session_id will be correctly stored in the users entry.

I dont have an idea where the problem lies, do you?

Hi, I would suggest to enable query logging in the Datasource configuration (app.php) and check the sequence of the queries generated to be able to debug the specific fk violation error. Bin your log here if you get stuck to take a look… Thanks,

thanks for your answer. i figured out that there is a session_id regeneration after sign in? dont know where is the right point to insert it to my users table. i have finally decided to remove the FK check in users table on the session_id column. it may be a bad workaround, but it works fine.

solved