This post explains the usage of
is_authenticated in the Flask-login User model.
The explanation of
is_authenticated in the official Flask-login documentation is confusing. It gives an impression that it indicates if a user is authenticated/validated/logged in. Following this direction, a natural question is when a user is logged in or logged out, should we set
is_authenticated dynamically and do we need a database to save the value?
In the following section, we try to clarify the notion a little bit.
Reformulate the question
Let's ask the question in a different way. If
is_authenticated is always set to true when a user object is created (e.g. returned by the
load_user method), after a user is logged out (by calling
logout_user()), does he/she need to login again before visiting a page that requires login? The answer is yes, which means the login part is handled by the Flask-login.
Then what does
is_authenticated really mean? We can try to build our own mental model to explain the behavior. Imaging we are signing up a new app. We choose our username and set the password. On the app side, a new account is created. Suppose only email is allowed to be the username. After the app creates the new account, it will send an email asking user to confirm the email by clicking the provided special link. If the link is clicked, then the app knows the user does own the email address and we could say the user is authenticated. Depending on the app, it may require subscription. If the user doesn't pay the subscription fee, then the account becomes inactive. In both cases, the user will lose access to pages that requires login.
Being logged in or logged out is another attribute of user and Flask-login handles this for us. According to the Flask-login documentation, it only allows an authenticated and active user to login.
Now back to original question, when a user is logged in or logged out, should we set
is_authenticated dynamically? This is essentially asking if we need to use
is_authenticated to track the user logged in/logged out state. The answer is no because this state tracking is handled by Flask-login and
is_authenticated is not designed for this purpose.
----- END -----
©2019 - 2022 all rights reserved