from flask import Blueprint, request, session, render_template, redirect, url_for from werkzeug.security import generate_password_hash, check_password_hash from .users import Users from .exceptions import UsernameTakenError from .config import * bp = Blueprint("auth", __name__, url_prefix="/") users = Users(USERS_PATH) def show_error(action, message): return render_template( "auth.html", action=action, error=message, ) @bp.route("/login", methods=["GET", "POST"]) def login(): if request.method == "GET": return render_template("auth.html", action="login") # validate login information username = request.form.get("username") password = request.form.get("password") if not all([username, password]): return show_erro("login", "Please fill in both the username and password.") user = users.find(username) if user is None: return show_error("login", f"User {username} does not exist.") if not check_password_hash(user["password"], password): return show_error("login", "Incorrect password. Sorry.") # give access session.clear() session["username"] = username return redirect(url_for("admin.index")) @bp.route("/register", methods=["GET", "POST"]) def register(): if request.method == "GET": return render_template("auth.html", action="register") username = request.form.get("username") password = request.form.get("password") if not all([username, password]): return render_template( "auth.html", action="register", error="Please fill in both the username and password.", ) try: users.register(username, generate_password_hash(password), "en-US") except UsernameTakenError as e: return render_template( "auth.html", action="register", error=e.message, ) session["username"] = username return redirect(url_for("admin.index"))