I’m working on a flask app that needs authentication. I’ve hooked up flask-login but it doesn’t seem very graceful.
First flask-login needs to make sure the user exists:
@login_manager.user_loader
def load_user(id):
return User.query.get(id)
But you also need to use ‘login_user’ to create the user object
# Some code above
user = User.query.filter_by(email = form.email.data, password = form.password.data).first()
user.login_status = 1
db.session.commit()
login_user(objects.SignedInUser(user.id, user.email, user.login_status == LoginStatus.Active))
# Some code below
In the code above ‘User’ is a model for postgres and SignedInUser is just an object to be used for flask-login.
Does anyone have an example of flask-login used with postgres?
It looks like you might be misunderstanding what Flask-Login handles. It’s there to keep track of everything about the user’s session after you tell it authentication was successful (by calling
login_user.) Theuser_loadercallback only tells it how to reload the object for a user that has already been authenticated, such as when someone reconnects to a “remember me” session. The docs are not especially clear on that.There should be no need to keep a flag in the database for the user’s login status. Also, the code you included will raise an AttributeError if the credentials are incorrect (user = None).
Here’s an example from a Flask-SQLAlchemy application. It uses an external authentication source and a wrapper for the SQLAlchemy User object, but the process is basically the same.
user_loader callback:
User class (wrapper for SQLAlchemy object):
Login handler:
Note that login fails if:
login_userreturns False (user.is_active() == False)Logout