TL;DR Create a Flask project using virtualenv, install Flask-Login extension, set up a User model with SQLAlchemy, implement login functionality with user registration and logout routes.
Flask Authentication with User Login/Logout
In this article, we'll delve into the world of Flask authentication, specifically focusing on implementing user login and logout functionality in a web application built using Flask.
Why Flask?
Flask is a lightweight Python web framework that provides an efficient way to build robust, scalable applications. Its minimalistic design makes it ideal for building small to medium-sized projects. With its extensive collection of extensions, Flask can be easily extended to support complex functionalities such as user authentication.
Project Setup
To begin with, let's set up a new Flask project using the following command:
mkdir flask_auth
cd flask_auth
virtualenv venv
source venv/bin/activate
pip install flask
Next, create a new file named app.py and add the following code to initialize our Flask application:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome to my Flask App!"
if __name__ == "__main__":
app.run(debug=True)
Flask-Login Extension
To implement user authentication in our Flask application, we'll use the Flask-Login extension. This extension provides a simple way to manage user sessions and authentication.
First, install the Flask-Login extension using pip:
pip install flask-login
Next, initialize the Flask-Login extension in our Flask application:
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
User Model
To store user information, we'll create a simple User model using SQLAlchemy, which is another popular extension for Flask.
First, install Flask-SQLAlchemy:
pip install flask-sqlalchemy
Next, import the necessary modules and define our User model:
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
Login Functionality
Now that we have our User model in place, let's implement the login functionality. We'll create a new route for user registration and another for user login.
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
return "User registered successfully!"
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username, password=password).first()
if user:
login_user(user)
return "User logged in successfully!"
return render_template('login.html')
@app.route('/logout')
def logout():
logout_user()
return "User logged out successfully!"
Template Integration
To display the registration and login forms, we'll create two new templates named register.html and login.html.
<!-- register.html -->
<form method="POST">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Register</button>
</form>
<!-- login.html -->
<form method="POST">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
Conclusion
In this article, we've successfully implemented user login and logout functionality in a Flask application using the Flask-Login extension. We've also created a simple User model to store user information.
With these basic authentication features in place, you can now focus on building more complex web applications using Flask.
Example Use Cases
- Implementing user roles and permissions
- Integrating with existing authentication systems (e.g., OAuth)
- Creating password reset functionality
Remember to explore the official documentation for Flask-Login and other extensions to unlock their full potential. Happy coding!
