Hudarsono's Blog

In an average game of Monopoly, B&O Railroad is the railroad most often landed on.

 

How to secure a function with require login easily in Django on AppEngine

last updated at 2010-11-4 tags:  

Found that in AppEngine there is a quite useful way to secure bunch of function from being accessed by unauthorized user. This is called 'decorator' and symbolized by '@' character. So, in AppEngine, if we use webapp framework, we can just put that @login_required in every function that require login.

In AppEngine Helper for Django, this AppEngine build-in operator doesn't work out of the box. So we have to write the function on our own. Here is the function that can be used in DJango :

from django.http import HttpResponseRedirect
from google.appengine.api import users

def login_required(func):
    def _wrapper(request, *args, **kw):
        user = users.get_current_user()
        if user:
            return func(request, *args, **kw)
        else:
            return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    return _wrapper

After importing that module, we can secure some function that require login, only by adding the decorator at the top of that function. Here is the example :

@login_required
def delPost(request, year, month, day, key):
  post = models.Post.get(key)
  if post:
    post.delete()

    # refresh memcache
    memcache.flush_all()
  return HttpResponseRedirect('/posts/')

Very easy and time-saving huh? . For complete example, just take a look on MeBlog here.

blog comments powered by Disqus
Categories
Tags