Skip to content

Instantly share code, notes, and snippets.

@farooqkz
Last active July 28, 2020 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farooqkz/2678846d2ae2b79ef10fb9d8578483d2 to your computer and use it in GitHub Desktop.
Save farooqkz/2678846d2ae2b79ef10fb9d8578483d2 to your computer and use it in GitHub Desktop.
Form based auth with CherryPy using sessions
# 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)
@farooqkz
Copy link
Author

farooqkz commented Jul 23, 2020

As an exercise, you can add different groups of users with different access level(e.g. users and admins)

@cherrypy.tools.register('before_handler')
def myauth(groups):
    ...

and for each exposed function:

@cherrypy.expose
@cherrypy.tools.myauth(groups=["admin", "user"])
def somepage(self, ...):
    ...

@alirezaahani
Copy link

Nice ! I will added to the code soon (right now I'm little bit busy)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment