Search code examples
pythonflask-loginflask

How do I handle login in flask with multiple blueprints?


I have multiple blueprints that needs to be integrated into a single app. I'm using flask-login to handle logins. However I'm confused on how to handle the LoginManager() and the .user_loader for my blueprints.

This is my current file structure.

system/
     run.py
     config.py
     app/
        __init__.py
        models.py
        views/
             blueprint1.py
             blueprint2.py
        static/
        templates/
              <templates>

What's the correct way to implement them? Do I just call them at the __init__.py and import the login manager variable at the blueprints? or Do I need to call them individually in the blueprints?

Hopefully I'm able to portray the question clearly. Thank you for reading and answering


Solution

  • You must understand that for one application you must use one login manager no matter how many blueprints you use (of course there can be specific exceptions for example when blueprints are independent, but in this case you probably can't use flask-login). Because:

    1. You have 1 entry point
    2. If user is not logged in, he will be redirected to login/registration page
    3. You have 1 user loader

    How login manager works:

    1. It registers current_user in request context
    2. before_request reads your session, gets user id, loads the user with user_loader and set it to current_user or AnonymousUser
    3. When you visit the private page, login_required checks current_user.is_authenticated() else redirects to login page
    4. On login, it adds user id to the session

    So you must initialize only one login manager instance for flask application and then use login_required and current_user in all your blueprints.