1# -*- coding: utf-8 -*- 2""" 3 webapp2_extras.appengine.users 4 ============================== 5 6 Helpers for google.appengine.api.users. 7 8 :copyright: 2011 tipfy.org. 9 :license: Apache Sotware License, see LICENSE for details. 10""" 11from google.appengine.api import users 12 13 14def login_required(handler_method): 15 """A decorator to require that a user be logged in to access a handler. 16 17 To use it, decorate your get() method like this:: 18 19 @login_required 20 def get(self): 21 user = users.get_current_user(self) 22 self.response.out.write('Hello, ' + user.nickname()) 23 24 We will redirect to a login page if the user is not logged in. We always 25 redirect to the request URI, and Google Accounts only redirects back as 26 a GET request, so this should not be used for POSTs. 27 """ 28 def check_login(self, *args, **kwargs): 29 if self.request.method != 'GET': 30 self.abort(400, detail='The login_required decorator ' 31 'can only be used for GET requests.') 32 33 user = users.get_current_user() 34 if not user: 35 return self.redirect(users.create_login_url(self.request.url)) 36 else: 37 handler_method(self, *args, **kwargs) 38 39 return check_login 40 41 42def admin_required(handler_method): 43 """A decorator to require that a user be an admin for this application 44 to access a handler. 45 46 To use it, decorate your get() method like this:: 47 48 @admin_required 49 def get(self): 50 user = users.get_current_user(self) 51 self.response.out.write('Hello, ' + user.nickname()) 52 53 We will redirect to a login page if the user is not logged in. We always 54 redirect to the request URI, and Google Accounts only redirects back as 55 a GET request, so this should not be used for POSTs. 56 """ 57 def check_admin(self, *args, **kwargs): 58 if self.request.method != 'GET': 59 self.abort(400, detail='The admin_required decorator ' 60 'can only be used for GET requests.') 61 62 user = users.get_current_user() 63 if not user: 64 return self.redirect(users.create_login_url(self.request.url)) 65 elif not users.is_current_user_admin(): 66 self.abort(403) 67 else: 68 handler_method(self, *args, **kwargs) 69 70 return check_admin 71