Skip to content

Instantly share code, notes, and snippets.

@andreadipersio
Last active March 12, 2018 10:34
Show Gist options
  • Save andreadipersio/7530717 to your computer and use it in GitHub Desktop.
Save andreadipersio/7530717 to your computer and use it in GitHub Desktop.
import tornado.ioloop
import tornado.web
from tornado.options import parse_command_line, define, options
define("port", default=8888)
define("debug", default=False)
class AuthHandler(tornado.web.RequestHandler):
def get(self):
# http://www.tornadoweb.org/en/branch3.1/_modules/tornado/web.html#RequestHandler.set_secure_cookie
self.set_secure_cookie("username", "foo")
# http://www.tornadoweb.org/en/stable/_modules/tornado/web.html#RequestHandler.redirect
self.redirect("/")
class MainHandler(tornado.web.RequestHandler):
def get_current_user(self):
return self.get_secure_cookie("username")
def get(self):
user = self.get_current_user()
if not user:
raise tornado.web.HTTPError(401, "Access denied")
self.write("Welcome back, {}".format(user))
handlers = [
(r"/auth", AuthHandler),
(r"/", MainHandler),
]
if __name__ == "__main__":
parse_command_line()
opts = {
"debug": options.debug,
"cookie_secret": "II*^WvQiOkv)QihQwQZ<JH!YY/q)v%TY"
}
application = tornado.web.Application(handlers, **opts)
application.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment