Welcome to my tutorial on creating a user authentication system using Flask! In this guide, I’ll walk you through the process of setting up signup, login, and logout routes for your Flask application using Python code.
Setting Up
First, make sure you have Flask installed. If not, you can install it via pip:
pip install FlaskNow, let’s dive into the code and understand how each route works.
Signup Route
The signup route (“/register”) handles user registration. When a user submits the registration form, their username, email, and password are validated. If the provided information passes validation, the user’s password is securely hashed using the generate_password_hash function from Werkzeug. The hashed password, along with the username and email, is then stored in the database.
from flask import Flask, request, render_template, redirect, session
from werkzeug.security import generate_password_hash
app = Flask(__name__)
app.secret_key = "your_secret_key"
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
# Validate form data
username = request.form.get("username")
password = request.form.get("password")
email = request.form.get("email")
if not (username and password and email):
return render_template("register.html", message="All fields are required.")
# Hash the password
hashed_password = generate_password_hash(password)
# Store user data in the database
# Your database insertion code goes here
return redirect("/login")
return render_template("register.html")Login Route
The login route (“/userlogin”) allows registered users to log into the application. Upon submitting the login form, the user’s credentials are verified against the database. If the username exists and the password matches the hashed password stored in the database, the user is logged in, and their user ID is stored in the session. If the credentials are invalid, an appropriate error message is displayed.
from flask import Flask, request, render_template, redirect, session
from werkzeug.security import check_password_hash
app = Flask(__name__)
app.secret_key = "your_secret_key"
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
# Retrieve user data from the database
# Your database query code goes here
# Check if username exists and password is correct
if user and check_password_hash(user.password, password):
session["user_id"] = user.id
return redirect("/userhome")
else:
return render_template("login.html", message="Invalid username or password.")
return render_template("login.html")Logout Route
The logout route (“/logout”) clears the user’s session, effectively logging them out of the application. This route is straightforward and doesn’t require any form submission. It simply removes the user’s session data and redirects them to the login page.
from flask import Flask, redirect, session
app = Flask(__name__)
app.secret_key = "your_secret_key"
@app.route("/logout")
def logout():
# Clear the session
session.clear()
return redirect("/")Conclusion
You’ve now implemented signup, login, and logout routes in your Flask application! These routes enable user authentication, allowing users to register, log in, and log out of your application securely.
Feel free to customize and expand upon this code to fit your specific application requirements. Flask provides a flexible framework for building web applications, and user authentication is a crucial aspect of many projects.
We hope you found this tutorial helpful in building your Flask application. Happy coding! 😊🚀
