Efficient way to detect user session is invalid, and log out the user

Hi guys, I’m just in the process of building a 2FA system for the first time and I could use your advice. I want to stop users from logging in on multiple devices simultaneously - so I want to save the User’s IP address. When a successful login is made with a new device, I want the server to invalidate the previous session and boot the user off / destroy the session.

However, I’m struggling to think of an efficient way to do this. I don’t want to add a check for whether the User’s session is valid on every single action… Does anyone know of a better way to detect that the current session is invalid and boot the user?

I don’t want to add a check for whether the User’s session is valid on every single action…

Don’t you sort of have to do this anyway? I.E. every request you want to ensure if they say they are John Doe they actually are?

What I would do is:

  • When someone logins in generate a random value.
  • Store that value with the user
  • Store it with the session
  • On every action read the value from the session to make sure it matches the value stored for the user.

This way if computer A logins in, the computer B logins in, the session on computer A will no longer match the value stored with the user which was updated when computer B logged in.

If you’re really concerned about performance store it in something like Redis rather than the RDBMS.