Search code examples
pythongoogle-app-enginewebapp2

User authentication best practices


I have an app on GAE that checks if an administrator is logged in before it calls any webpage. I have tried various methods to manage the login process.

Q1 - What am I doing wrong with my decorator in example two?
Q2 - Does one normally do this check on the post function too?

Before I used an if statement in each get function. The problem is that I would repeat this if statement over and over in each function.

class IncomePage(webapp2.RequestHandler):
  def get(self):
    if users.is_current_user_admin():
      self.response.write('My Webpage')
    else:
      self.response.write('Please Login')

Then I tried to make a decorator do that for me. It didn't work so what am I doing wrong.

def check(func):
  if users.is_current_user_admin():
    return func
  else:
    response.write('Please Login') ### Doesn't work

class IncomePage(webapp2.RequestHandler):
  @check
  def get(self):
      self.response.write('My Webpage')

Solution

  • That's not a decorator. A decorator needs to return a wrapper function that is called in place of the actual function, and it's the wrapper that needs to do the test and then call the original.

    def check(func):
      def wrapper(*args, **kwargs):
        if users.is_current_user_admin():
          return func(*args, **kwargs)
        else:
          response.write('Please Login')
      return wrapper