Last active
November 7, 2019 12:26
-
-
Save hclivess/31d9dd357f06a5d014c4cccc0abb812b to your computer and use it in GitHub Desktop.
Full tornado web authentication example that is actually working
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
<html> | |
<body> | |
<form action="/login" method="post"> | |
Name: <input type="text" name="name"> | |
<input type="submit" value="Sign in"> | |
</form> | |
</body> | |
</html> |
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
import os | |
import string | |
import random | |
import tornado.ioloop | |
import tornado.web | |
class BaseHandler(tornado.web.RequestHandler): | |
def get_current_user(self): | |
return self.get_secure_cookie("user") | |
class MainHandler(BaseHandler): | |
def get(self): | |
if not self.current_user: | |
self.redirect("/login") | |
return | |
name = tornado.escape.xhtml_escape(self.current_user) | |
self.write(f"Hello, {name}") | |
class LoginHandler(BaseHandler): | |
def get(self): | |
self.render("login.html") | |
def post(self): | |
self.set_secure_cookie("user", self.get_argument("name"), expires_days=28) | |
self.redirect("/") | |
def make_app(): | |
return tornado.web.Application([ | |
(r"/", MainHandler), | |
(r"/login", LoginHandler), | |
]) | |
def cookie_get(): | |
filename = "cookie_secret" | |
if not os.path.exists(filename): | |
cookie_secret = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30)) | |
with open(filename, "w") as infile: | |
infile.write(cookie_secret) | |
else: | |
with open(filename) as infile: | |
cookie_secret = infile.read() | |
return cookie_secret | |
if __name__ == "__main__": | |
app = make_app() | |
app.settings["cookie_secret"] = cookie_get() | |
app.listen(80) | |
tornado.ioloop.IOLoop.current().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment