To implement a login system in Flask, you can follow these steps:
1. **Install Flask-Login**: Flask-Login is a widely used Flask extension that handles user authentication. You can install it using pip:
```bash
pip install flask-login
```
2. **Set up User Model**: Create a User model to represent your application's users. This model should have fields like username, password hash, etc.
3. **Initialize Flask-Login**: Initialize Flask-Login in your Flask application:
```python
from flask import Flask
from flask_login import LoginManager
app = Flask(__name__)
login_manager = LoginManager(app)
```
4. **User Loader Function**: Implement a user loader function to load users from the database. This function is required by Flask-Login to manage user sessions:
```python
from your_application.models import User
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
```
5. **Login View**: Create a login view where users can enter their credentials:
```python
from flask import render_template, request, redirect, url_for
from flask_login import login_user
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Validate user credentials
user = User.query.filter_by(username=request.form['username']).first()
if user and user.check_password(request.form['password']):
login_user(user)
return redirect(url_for('index'))
return render_template('login.html')
```
6. **Protect Routes**: Use the `@login_required` decorator to protect routes that require authentication:
```python
from flask_login import login_required
@app.route('/protected')
@login_required
def protected():
return 'This is a protected route!'
```
7. **Logout**: Implement a logout function to allow users to log out:
```python
from flask_login import logout_user
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('index'))
```
8. **HTML Templates**: Create HTML templates for login, logout, and other views as needed.
By following these steps, you'll have a basic user authentication system in your Flask application. Make sure to handle password hashing securely and consider additional security measures like CSRF protection.