Last active
July 28, 2020 11:54
-
-
Save farooqkz/2678846d2ae2b79ef10fb9d8578483d2 to your computer and use it in GitHub Desktop.
Form based auth with CherryPy using sessions
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
# Code is by Farooq Karimi Zadeh | |
# and it is under CC0 which means | |
# Public Domain and no copyright :) | |
import cherrypy # <3 | |
@cherrypy.tools.register('before_handler') | |
def myauth(): | |
sess = cherrypy.session | |
if sess.get("login?"): | |
return "Mooo" # It should just return, not important what it returns | |
else: | |
raise cherrypy.HTTPRedirect("/login") | |
class Hello: | |
@cherrypy.expose | |
def login(self, username="", password=""): | |
if not (username and password): # not (u and p) <=> (not u) or (not p) | |
return """ | |
<html> | |
<body> | |
<form action="/login"> | |
<input name="username"><br> | |
<input type="password" name="password"><br> | |
<input type="submit"> | |
</form> | |
</body> | |
</html>""" | |
if username == "bob" and password == "secret": | |
cherrypy.session["login?"] = True | |
raise cherrypy.HTTPRedirect("/") | |
else: | |
return "Username or password is incorrect" | |
@cherrypy.expose | |
@cherrypy.tools.myauth() | |
def index(self): | |
return "Hello there! Are you alright?" | |
conf = {"global": { | |
"tools.sessions.on": True | |
} | |
} | |
cherrypy.quickstart(Hello(), "/", conf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice ! I will added to the code soon (right now I'm little bit busy)