views:

67

answers:

2

I have a web application in python wherein the user submits their email and password. These values are compared to values stored in a mysql database. If successful, the script generates a session id, stores it next to the email in the database and sets a cookie with the session id, with allows the user to interact with other parts of the sight.

When the user clicks logout, the script erases the session id from the database and deletes the cookie. The cookie expires after 5 hours. My concern is that if the user doesnt log out, and the cookie expires, the script will force him to login, but if he has copied the session id from before, it can still be validated.

How do i automatically delete the session id from the mysql database after 5 hours?

+1  A: 

You can encode the expiration time as part of your session id. Then when you validate the session id, you can also check if it has expired, and if so force the user to log-in again.

You can also clean your database periodically, removing expired sessions.

DanJ
A: 

You'd have to add a timestamp to the session ID in the database to know when it ran out.

Better, make the timestamp part of the session ID itself, eg.:

Set-Cookie: session=1272672000-(random_number);expires=Sat, 01-May-2010 00:00:00 GMT

so that your script can see just by looking at the number at the front whether it's still a valid session ID.

Better still, make both the expiry timestamp and the user ID part of the session ID, and make the bit at the end a cryptographic hash of the user ID, expiry time and a secret key. Then you can validate the ID and know which user it belongs to without having to store anything in the database. (Related PHP example.)

bobince