Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering users' sessions over extended periods of time.
Here's a basic guide to adding authentication to your Flask app using Flask-Login:
First, you need to install the Flask-Login extension:
pip install flask-login
After installation, set up the user loader callback. This callback is used to reload the user object from the user ID stored in the session.
from flask_login import LoginManager, UserMixin
login_manager = LoginManager()
login_manager.init_app(app) # Initialize it with your Flask app instance.
class User(UserMixin):
# Create a User class with UserMixin that includes generic implementations
# that are appropriate for most use cases.
@login_manager.user_loader
def load_user(user_id):
# Given *user_id*, return the associated User object.
return User.get(user_id)
Flask-Login expects your user class to have certain properties and methods (is_authenticated, is_active, is_anonymous, get_id). UserMixin provides these default implementations, which should suffice for most use cases.
class User(UserMixin):
def __init__(self, username, password, id, active=True):
self.id = id
self.username = username
self.password = password
self.active = active
# method to retrieve a user from the database
@staticmethod
def get(user_id):
# For the purpose of this example, we'll use a predefined user.
# In a real application, you'd query the database here.
if user_id == '1':
return User('user', 'password', 1)
else:
return None
Now, create routes for login and logout functionality.
from flask import Flask, redirect, url_for, request
from flask_login import current_user, login_user, logout_user
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.get(1) # Get user from database, here we're just using a mock
if user and user.password == password:
login_user(user)
return redirect(url_for('index'))
else:
return 'Invalid username or password'
return 'Login form here'
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
To protect a route, use the login_required decorator.
from flask_login import login_required
@app.route('/protected')
@login_required
def protected():
return 'Logged in as: ' + current_user.username
Make sure to initialize LoginManager with your app object.
if __name__ == '__main__':
# The login manager contains the code that lets your application and Flask-Login work together.
login_manager.init_app(app)
app.run(debug=True)
Remember that this is just a simple example to show you the basics of Flask-Login. In a real-world application, you would also need to:
bcrypt).login_manager.login_view = 'login') so Flask-Login knows where to redirect users for login.By following these steps, you'll integrate Flask-Login into your Flask application and provide a working authentication system.
flying-saucer final ontouchlistener azure-cosmosdb-sqlapi special-folders instanceof character-properties text-widget cardlayout vhosts