Created
December 21, 2018 15:28
-
-
Save ramuta/69548d364dc51a8e64da0acaac3a72e1 to your computer and use it in GitHub Desktop.
Handlers and the use of decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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