Managed Sessions
Loading "Intro to Man Sessions"
Run locally for transcripts
Cookies having a set expiration time that we can control is a great feature. But
consider the following scenario:
A Person we'll call Shaundai logs into the site
on a public computer at the library. She checks on her notes in the app and then
has to rush away to a meeting. An hour later she remembers that she did close
the browser window, but she's not sure if she logged out. She doesn't have time
to go back to the library to make sure and she's worried someone will be able to
access her account.
Unfortunately, there's simply no way possible currently for us to offer
Shaundai a solution. We can't delete her cookie because we don't have it... The
browser at the library does. There's just no way to proactively logout of a
session on another computer.
This is where managed sessions comes in. It's actually pretty simple. We create
a new database model called "session" which has an expiration time, and id, and
a user ID. When a user logs in, we create a new session record for them in the
database and instead of putting the user's ID in the cookie, we put the session
ID. When the user makes a request, we use that to find the user attached to the
(unexpired) session.
Then we can offer Shaundai a special page that lists all of her active sessions
and allows her to delete them. If she's worried about someone accessing her
account, she can delete the session from the library and the next time someone
tries to access her account from that computer, they'll be logged out.
Some apps even store the IP address of the session so users can use that to help
them identify which session to delete.
Note: when you query the database for the session, make sure you filter out
expired sessions. You can also add cron job that deletes expired sessions on a
regular basis which can help prevent the database from getting unnecessarily
large.