1

Is there a way to prevent the same user having multiple concurrent active sessions? Specifically if a user has logged into Craft's CP in one browser, but logs in on other browser/device, can we automatically invalidate the previous session and log the user out?

I've checked through the General Config Settings in the docs and can't find anything that would enable this behaviour.

1 Answer 1

2

There's no built-in Craft functionality to restrict concurrent logins at present.

When I've needed to implement this functionality, I've built a module to prevent concurrent logins which listens to the EVENT_BEFORE_LOGIN event and checks in a custom table for an active login record for the user. If there's fewer records than the desired limit for concurrent logins, a new session record is added to the custom table and the user can log in successfully.

If there's more than the desired limit for concurrent logins for that user in the table, it sends an email alert to the user to let them know they've reached the limit for concurrent logins, removes all of their login records from the custom table and logs them out of all of their previous sessions by deleting their records from the Craft sessions table using the following command:

Craft::$app->getDb()->createCommand()
    ->delete(Table::SESSIONS, [
        'userId' => $userId,
    ])
    ->execute();

This was developed to mitigate login sharing amongst users, so it always allows the current login session to continue but removes all others if the current login session breaches the desired concurrent logins limit. This means that the user logging in is never blocked from accessing the site/CP but anyone else who might be piggy-backing onto their user account at the same time is logged out automatically.

If it helps, I can post some more code here to get you started if you want to follow a similar route.

3
  • That's okay, thanks Martin that's super helpful. Sounds like your Module would make a very useful plugin! Commented Aug 24, 2022 at 13:37
  • 1
    It's crossed my mind to turn it into a proper plugin. One day when I have a bit more time to tidy it up, perhaps! Glad I could help. Commented Aug 24, 2022 at 15:34
  • I need this functionality for a client. Do you know if a plugin exists? Or are you able to share more code? Commented Jun 18, 2024 at 15:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.