import cherrypy # <3
import hashlib
import chevron
import lmdb
import time
import pickle
def page404(**kwargs):
return "Welcome to Neverland!"
@cherrypy.tools.register("before_handler")
def auth(groups):
sess = cherrypy.session
if sess.get("login") in groups:
return
else:
raise cherrypy.HTTPRedirect("/login")
class PicoSocial:
def __init__(self, env, admin):
self.env = env
self.admin = admin
self.users_db = env.open_db(b"users")
self.msgs_db = env.open_db(b"msgs")
@cherrypy.expose
def index(self):
template = """
{{#messages}}
{{text}}
From {{name}} at {{date}}
{{/messages}}
"""
result = []
with self.env.begin(db=self.msgs_db) as txn:
for t, d in txn.cursor():
t = pickle.loads(t)
d = pickle.loads(d)
result.append({"text": d["message"],
"name": d["name"],
"date": time.ctime(t)})
return chevron.render(template, {"messages": result})
@cherrypy.expose
def login(self, username="", password=""):
if username == "" and password == "":
return """
"""
password = hashlib.sha512(password.encode()).digest()
if username == self.admin["username"] and password == self.admin["password"]:
cherrypy.session["login"] = "admin"
cherrypy.session["uname"] = username
raise cherrypy.HTTPRedirect("/send")
with self.env.begin(db=self.users_db) as txn:
password_ = txn.get(username.encode())
if password_:
if password_ == password:
cherrypy.session["login"] = "user"
cherrypy.session["uname"] = username
raise cherrypy.HTTPRedirect("/send")
else:
return "Incorrect username and/or password"
else:
return "Incorrect username and/or password"
@cherrypy.expose
@cherrypy.tools.auth(groups=("admin", ))
def adduser(self, username, password):
with self.env.begin(db=self.users_db, write=True) as txn:
password = hashlib.sha512(password.encode()).digest()
if txn.get(username.encode()):
txn.replace(username.encode(), password)
return "This user's password has been updated"
else:
txn.put(username.encode(), password)
return "User has been added to system"
@cherrypy.expose
@cherrypy.tools.auth(groups=("admin", "user"))
def send(self, message=""):
if message == "":
return """
"""
with self.env.begin(db=self.msgs_db, write=True) as txn:
t = pickle.dumps(time.time())
msg = {"message": message, "name": cherrypy.session.get("uname")}
msg = pickle.dumps(msg)
txn.put(t, msg)
return "Your message has been sent successfully."
@cherrypy.expose
@cherrypy.tools.auth(groups=("admin", "user"))
def logout(self):
cherrypy.session["login"] = False
raise cherrypy.HTTPRedirect("/")
env = lmdb.open("/tmp/picosocial081", max_dbs=2)
admin = {
"username": "admin",
"password": hashlib.sha512(b"1234").digest()
}
conf = {"global": {"tools.sessions.on": True,
"request.show_tracebacks": False,
"error_page.404": page404
}
}
cherrypy.quickstart(PicoSocial(env,admin), "/", conf)