Created
May 25, 2012 02:52
-
-
Save sharoonthomas/2785473 to your computer and use it in GitHub Desktop.
Serve files based on google authentication
This file contains hidden or 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
#! /usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
Authentication proxy for Tornado to use Google apps authentication to | |
serve the files in a protected location. Ideal to serve files like | |
sphinx documentation behind a password. | |
:copyright: (c) 2011 by Openlabs Technologies & Consulting (P) Limited | |
:license: BSD, see LICENSE for more details. | |
""" | |
import sys | |
import random | |
import string | |
import tornado.ioloop | |
import tornado.web | |
import tornado.auth | |
ALLOWED_GOOGLEAPPS_DOMAIN = '@openlabs.co.in' | |
class GoogleHandler(tornado.web.RequestHandler, tornado.auth.GoogleMixin): | |
@tornado.web.asynchronous | |
def get(self): | |
if self.get_argument("openid.mode", None): | |
self.get_authenticated_user(self.async_callback(self._on_auth)) | |
return | |
self.authenticate_redirect() | |
def _on_auth(self, user): | |
if not user: | |
raise tornado.web.HTTPError(500, "Google auth failed") | |
if not user['email'].endswith(ALLOWED_GOOGLEAPPS_DOMAIN): | |
raise tornado.web.HTTPError(403, "User from forbidden domain") | |
self.set_secure_cookie("user", unicode(user['email'])) | |
self.redirect(self.get_argument("next", "/")) | |
class LogoutHandler(tornado.web.RequestHandler): | |
def get(self): | |
self.clear_cookie("user") | |
self.redirect('/') | |
class BaseHandler(tornado.web.RequestHandler): | |
def get_current_user(self): | |
user = self.get_secure_cookie("user") | |
return user and user.endswith(ALLOWED_GOOGLEAPPS_DOMAIN) | |
class MainHandler(BaseHandler): | |
@tornado.web.authenticated | |
def get(self): | |
self.set_header('X-Accel-Redirect', '/protected/index.html') | |
self.finish() | |
class ProtectedFilesHandler(BaseHandler): | |
@tornado.web.authenticated | |
def get(self, path): | |
self.set_header('X-Accel-Redirect', '/protected/' + path) | |
self.finish() | |
settings = { | |
"cookie_secret": "some really strong cookie secret to be set", | |
"login_url": "/login", | |
} | |
application = tornado.web.Application([ | |
(r"/", MainHandler), | |
(r"/login", GoogleHandler), | |
(r"/logout", LogoutHandler), | |
(r"/(.*)", ProtectedFilesHandler), | |
], **settings) | |
if __name__ == "__main__": | |
application.listen(sys.argv[1], "127.0.0.1") | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment