Skip to content

Instantly share code, notes, and snippets.

@ramuta
Created December 21, 2018 15:28
Show Gist options
  • Save ramuta/69548d364dc51a8e64da0acaac3a72e1 to your computer and use it in GitHub Desktop.
Save ramuta/69548d364dc51a8e64da0acaac3a72e1 to your computer and use it in GitHub Desktop.
Handlers and the use of decorators
from google.appengine.api import users
from webapp2 import redirect_to, redirect
def google_login_required(handler):
def _check_login(self, *args, **kwargs):
user = users.get_current_user()
if user:
return handler(self, *args, **kwargs)
else:
return self.redirect(users.create_login_url(self.request.uri))
return _check_login
def admin_required(handler):
def _check_login(self, *args, **kwargs):
google_user = users.get_current_user()
if google_user:
if not users.is_current_user_admin():
return redirect_to("forbidden")
else:
return handler(self, *args, **kwargs)
else:
return self.redirect(users.create_login_url(self.request.uri))
return _check_login
def normal_login_required(handler):
# if user logs in with username/password combo
def _check_login(self, *args, **kwargs):
# ... write code that checks login here ...
if valid_login:
return handler(self, *args, **kwargs)
else:
return self.redirect_to("forbidden")
return _check_login
from decorators import google_login_required, admin_required
# This one is visible to everyone
class OpenToEveryoneHandler(BaseHandler):
def get(self):
return self.render_template("visible_to_everyone.html")
# This one is visible to logged in users (via Google login)
class LimitedVisibilityHandler(BaseHandler):
@google_login_required
def get(self):
return self.render_template("visible_to_logged_in_users.html")
# This one is visible to admins
class AdminVisibilityHandler(BaseHandler):
@admin_required
def get(self):
return self.render_template("visible_to_admins.html")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment