git.haldean.org apex / master apex.py
master

Tree @master (Download .tar.gz)

apex.py @masterraw · history · blame

import flask
import io
import redis

import globals

app = flask.Flask(__name__)
globals.app = app
r = redis.Redis(host="localhost", port=6379, db=0)
globals.r = r

import data
import users

with open("session-key.dat", "rb") as session_file:
    app.secret_key = session_file.read()


@app.route("/static/<path:path>")
def static_file(path):
    return flask.send_from_directory("static")

@app.route("/")
def index():
    if users.session_user() is None:
        return flask.render_template("login.html")
    return flask.redirect(flask.url_for("log"))

@app.route("/login", methods=["POST"])
def login():
    username = flask.request.form["username"]
    password = flask.request.form["password"]

    if not users.check_password(username, password):
        flask.abort(401)
        return
    users.set_session_user(username)
    return flask.redirect(flask.url_for("index"))

@app.route("/log", methods=["GET", "POST"])
def log():
    if users.session_user() is None:
        return flask.redirect(flask.url_for("index"))
    if flask.request.method == "POST":
        data.store(users.session_user(), flask.request.get_json())
        return "ok"
    return flask.render_template("log.html", username=users.session_user())

@app.route("/adduser", methods=["GET", "POST"])
def adduser():
    if users.session_user() is None:
        return flask.redirect(flask.url_for("index"))
    if not users.user_is_admin():
        return flask.redirect(flask.url_for("index"))
    if flask.request.method == "GET":
        return flask.render_template("adduser.html", username=users.session_user())
    username = flask.request.form["username"]
    password = flask.request.form["password"]
    try:
        users.add_user(username, password)
    except BadRequest:
        flask.abort(400)
        return
    flask.flash("User \"{}\" added".format(username))
    return flask.redirect(flask.url_for("adduser"))

@app.route("/api/games/<username>")
def allgames_json(username):
    return data.dump_games_to_json(username), 200, {"Content-type": "text/plain"}

@app.route("/logout")
def logout():
    users.set_session_user(None)
    return flask.redirect(flask.url_for("index"))