Help with replit.web.authenticated not working right on my repl auth logout system

Question:
guys I am on the verge of TEARS trying to understand what is going on rn :sob::sob:

so you know how the replit.web module has an authenticated decorator?

def authenticated_template(template: str, **context: Any) -> Callable:
    """A decorator that renders a template if the user is not signed in.

    Args:
        template (str): The template filename to render.
        **context (Any): The context to pass to the template.

    Returns:
        Callable: A decorator to apply to your route.
    """

    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def handler(*args: Any, **kwargs: Any) -> flask.Response:
            if ReplitAuthContext.from_headers(flask.request.headers).is_authed:
                return func(*args, **kwargs)
            else:
                return flask.render_template(template, **context)

        return handler

    return decorator

look specifically at

            if ReplitAuthContext.from_headers(flask.request.headers).is_authed:
                return func(*args, **kwargs)
            else:
                return flask.render_template(template, **context)

this very clearly only calls the decorated function if user is authenticated.

now see my code

@web.authenticated_template('login.html')
@app.route('/')
def index():
    return render_template('index.html',
                           url=request.headers['X-Replit-User-Url'],
                           pfp=request.headers['X-Replit-User-Profile-Image'],
                           username=web.auth.name,
                           userid=web.auth.user_id
                          )

I even put a print statement to check if is_authed is true

print(f"is_authed: {web.ReplitAuthContext.from_headers(request.headers).is_authed}")

(there’s a shorter way, you can use web.auth.is_authed instead)

BUT it’s still rendering index.html???

I srsly don’t understand it


Repl is private but you can take a look for yourself

Not sure why it’s bugged, but as a work-around, you could try:

if not web.auth.is_authed:
   return render_template("login.html")
1 Like

Yes that works for now but I want to know what’s going on

Put the @app.route decorator first so it gets executed last.

This:

@web.authenticated_template('login.html')
@app.route('/')
def index():

registers the index fn as the / route, and then wraps it with the authenticated_template decorator, which isn’t what you want

There it is. Was sure it was something I was doing wrong, don’t know why I didn’t think to switch it around. :clap:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.