[Python] Endpoint(Router) Available for Authenticated user or not FastAPI

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    Today I have a question that I tried to solve myself and looked around the internet with no success.

    In a fastAPI website. While the user is not logged in he can navigate in any page. But if logged in, and click in a link that does not have the auth signature "current_user" it automatically logged-out. Only open properly pages with "current_user" signature what I expected since pages like:"/me", "/update" will contain the user logged-in data.

    For a better understanding. I have a pages "home" homepage, "users" that list all users. These pages have to be available for authenticated user or not.But to work I made an adaptation and I'm sure it's not the best way to implement that.

    Here is what I did. In my code I made two methods one for authenticated one for not authenticated as the code below shows:

    # router to index page not authenticated users
    @app.get('/', include_in_schema=False)
    def home(request: Request):
    return globals.templates.TemplateResponse('index.html', context= {'request': request})


    # router to index page if users is authenticated (loged-in)
    @app.get('/home', include_in_schema=False)
    def home(request: Request, **cur_user: User= Depends(authentication.get_current_user)**):
    return globals.templates.TemplateResponse('index.html', context= {'request': request, 'user_in': cur_user})



    As you can see I created a path "/" for not authenticated, and "/home" if logged-in. But that is not functional at all because I would have to create 2 endpoints for all routers.

    Plus in my jinja2 I'll have to add an if..else for every link or page like this:

    {% if not user_in %}
    <a class="navbar-brand" href="http://127.0.0.1:8000/">
    <img class="img-thumbnail" src="https://deliveryti.com/fastapi_images/domain.png">
    </a>
    {% else %}
    <a class="navbar-brand" href="http://127.0.0.1:8000/home">
    <img class="img-thumbnail" src="https://deliveryti.com/fastapi_images/domain.png">
    </a>
    {% endif %}


    I'm not expert in fast api but I could not find out a way to manage session guys. I will be more than happy if someone can give a help to this problem.

    Thanks in advance.

    Continue reading...

Compartilhe esta Página