Skip to content

Simple Session Management With Google’s App Engine

by Jason on September 28th, 2010

The Problem
I have a simple site, www.radstuff.com, that requires a login to view all kinds of rad stuff. I don’t want anyone to enter www.radstuff.com/privatedata to view any private data. Also, I want to know when a user logs in what kind of user they are (admin, regular, manager, etc).

The Solution
Gaeutilities’ Session is pretty sophisticated. It generates 3 tokens at a time (for async requests some pages may make) and stores them as a list in both the gae’s datastore and cache. Every time you instantiate it, it will automatically generate tokens and assign one to the cookie and update the cache and datastore with the new tokens. Tokens are valid for 5 seconds after which they will be re-generated again.

I found all of this a bit more than I needed, and immediately began to pair it down so that it would suit my needs. One of the things I found was the class function check_token that checked if a token was still valid (ie. exists, hasn’t expired). With this I created a session StringProperty in my user model so that when a user logs in, I would use gaeutilities to generate a session token and save it in my user model. Because gaeutilities automatically creates a cookie with the session token in it, the next time a user requests data from my app, I check the cookie’s session token and see if it exists in any of the user records. If it doesn’t, the user gets redirected to the login page. If a user record exists with that session token in it, I create a new token, update the cookie and the user’s session token in the datastore and allow them to view the requested page.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • RSS
  • StumbleUpon
  • Twitter

From → Uncategorized

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS