jon/jon/auth.py

42 lines
1.1 KiB
Python

import secrets
import string
from flask import Blueprint, request, redirect, render_template, session
bp = Blueprint("auth", __name__, url_prefix="/auth")
ACCESS_TOKEN = "".join(secrets.choice(string.ascii_lowercase) for i in range(64))
ALLOWED_PATHS = [
"/favicon.ico",
"/static/jon.css"
]
def before_request():
"""
If the correct token query parameter is passed along with any request,
we mark this session authenticated by setting `session["authenticated"]`.
Unless the session is authenticated, all requests result in a 403 FORBIDDEN.
"""
if "token" in request.args:
if request.args["token"] == ACCESS_TOKEN:
session["authenticated"] = ()
# Reload the page without query parameters
return redirect(request.path)
# Don't deny any paths in `ALLOWED_PATHS`
if request.path in ALLOWED_PATHS:
return
if not "authenticated" in session:
return render_template("auth/denied.html"), 403
@bp.get("/logout")
def logout():
session.pop("authenticated", None)
return redirect("/")