213 views

In any web application, user authentication and protecting certain routes are essential for maintaining security and ensuring that users have access only to the appropriate resources. Python Flask provides powerful tools to implement user authentication and protect routes seamlessly. In this tutorial, we'll explore how to implement authentication and protected pages using Flask-Login, a widely used Flask extension.

Flask Login

Flask-Login is an extension for Flask that simplifies the process of managing user sessions and authentication. To get started, install Flask-Login using pip:

```bash
pip install flask-login
```

One of the key features of Flask-Login is the `UserMixin` class. By inheriting from `UserMixin` in your user model, you gain default implementations for methods required by Flask-Login, such as `is_authenticated`, `is_active`, `is_anonymous`, and `get_id`. This saves you from writing these methods yourself, making integration with Flask-Login much smoother.

```python
from flask_login import UserMixin

class UserModel(UserMixin):
    # Your user model implementation
```

Initialize Login Manager

In your Flask application's `__init__.py`, initialize the `LoginManager` and configure a user loader function.

```python
from flask_login import LoginManager

login_manager = LoginManager(app)

@login_manager.user_loader
def load_user(user_id):
    # Load and return a user instance based on user_id
    return UserModel(user_id)
```

Login View

When creating a login form, make sure to include a CSRF token tag using `form.hidden_tag()` to prevent CSRF attacks. Also, ensure that the form method attribute is set to "POST" and the action attribute points to the login method.

```html
<form method="POST" action="{{ url_for('bp_authcontroller.login') }}">
    {{ form.hidden_tag() }}
    <!-- Other form fields -->
</form>
```

AuthController

In your authentication controller, handle the login process. Retrieve form data using `request`, validate the form using a `LoginForm` class, and query the database for the user. Check if the password matches using `check_password_hash` from Werkzeug. If successful, create session variables and redirect to the protected page.

```python
from flask import request, redirect, url_for, flash, session
from werkzeug.security import check_password_hash

@bp_authcontroller.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        form = LoginForm(request.form)
        # Query database for user and validate password
        if user and check_password_hash(user.password_hash, form.password.data):
            # Create session variables and redirect
            return redirect(url_for('protected_page'))
        else:
            flash('Invalid username or password')
            return redirect(url_for('bp_authcontroller.login'))
```

Protected Page

To protect a route, use the `@login_required` decorator from Flask-Login. This decorator ensures that only authenticated users can access the route.

```python
from flask_login import login_required

@bp_homecontroller.route('/dashboard')
@login_required
def dashboard():
    # Retrieve session variables or use current_user
    return render_template('dashboard.html', user=current_user)
```

Custom Unauthorized Page

Define a custom unauthorized handler to handle cases where a user tries to access a protected route without authentication.

```python
@login_manager.unauthorized_handler
def unauthorized():
    return render_template('unauthorized.html'), 403
```

Logout Functionality

To log out a user, simply call `logout_user()` from Flask-Login.

```python
from flask_login import logout_user

@bp_authcontroller.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('bp_authcontroller.login'))
```

Implementing authentication and protected pages in Python Flask is crucial for building secure web applications. With Flask-Login, you can streamline the process and focus on creating robust user authentication mechanisms while ensuring the security of your application.

Source Code on GitHub
Click here to access or download the source code.

Share:

Categories:
Master the code, Change the World! Connect with a vibrant community of coders and launch your tech dreams.