The user authentication process described in Chapter 8 of Miguel Grinberg’s book is quite complicated. The flask-login plugin makes it a little simpler. Here are the steps it takes to create a basic login and logout system.
password_hash
field to User
model, and add a @password.setter
property and
a verify_password
method to the User
model. UserMixin
to User
model. The UserMixin
is defined in flask-login plugin. login_manager
in app/__init__.py
like any other flask plugin.base.html
template file, add links for login and logout. The links will show up
for all pages of the site. login
view function. auth/login.html
template file. login_user
of flask-login to do the actual log in work. logout
view function is simpler. It calls logout_user
to do the work and no
template is need. Page 113 of the book has an excellent description on how flask-login works.
The user registration process is simpler. It is a typical form collecting data from a user and saving the data in a database. Here are the steps.
login
template page for user registration.register
view function.user
instance and commit it to the db.User email confirmation logic is not very difficult. The system sends an email to a user
during registration. The email contains a link to a view function that changes a field of
User
model in the database. The interesting part is that user id is not passed around in
text, instead it is encoded into tokens. Below are the steps.
User
model. confirm
boolean field.generate_confirmation_token
and confirm
register
view function. confirm
view function and contains tokenconfirm
view function<token>
as a variable. current_user.confirm
method to change db field. If the user confirms, everything is good. But the system needs to consider what happens
when a user does not confirm. The idea is to check every request, and to show an
unconfirmed
page when necessary. The pages has a link to resend the confirmation email.
There is also a flask-user plugin that is widely used.