JA
header image

枝折 - bookmark

Building E-Commerce Features with Flask ③

Python

CREATED: 2024 / 04 / 07 Sun

UPDATED: 2024 / 04 / 07 Sun

Adding authentication.

Adding Authentication

This time we add authentication. Libraries like Flask-Login exist for this, but let’s implement it without them.

The authentication method will be password-based. Password management follows the Modular Crypt Format (MCF).

As described on the passlib page, MCF is a standard format for hashed passwords and is commonly used in authentication features of popular frameworks.

MCF passwords are stored as a $-delimited string containing the algorithm version, stretching parameter, salt, and hash value:

$2a$12$M1VFsgOHnMfB5q.XHX9UwuYTlURtdN9Y2Jmoj3ZkxxBSrJc8r1V.6

For the hash algorithm, it’s recommended to use a slow algorithm like bcrypt rather than a fast one like MD5 (this article by Tokumaru is a helpful read). Hashed passwords using such slow algorithms are not impossible to crack, but salt and stretching make cracking time-consuming enough to allow for password rotation before a breach occurs.

Here, we use bcrypt to generate MCF-compliant hashed passwords.

In practice, depending on your development requirements, PBKDF2 or Argon2id might be better choices. These references may help:

Saving a Password on User Creation

First, add a password column to the User model created in the previous article:

class User(db.Model):
    __tablename__ = 'users'
    id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
    name: Mapped[str] = mapped_column(db.String(20), unique=True, nullable=False)
    email: Mapped[str] = mapped_column(db.String(100), unique=True, nullable=False)
    password: Mapped[str] = mapped_column(db.String(100), unique=True, nullable=False)
    purchase_transactions: Mapped[List['PurchaseTransaction']] = db.relationship(back_populates='user', cascade='all, delete-orphan')
    created: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
    updated: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
    def __repr__(self) -> str:
        return f'User(id={self.id!r}, name={self.name!r}, created={self.created!r}, updated={self.updated!r})'

Running flask db migrate and flask db upgrade applies this to the DB. If you already have data, the missing default value for password will cause an error — in that case, delete db/data and restart the container.

Then generate a hashed password in the sign_up() API from the previous article. First, install bcrypt and import it in main.py:

bcrypt>=4.1.0,<5.0
import bcrypt

@app.route("/sign_up", methods=('GET', 'POST'))
def sign_up():
    form = SignUpForm(request.form)
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data
        password = form.password.data # Get password from form

        # Generate salt
        # Stretching parameter = 12 (10 or above recommended) = 2^12 stretching iterations
        # Specify bcrypt version 2b (latest)
        salt = bcrypt.gensalt(rounds=12, prefix=b'2b')

        # Hash the password with salt to generate an MCF hashed password
        hashpw = bcrypt.hashpw(password.encode('utf8'), salt)

        # Save the generated hashed password to the User record
        user = User(name=name, email=email, password=hashpw.decode('utf8'))
        db.session.add(user)
        db.session.commit()

        # Add email to session variable
        session['email'] = user.email
        return redirect(url_for('products'))
    return render_template('sign_up.html', form=form)

The MCF hashed password is now saved, and from the next request onwards we can identify the current logged-in user by checking the session email. Let’s also add sign-in and sign-out APIs:

@app.route("/sign_in", methods=('GET', 'POST'))
def sign_in():
    form = SignInForm(request.form)
    if form.validate_on_submit():
        email = form.email.data
        password = form.password.data
        user = db.session.execute(db.select(User).filter_by(email=email)).scalar_one()

        # Check if the entered password matches the stored hashed password
        if bcrypt.checkpw(password.encode('utf8'), user.password.encode('utf8')):
            session['email'] = user.email
            return redirect(url_for('products'))
    return render_template('sign_in.html', form=form)

@app.route("/products")
def products():
    form = SignOutForm(request.form)
    products = db.session.query(Product).all()
    return render_template('products.html', products=products, form=form)

Sign-out is accessible from the product list page.

<!-- sign_in.html -->
{% extends 'base.html' %} {% from "_formhelpers.html" import render_field %} {% block header %}
<h1>{% block title %}SignIn{% endblock %}</h1>
{% endblock %} {% block content %}
<section>
	<form method="post">
		{{ form.csrf_token }}
		<dl>
			{{ render_field(form.email, placeholder="email") }} {{ render_field(form.password,
			placeholder="password") }}
		</dl>
		<input type="submit" value="Sign In" />
	</form>
</section>
{% endblock %}
<!-- products.html -->
<!-- omitted -->
<form action="/sign_out" method="post">
	{{ form.csrf_token }}
	<input type="submit" value="Sign Out" />
</form>
<!-- omitted -->

For screens that require sign-in, add a check for the session email variable:

@app.route("/products")
def products():
    if 'email' in session: # Check if session email exists
        form = SignOutForm(request.form)
        products = db.session.query(Product).all()
        return render_template('products.html', products=products, form=form)
    return redirect(url_for('sign_in')) # Redirect to sign-in if email not in session

Appendix

This article covered saving passwords with MCF and implementing authentication. In practice, rather than rolling your own (even though password hashing/verification is handled by the bcrypt library), using a library or framework feature that wraps this kind of functionality is usually the better approach.

Next: error handling and testing, which will wrap up the Flask series.