How to prevent current_user in flask_login from getting reset?

445 views Asked by At

I am using flask app as a backend server for my react frontend. In the flask app, I have setup LoginManager(app) and I have a @login_manager.user_loader, all setup according to the flask documentation. With a print statement I make sure, that the current_user.is_authenticated is true after login_user(user, remember=True) statement.

However, when I check current_user.is_authenticated at a different route, it is false. How do I resolve this ? Is it something to do with CORS(app) ? if so, how do I set up flask_login for CORS ?

#__init__.py
...
app = Flask(__name__)
CORS(app)
login_manager = LoginManager(app)

The Login happen as follows:

# users.py

@app.route('/auth/login', methods=['GET', 'POST'])
def login():
  username = request.json.get('username')
  password = request.json.get('password')
  userObj = {}

  if verify_password(username, password):
    user =User.query.filter_by(username=username).first()
    login_user(user, remember=True)
    userObj ={"uid":user.id, "username": user.username, "email": user.email}        

  return jsonify({"loggedin":current_user.is_authenticated, "user":userObj})

And then I try to verify if current_user is authenticated before sending back a list of chapters.

# lists.py
from flask_login import current_user as curUser

@app.route('/get_chaptersList', methods=['GET'])
def chaptersList():
  # Access Checks
  print("curUser:",curUser.get_id(), curUser.is_authenticated)
  if not curUser.is_authenticated:
    return jsonify({ 'list': [], 'restricted':True, 'msg': 'Login required' })

The output I get from the above funtion curUser: None False and when I check the response in the console, it is always { 'list': [], 'restricted':True, 'msg': 'Login required' }

I am trying to server react frontend with flask as the backend. To authenticate users I am useing flask_login. Everything works fine in development with react's proxy value in package.json set to "localhost:5000". But for production's sake, I avoid using proxy and use the whole url in the fetch calls, like fetch('http://localhost:5000/auth/login', userObj). When I do this, flask is not able to remember the user or keep the user logged in for the next api call. I tried to print current_user.is_authenticated and it outputs False on the very next fetch call. How do I handle this ?

0

There are 0 answers