OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 import datetime |
| 6 import logging |
| 7 import os.path |
| 8 import re |
| 9 |
| 10 from google.appengine.api import memcache |
| 11 from google.appengine.api import users |
| 12 import webapp2 |
| 13 from google.appengine.ext.webapp import template |
| 14 |
| 15 |
| 16 class BasePage(webapp2.RequestHandler): |
| 17 """Base request handler with this application specific helpers.""" |
| 18 # Check if the username ends with @chromium.org/@google.com. |
| 19 _VALID_EMAIL = re.compile(r"^.+@(chromium\.org|google\.com)$") |
| 20 app_name = '' |
| 21 _is_admin = None |
| 22 _user = None |
| 23 _initialized = False |
| 24 |
| 25 def _late_init(self): |
| 26 """Initializes self._is_admin and self._user once the request object is |
| 27 setup. |
| 28 """ |
| 29 self._is_admin = False |
| 30 |
| 31 self._user = users.get_current_user() |
| 32 if not self._is_admin and self._user: |
| 33 self._is_admin = bool( |
| 34 users.is_current_user_admin() or |
| 35 self._VALID_EMAIL.match(self._user.email())) |
| 36 self._initialized = True |
| 37 logging.info('Admin: %s, User: %s' % (self._is_admin, self._user)) |
| 38 |
| 39 @property |
| 40 def is_admin(self): |
| 41 if not self._initialized: |
| 42 self._late_init() |
| 43 return self._is_admin |
| 44 |
| 45 @property |
| 46 def user(self): |
| 47 if not self._initialized: |
| 48 self._late_init() |
| 49 return self._user |
| 50 |
| 51 def InitializeTemplate(self, title='Chromium Build'): |
| 52 """Initializes the template values with information needed by all pages.""" |
| 53 user_nickname = self.user.email() if self.user else '' |
| 54 template_values = { |
| 55 'app_name': self.app_name, |
| 56 'current_utc_time': datetime.datetime.now(), |
| 57 'is_admin': self.is_admin, |
| 58 'login_url': users.create_login_url(self.request.url), |
| 59 'logout_url': users.create_logout_url(self.request.url), |
| 60 'title': title, |
| 61 'user': self.user, |
| 62 'user_nickname': user_nickname, |
| 63 } |
| 64 return template_values |
| 65 |
| 66 def DisplayTemplate(self, name, template_values, use_cache=False): |
| 67 """Replies to a http request with a template. |
| 68 |
| 69 Optionally cache it for 1 second. Only to be used for user-invariant |
| 70 pages! |
| 71 """ |
| 72 self.response.headers['Cache-Control'] = 'no-cache, private, max-age=0' |
| 73 buff = None |
| 74 if use_cache: |
| 75 buff = memcache.get(name) |
| 76 if not buff: |
| 77 path = os.path.join(os.path.dirname(__file__), 'templates/%s' % name) |
| 78 buff = template.render(path, template_values) |
| 79 if use_cache: |
| 80 memcache.add(name, buff, 1) |
| 81 self.response.out.write(buff) |
| 82 |
| 83 |
| 84 def bootstrap(): |
| 85 app_name = os.environ['APPLICATION_ID'] |
| 86 BasePage.app_name = app_name |
OLD | NEW |