Skip to content

Instantly share code, notes, and snippets.

@krtek
Last active December 25, 2015 14:59
Show Gist options
  • Save krtek/6994910 to your computer and use it in GitHub Desktop.
Save krtek/6994910 to your computer and use it in GitHub Desktop.
Secure access to AppEngine application with webapp2.
from utils import SecureApplication
routes = (
('/route1', 'app.views.view1'),
)
handler = SecureApplication(routes=routes, debug=settings['DEBUG'])
import logging
from google.appengine.api import users
from webapp2 import WSGIApplication
from webob import exc
class SecureApplication(WSGIApplication):
""" WSGIApplication which checks if user belongs to one of allowed domains. """
def __call__(self, environ, start_response):
logging.debug('calling request as %s' % users.get_current_user())
with self.request_context_class(self, environ) as (request, response):
try:
if authorize_user():
return super(SecureApplication, self).__call__(environ, start_response)
else:
raise exc.HTTPForbidden(detail="User not allowed to access application!")
except Exception, e:
try:
# Try to handle it with a custom error handler.
rv = self.handle_exception(request, response, e)
if rv is not None:
response = rv
except exc.HTTPException, e:
# Use the HTTP exception as response.
response = e
except Exception, e:
# Error wasn't handled so we have nothing else to do.
response = self._internal_error(e)
try:
return response(environ, start_response)
except Exception, e:
return self._internal_error(e)(environ, start_response)
def authorize_user(allowed_domains):
""" Checks if user is authorized to use the application. If user is not from one of allowed domains it returns
false."""
user = users.get_current_user()
email_info = user.email().split('@')
if len(email_info) != 2:
logging.warning('Cannot resolve domain for current user: %r' % user.email())
return False
domain = email_info[1]
if domain not in allowed_domains:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment