I’m building a session timeout feature to a LiveView app and I’m looking for some feedback. Basically it’s a modal that pops out telling the user they will be logged out after 5 minutes (with a button to stay logged in). I’m rendering a SessionTimeoutModal LiveView in app.html.heex which ticks every few seconds and checks a session_token_expires_at timestamp against current time. The issue I’m having is when it’s actually time to log the user out automatically. I’ve thought about and tried out the following:
Deleting the token from database in LiveView (but then the browser session doesn’t get cleared? Also can’t add a “You’ve been logged out automatically” flash notification)
Pushing a JS event which fetches the logout route (seems gimmicky and requires CORS stuff)
Redirecting to /logout from LiveView (can’t redirect to a DELETE route)
Redirecting to a new GET /logout or GET /auto_logout (GET shouldn’t modify stuff, but should I care?)
Option 4 seems to work, I just thought I’d ask how people tend to solve this since this is a fairly common feature.
Delete the token in the db (that’s why it’s in the db in the first place) and use Security considerations — Phoenix LiveView v1.0.9 to make sure any persistent connections are dropped. On reconnect the token of those connections would be invalid.
Yeah either way, I am deleting the token. I just thought it would be nice to use the same logout method as when manually logging out. I guess I’ll try to go with deleting the token in LiveView, broadcasting the “disconnect” event and redirecting with a flash message. Thanks for your input
Surprisingly it is possible to hit that route using a GET+params (/logout?method=DELETE) because the standard router has a plug that converts such params into the proper request method, thus hitting the desired logout controller.
(I’ve had to do it before)
On mobile now, let me know if you need more details.
In this particular case, I suppose the CSRF token can be pulled out from the meta tag or session and passed as a param too, _csrf_token according to Plug.CSRFProtection docs.
If there’s a manual logout action in the UI, you could add some javascript to support an event pushed from the server that invokes the same action, perhaps with a parameter indicating that this was an auto-logout. That way you’re in control for longer than if you just redirect, and the logout action is re-used.
You cannot depend on the client cooperating for something like a forced logout. There might be optional stuff done to make the logout a better experience, but eventually the logout needs to be driven by server side controlled mechanisms.
Well a user script or browser extension could prod the server to prevent forced logout due to inactivity, so for this sort of thing a degree of client cooperation is involved anyway. However I take your point, there should always be a way to force log out a user from the server in an orderly way.