Python tutorial 57 – Build the User Account Login and Authentication System Using Flask, SQLAlchemy

User-based and customer-oriented are super popular in nowadays’ business model. Apart from web 2.0, web 3.0 more emphasizes decentralisation and gives back more data authority and data management to current users. So an user-centralization approach trend is arising and it just would be more important. So regarding buidling an application using Flask, user login and authentication system is a basic function it must have. Today is on how to leverage Flask login manager and build one in your application.

flask login

User-based and customer-oriented are super popular in nowadays’ business model. Apart from web 2.0, web 3.0 emphasizes decentralization and gives back more data authority and data management to current users. So a user-centralization approach trend is arising and it just would be more important. So regarding building an application using Flask, a user login and authentication system is a basic function it must have. Today is on how to leverage Flask login manager and build one in your application.

Flask Login Manager Installation and Configuration

This module provides user session management in the Flask application. It handles the common tasks of logging in, logging out, and remembering your users’ sessions over extended periods of time.

Basically, the Flask login manager can let you do these things below:

  1. Store the active user’s ID in the session, and let you log them in and out easily.
  2. Let you restrict views to logged-in (or logged-out) users.
  3. Handle the normally tricky “remember me” functionality.
  4. Help protect your users’ sessions from being stolen by cookie thieves.
  5. Possibly integrate with Flask-Principal or other authorization extensions.

First thing first, installing a flask login manager is super easy. We can input pip3 install flask-login into your computer terminal. Then, configuring the flask login with your flask application is by doing the three steps:

1. Import the flask login modules

from flask_login import LoginManager

from flask_login import login_user, logout_user, login_required, current_user

2. Initiate the LoginManager instance and connect with your app

flask login

3. Define the load_user function by returning the user_id

@login_manager.user_loader

def load_user(user_id):

return User.query.get(int(user_id))

Create and Configure the User Database using SQLAlchemy and Flask login UserMixin

No.1, we need to import the SQLAlchemy module and configure it with the flask application

From flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database1.db'

Second, creating a class User which is added the data column needed and the specification of each data column.

from flask_login import UserMixin

class User(db.Model, UserMixin):

id = db.Column(db.Integer, primary_key=True)

email = db.Column(db.String(yourNumber), unique=True)

username = db.Column(db.String(yourNumber),nullable=False, unique=True)

password = db.Column(db.String(yourNumber),nullable=False)

date_created = db.Column(db.DateTime(timezone=True), default=func.now())

token = db.Column(db.String(yourNumber), unique=True)

Last but not least, we need to create an initiative SQLAlchemy database. In the terminal, we can create the initiative SQLAlchemy database. Please use the application name you created in the flask application and the variable name you used to connect with the flask app. I use the app and db here.

$ >>> from app import db

$ >>> db.create_all()

User Registration

Now ingredients are ready to start building a registration route for new users to join your application.

First thing first, a route is indispensable for users to register. 

@app.route("/registration", methods=['GET', 'POST'])

For more details regarding the Flask route and collecting submission data from HTML, please check out this article

https://www.easy2digital.com/automation/data/python-tutorial-26-create-a-shopify-bot-web-application-using-flask-and-heroku/

Second, by referring to the User class we created earlier, we need to match the new user input data from the form on the registration route with our database column. If your application also has an API program, here also needs to add the token variable and decode it the password input by the new user.

new_user = User(email=email, username=username, password=generate_password_hash(password, method='sha256'), token=token.decode())

Then, we can add the new_user and utilize commit() it to confirm it, and remember it by using the login_user function we created earlier.

flask login

For more details about Flask JWT API deployment, please refer to this article

https://www.easy2digital.com/automation/data/python-tutorial-54-utilize-flask-jwt-to-tokenizer-the-api-user-identity-and-authenticate-users/

Flask login_user, logout_user, and current_user

After new user creation, Flask provides modules to facilitate developers to build up login pages, login out page,s and detect the logined user on sites.

First thing first, we need to import the modules from the flask_login. I’ll talk about login_required in the next section.

from flask_login import login_user, logout_user, login_required, current_user

Login_user

To verify the user login information input on the login page, we can check if the user password in the SQLAlchemy data can match the password input by the visitor.

Using the query.filter_by in the User class to match the email address first. 

user = User.query.filter_by(email=email).first()

Then, if the fetched email user’s password is matching the input value from the form, it’s logged in. And login_user can remember this user in any session later on before log_out.

if user:

    if check_password_hash(user.password, password):

         flash("Logged in!", category='success')

         login_user(user, remember=True)

Logout_user

Creating a new route for users to log out of their accounts.

@app.route("/logout")

@login_required

def logout():

logout_user()

return redirect(url_for('home'))

Current_user

This is a super useful module as it tells the application who is visiting the page. If you like to offer exclusive content for members or differentiate content between unknown users and sign-up users. This module facilitates you to deploy and build the functions.

return render_template("shopify.html", user=current_user)

To detect the existing users, we need to add the current_user in the render_template of each route or the routes you wanna show personalized content in the Flask application.

Login_required decorator

For any routes that are only open to members, you need to add the login_required decorator under the route. Take the logout route, for example, if a user hasn’t login yet, she or he can’t click through the logout page, and you can add a flask message to notify them login first.

@app.route("/logout")

@login_required

def logout():

logout_user()

return redirect(url_for('home'))

Full Python Script of Flask User Account Login and Authentication

If you are interested in the full Python tutorial 57 – Build the User Account Login and Authentication System Using Flask, SQLAlchemy, please subscribe to our newsletter by adding the message “Python Tutorial 56”. We would send you the script immediately to your mailbox.

Contact us

I hope you enjoy reading Python tutorial 57 – Build the User Account Login and Authentication System Using Flask, SQLAlchemy. If you did, please support us by doing one of the things listed below, because it always helps out our channel.

  • Support my channel through PayPal (paypal.me/Easy2digital)
  • Subscribe to my channel and turn on the notification bell Easy2Digital Youtube channel.
  • Follow and like my page Easy2Digital Facebook page
  • Share the article to your social network with the hashtag #easy2digital
  • Buy products with Easy2Digital 10% OFF Discount code (Easy2DigitalNewBuyers2021)
  • You sign up for our weekly newsletter to receive Easy2Digital latest articles, videos, and discount code on Buyfromlo products and digital software
  • Subscribe to our monthly membership through Patreon to enjoy exclusive benefits (www.patreon.com/louisludigital)