1

I am able to successfully login and authenticate the user and I can access their info with current_user from the login method. But then when I make another API call and try to access current_user, I get an error and current_user is of type AnonymousUserMixin.

I thought the issue may be with the load_user function, so I added a print statement but it seems as though it never gets called.

Is there anything wrong with the below setup that would prevent load_user from getting executed when an API call is made or cause the user's session to not persist?

# app.py
login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(user_id):
    print("[LoadUser]")
    return Users.query.get(user_id)

@app.route("/login")
def login():
    user = Users(
        id = unique_id, name=users_name, email=users_email
    )
    login_user(user, remember=True)
    print(current_user.username) # Works with no issue
    return

@app.route("/test")
def test():
    print(current_user.username) # AttributeError: 'AnonymousUserMixin' object has no attribute 'username'
blackbishop
  • 30,945
  • 11
  • 55
  • 76
Aaron Rotem
  • 356
  • 1
  • 3
  • 18

1 Answers1

0

I noticed your test route does not protect against anonymous access. according to flask-login docs 0.7..current_user would then be anonymous... Which means if you lock the test route to logged in users only current_user will then be populated!

@app.route("/test")
@login_required
def test():
    print(current_user.username) 

https://flask-login.readthedocs.io/en/latest/

Tushar
  • 880
  • 9
  • 17