Intermediate Flask: User Login, Registration, and Sessions

Table of Contents

  1. Overview
  2. Prerequisites
  3. Setup
  4. User Registration
  5. User Login
  6. Session Management
  7. Conclusion

Overview

In this tutorial, we will learn how to implement user login, registration, and session management in a Flask web application. By the end of this tutorial, you will be able to create a secure login and registration system for your Flask projects.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of the Flask framework and Python programming language. Familiarity with HTML and CSS will also be beneficial, but not mandatory.

Setup

Before we begin, make sure you have the necessary software installed on your machine. You will need the following:

  • Python 3.x
  • Flask
  • Flask-WTF
  • SQLAlchemy

You can install Flask and its dependencies using pip. Open your terminal or command prompt and run the following command: bash pip install flask flask-wtf sqlalchemy Now that we have the required dependencies installed, let’s create a new Flask project.

Create a new directory for your project and navigate to it in the terminal. Initialize a virtual environment by running the following commands: bash python -m venv venv source venv/bin/activate (for Mac/Linux) venv\Scripts\activate (for Windows) Next, create a new file called app.py: ```python from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run(debug=True)
``` Save the file and run the Flask development server using the following command:
```bash
python app.py
``` If everything is set up correctly, you should see the Flask app running at `http://127.0.0.1:5000`. Congratulations, you have set up your Flask project!

User Registration

In this section, we will implement user registration functionality in our Flask app. Users will be able to create an account by providing their name, email, and password.

Let’s start by creating a new route for the registration page in app.py: ```python from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Flask!'

@app.route('/register', methods=['GET', 'POST'])
def register():
    # Implementation goes here

if __name__ == '__main__':
    app.run(debug=True)
``` Next, we need to create a registration form using Flask-WTF. Create a new file called `forms.py` in the project directory and add the following code:
```python
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, EqualTo

class RegistrationForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Sign Up')
``` Now, let's go back to `app.py` and import the `RegistrationForm` class:
```python
from flask import Flask, render_template, redirect, url_for
from forms import RegistrationForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

@app.route('/')
def home():
    return 'Hello, Flask!'

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        # Create user and save to database
        return redirect(url_for('home'))
    return render_template('register.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)
``` In the code above, we create an instance of the `RegistrationForm` class and pass it to the `register.html` template. If the form is submitted and valid, we will redirect the user to the home page.

Now, let’s create the register.html template. Create a new directory called templates in the project directory, and inside it, create a new file called register.html with the following content: ```html

{% extends 'base.html' %}

{% block content %}
  <h2>Register</h2>
  <form method="POST" action="{{ url_for('register') }}">
    {{ form.hidden_tag() }}
    {{ form.name.label }} {{ form.name }}
    {{ form.email.label }} {{ form.email }}
    {{ form.password.label }} {{ form.password }}
    {{ form.confirm_password.label }} {{ form.confirm_password }}
    {{ form.submit }}
  </form>
{% endblock %}

``` Finally, let's create the base HTML template. In the `templates` directory, create a new file called `base.html` with the following content:
```html

<!DOCTYPE html>
<html>
<head>
  <title>My Flask App</title>
</head>
<body>
  {% block content %}{% endblock %}
</body>
</html>

``` That's it! Now you should be able to access the registration page at `http://127.0.0.1:5000/register` and register a new user.

User Login

In this section, we will implement user login functionality in our Flask app. Users will be able to log in to their accounts using their email and password.

First, let’s create a new route for the login page in app.py: ```python from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

@app.route('/')
def home():
    return 'Hello, Flask!'

@app.route('/register', methods=['GET', 'POST'])
def register():
    # Registration implementation

@app.route('/login', methods=['GET', 'POST'])
def login():
    # Implementation goes here

if __name__ == '__main__':
    app.run(debug=True)
``` Next, let's create a login form using Flask-WTF. Open the `forms.py` file and add the following code:
```python
class LoginForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Log In')
``` Now, let's go back to `app.py` and import the `LoginForm` class:
```python
from forms import RegistrationForm, LoginForm

# ...

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # Log in user and set session
        return redirect(url_for('home'))
    return render_template('login.html', form=form)

# ...
``` Next, let's create the `login.html` template. In the `templates` directory, create a new file called `login.html` with the following content:
```html

{% extends 'base.html' %}

{% block content %}
  <h2>Login</h2>
  <form method="POST" action="{{ url_for('login') }}">
    {{ form.hidden_tag() }}
    {{ form.email.label }} {{ form.email }}
    {{ form.password.label }} {{ form.password }}
    {{ form.submit }}
  </form>
{% endblock %}

``` Now, when you access `http://127.0.0.1:5000/login`, you should see the login form.

Session Management

In this section, we will implement session management to keep track of logged-in users. We will use Flask’s built-in session management feature.

First, let’s modify the register and login routes to set the session when the user successfully registers or logs in: ```python from flask import Flask, render_template, redirect, url_for, session

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

# ...

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        # Create user and save to database
        session['email'] = form.email.data
        return redirect(url_for('home'))
    return render_template('register.html', form=form)

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # Log in user and set session
        session['email'] = form.email.data
        return redirect(url_for('home'))
    return render_template('login.html', form=form)

# ...
``` Now, let's modify the `home` route to display the logged-in user's email:
```python
@app.route('/')
def home():
    if 'email' in session:
        return f'Hello, {session["email"]}!'
    return 'Hello, Flask!'
``` Finally, let's implement the logout functionality. Modify `app.py` to include a new route for logging out:
```python
@app.route('/logout')
def logout():
    session.pop('email', None)
    return redirect(url_for('home'))
``` That's it! You have successfully implemented user login, registration, and session management in Flask.

Conclusion

In this tutorial, we learned how to create a secure login and registration system in a Flask web application. We covered the following topics:

  • Setting up a Flask project and installing the necessary dependencies
  • Implementing user registration with validation using Flask-WTF
  • Creating a login form and handling user authentication
  • Managing user sessions to keep track of logged-in users

Remember to always validate user input and handle errors securely to protect your application from malicious attacks. You can further enhance the user experience by adding features like password reset, email verification, and user roles.

I hope you found this tutorial helpful. Happy coding with Flask!


Note: The code in this tutorial is for educational purposes only and may not be suitable for production environments. Always follow best practices and recommendations specific to your project and use case.