2
votes

I have the impression that using is_authenticated from flask_login doesn't work properly. Giving the following logs that I get on my test environment:

False
2018-06-05 15:20:22,416 - root - INFO - GET - /ngin/api/v2/menu/main? - 200 OK
False
2018-06-05 15:20:45,543 - root - INFO - GET - /ngin/api/v2/menu/lvgo? - 200 OK
False
2018-06-05 15:20:48,605 - root - INFO - GET - /ngin/api/v2/menu/main? - 200 OK
False
2018-06-05 15:20:51,120 - root - INFO - GET - /ngin/api/v2/menu/lpgp? - 200 OK
user_id
True
2018-06-05 15:20:51,219 - root - INFO - GET - /ngin/static/media/ngin_gas.svg? - 200 OK
False
2018-06-05 15:20:52,865 - root - INFO - GET - /ngin/api/v2/menu/main? - 200 OK
False
2018-06-05 15:20:55,173 - root - INFO - GET - /ngin/api/v2/menu/lpgp? - 200 OK
False

The log line with the url is in the after_request block, so is printed at the end. The username ('user_id') comes from the login_manager.user_loader ; and the True or False come from the current_user.is_authenticated. It seems that the user_loader isn't always called. And when it does, the user shows authenticated, but when the call doesn't happen, the is_authenticated returns false.

My code is structured like this:

class usrmgmr():

  def __init__(self, app):
    self.login_manager = fl.LoginManager()
    self.login_manager.init_app(app)
    self.login_manager.session_protection = 'strong'

    @self.login_manager.user_loader
    def load_user(user_id):
      print(user_id)
      return User(user_id)

  #Function to check if a user is authenticated.
  # returns True or False
  def is_loggedin(self):
    return fl.current_user.is_authenticated

  #only for debug purposes!
  def do_debug_login(self):
    user = User('user_id')
    fl.login_user(user, remember=True, duration=datetime.timedelta(seconds=7200)) 

And the code is used like this in run.py:

usrmgmr = login.usrmgmr(app)
@app.before_request
def before_every_request():
  #check if for this endpoint a login is required.
  #if yes, and the user is not logged in, force the login method.
  #else we can just move on. Also the user probably is logged in then.
  if msec.needs_login(page_security):
    print(usrmgmr.is_loggedin())
    if usrmgmr.is_loggedin() == False:
       usrmgmr.do_debug_login()

So for every request we check if a user needs to be logged in to see the endpoint, and we check if the user is already logged in.

The strange thing is that sometimes I get 'True' and sometimes I get 'False'. So that doesn't seem very consistent. The strange this is that it seems it never returns True when /ngin/api/v2/... is called, but when a statick file is called, it does work.

Does anyone know how to fix this, or what the reason is for this behaviour?

1

1 Answers

1
votes

I was facing the same issue for Flask on Heroku. The fix eas to add --preload on your Procfile web: gunicorn app:app --preload