Restrict account multiple sessions

My system is current allowing users on difference machines to login in using the same user account at the same time, how can I tell the system to only allow one user account to be login at a time

To start with, you may need to add a plug to set remote_ip correctly based on headers (if you’re running Phoenix behind a load balancer or similar). for instance

Then you could cache whatever IP the user is logged in from on their profile, and reject access from different IPs until the user “logs out”.

Some gotchas:

  • what should happen if the user forgets to log out? This will happen
  • what about users behind carrier-grade NAT, VPNs, and similar systems that make many computers appear to have one IP address? This will happen
  • what about users on mobile devices that change IPs frequently as they move between cellular towers? If your application makes sense on mobile, this will happen
1 Like

I suppose you’re currently storing the entire session in a cookie, using Plug.Session.COOKIE. You’ll want to move to a stateful model where you store session information in the server, identified by a random session ID that is assigned during sign-in. The session cookie would then only store the session identifier, which is used to look up the session details.

This is generally a good idea anyway, as it allows the server to revoke the session on sign-out or after some time, reducing the risk of leaked/stolen cookies being used for session hijacking:

Of the 2 billion cookies extracted, 22 percent remained valid at the time of the discovery.

If you are absolutely sure you will only ever allow a single session per user you can store the session ID inside the user account table, and clear it on sign-out. If you want to be able to restrict the number of sessions to a configurable number, or you want to have a session activity log per user, you’d need a separate session table with a 1:N relationship from the user account.

2 Likes