Welcome to our Flask-Login Setup tutorial! In this lesson, we'll learn how to secure your Flask applications using the Flask-Login extension. By the end of this tutorial, you'll have a solid understanding of user authentication and authorization, and you'll be able to apply these skills to your own projects. Let's get started!
Flask-Login is a popular extension for Flask that helps manage user sessions and authentication. It provides an easy-to-use decorator for protecting routes, ensuring that only authenticated users can access them.
To install Flask-Login, run the following command in your terminal:
pip install Flask-Login
Next, let's import Flask-Login and create a user manager class:
from flask import Flask, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required
app = Flask(__name__)
app.secret_key = 'your_secret_key' 📝 **Note**: Replace 'your_secret_key' with a secure value.
login_manager = LoginManager()
login_manager.init_app(app)Next, we'll create a simple User model that Flask-Login can manage. For this example, we'll use a dictionary-based user model:
users = {
'admin': {
'username': 'admin',
'password': 'password'
}
}
class User(UserMixin):
pass
@login_manager.user_loader
def load_user(user_id):
if user_id not in users:
return None
return User()Now, let's create a login route that checks the user's credentials against our users dictionary:
@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.get('username')
password = request.form.get('password')
if username not in users or users[username]['password'] != password:
return 'Invalid username or password'
user = User()
user.id = username
login_user(user)
return redirect(url_for('index'))
return '''
<form method="post">
<label for="username">Username:</label>
<input type="text" name="username"><br>
<label for="password">Password:</label>
<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
'''
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('login'))login_required 💡Finally, let's create a protected route that requires user authentication:
@app.route('/')
@login_required
def index():
return 'Welcome, ' + current_user.id + '!'Now, when you run your Flask app and navigate to http://localhost:5000/, you'll be prompted to log in. After logging in, you'll be redirected to the protected route, which displays your username.
What is the purpose of the `app.secret_key` variable in the code?
We've covered the basics of setting up Flask-Login in this tutorial. In the next lessons, we'll dive deeper into Flask and learn about topics like database integration, RESTful APIs, and more! 💡 Pro Tip: Be sure to explore Flask's official documentation for more advanced features and best practices.
Happy coding! 💻