from flask import Blueprint, session, redirect, url_for, render_template
from application import keycloak

auth_blueprint = Blueprint("auth", __name__, template_folder="templates")


@auth_blueprint.route("/demo")
def demo():
    return render_template("login.html")


@auth_blueprint.route("/")
def home():
    user = session.get("user")
    if user:
        return f'Hello, {user["name"]}'
    return redirect(url_for("auth.login"))


@auth_blueprint.route("/login")
def login():
    redirect_uri = url_for("auth.auth", _external=True)
    return keycloak.authorize_redirect(redirect_uri)


@auth_blueprint.route("/auth")
def auth():
    user = keycloak.userinfo()
    session["user"] = user
    return redirect(url_for("auth.home"))
