How to Add Authentication too App with Flask-Login
0 418
Introduction
Implementing authentication in a Flask application is crucial for managing user sessions and securing sensitive data. Flask-Login is a powerful extension that simplifies user authentication by handling user sessions and providing tools for login, logout, and session management. In this guide, we'll walk through the steps to add authentication to your Flask app using Flask-Login, including setting up user models, creating login and registration routes, and protecting routes that require authentication.
Step 1: Install Necessary Packages
To get started, install Flask, Flask-Login, Flask-SQLAlchemy, and Werkzeug using pip:
pip install flask flask_sqlalchemy flask_login werkzeug
Step 2: Set Up Flask Application
Create a Flask application and configure it to use an SQLite database. Set a secret key for session management and initialize Flask-SQLAlchemy and Flask-Login:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SECRET_KEY"] = "supersecretkey"
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
Step 3: Create User Model
Define a User model that inherits from both db.Model and UserMixin. This model will represent users in the database:
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), unique=True, nullable=False)
password = db.Column(db.String(150), nullable=False)
with app.app_context():
db.create_all()
Step 4: Implement User Loader
Flask-Login requires a function to load a user from the user ID stored in the session. Define the user_loader function:
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
Step 5: Create Registration Route
Create a route to handle user registration. This route will render a registration form and handle form submissions to create new users:
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
hashed_password = generate_password_hash(password, method="sha256")
new_user = User(username=username, password=hashed_password)
db.session.add(new_user)
db.session.commit()
return redirect(url_for("login"))
return render_template("register.html")
Step 6: Create Login Route
Create a route to handle user login. This route will render a login form and handle form submissions to authenticate users:
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
user = User.query.filter_by(username=username).first()
if user and check_password_hash(user.password, password):
login_user(user)
return redirect(url_for("dashboard"))
return render_template("login.html")
Step 7: Protect Routes with Login Required
Use the login_required decorator to protect routes that should only be accessible to authenticated users:
@app.route("/dashboard")
@login_required
def dashboard():
return render_template("dashboard.html", name=current_user.username)
Step 8: Implement Logout Route
Create a route to handle user logout. This route will log out the current user and redirect them to the login page:
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for("login"))
Conclusion
By following these steps, you can implement user authentication in your Flask application using Flask-Login. This setup provides a secure and efficient way to manage user sessions and protect routes that require authentication.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:


Comments
Waiting for your comments