from fastapi import Request
from fastapi.responses import JSONResponse, RedirectResponse


class NotAuthenticatedException(Exception):
    pass


def auth_exception_handler(request: Request, exc: Exception):
    """
    Redirect the user to the login page if not logged in
    """
    print(request.headers.get("accept", ""))
    print("application/json" in request.headers.get("accept", ""))
    if "application/json" in request.headers.get("accept", ""):
        return JSONResponse(
            content={
                "access": "denied",
                "msg": "You are not authenticated or your token has expired",
            }
        )

    response = RedirectResponse(
        url=request.url_for("login_view").include_query_params(msg="not-authenticated")
    )
    manager = request.app.state.manager
    manager.set_cookie(response, "")
    return response
