views:

133

answers:

2

I'm putting user privileges identificator in user sessions after authentication. How to restrict access to some parts of the site depending on user privileges. For now I'm checking privileges within page handlers but how to make it better?

Are there any existing templates of doing this? Could you give an example?

+1  A: 

If you want to restrict certain areas to only admins of your app you can put the following into app.yaml

- url: /url.*
  script: path.py
  login: admin

otherwise you can check when someone

class PathHandler(webapp.RequestHandler): 
  def get(self):
    if users.get_current_user():
       pass #do something
    else:
       self.error(403) #Access denied

 def post(self):
    if users.get_current_user():
       pass #do something
    else:
       self.error(403) #Access denied

EDIT: http://code.google.com/p/gdata-python-client/source/browse/#svn/trunk/samples/oauth/oauth_on_appengine has examples of using OAuth on appengine

AutomatedTester
Thanks, but this is almost that I'm using right now :)
Oleksandr Bolotov
you could use http://code.google.com/p/gdata-python-client/source/browse/#svn/trunk/samples/oauth/oauth_on_appengine as a template maybe?
AutomatedTester
+3  A: 

You can define decorators to make this easier. For example:

def requiresUser(fun):
  def decorate(*args, **kwargs):
    if not users.get_current_user():
      self.error(403)
    else:
      fun(*args, **kwargs)
  return decorate

def requiresAdmin(fun):
  def decorate(*args, **kwargs):
    if not users.is_current_user_admin():
      self.error(403)
    else:
      fun(*args, **kwargs)
  return decorate

And to use them, just decorate handler methods:

class NewsHandler(webapp.RequestHandler):
  # Only logged in users can read the news
  @requiresUser
  def get(self):
    # Do something

  # Only admins can post news
  @requiresAdmin
  def post(self):
    # Do something
Nick Johnson
Thank you that's cool!
Oleksandr Bolotov