Flask Login WITHOUT a library - Minimal tutorial

The reason why many of us use flask is that it has less black magic than Django. We want a minimal web framework that we can fully understand nad modify just by looking at the code.

However, today, when you search for “Flask Login” and even “Flask Login without a library” all you get is how to use “Flask-login” module, or how to implement login systems with CORS and JWT and some other fancy stuff.

This article lists how you can create a simple login system with flask, and nothing else. No libraries. No extra features. Not even security. A minimal example of how to do it, not following any of the standard good practices.

Enough for testing and debugging.

The following code does not use external libraries, does not validate anything, it doesn’t encrypt the password either. It’s as simple (and stupid) as it gets, and yet, beautiful.

@app.route("/login", methods=["GET", "POST"])
def login():
    # check if the user is already logged in
    if session.get("user_id"):
        return redirect(url_for("index"))
    # check if the request method is POST
    if request.method == "POST":
        # get the username and password from the form
        username = request.form.get("username")
        password = request.form.get("password")
        # get the user from the database
        user = User.query.filter_by(name=username).first()
        # check if the username exists and the password is correct
        if user and user.password == password:
            # add the user id to the session
            session["user_id"] = user.id
            # redirect to the home page
            return redirect(url_for("index"))
        else:
            # display an error message
            flash("Wrong username or password")
    # display the login form
    return render_template("login.html")

That’s it. So when you want to create a simple login function, that’s basically what you need. Simple.

The full code

Create the templates

Create the folder templates in your project root and add these two files:

  • index.html
  • login.html

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to the Site!</h1>
    <p>If you see this page, you have successfully logged in.</p>
    <a href="/logout">Logout</a>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <button type="submit">Login</button>
    </form>
</body>
</html>

Create the app.py file

Add the following code

from flask import Flask, request, session, redirect, url_for, render_template, flash

app = Flask(__name__)
app.secret_key = 'your_secret_key'

# Dummy database of users
users = {'user1': 'password1', 'admin': 'adminpass'}

@app.route('/')
def index():
    if 'user_id' in session:
        return render_template('index.html')
    return redirect(url_for('login'))

@app.route("/login", methods=["GET", "POST"])
def login():
    if 'user_id' in session:
        return redirect(url_for("index"))
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        # Dummy user validation
        if username in users and users[username] == password:
            session['user_id'] = username
            return redirect(url_for('index'))
        else:
            flash('Wrong username or password')
    return render_template("login.html")

@app.route("/logout")
def logout():
    # Remove the user_id from the session
    session.pop('user_id', None)
    # Redirect to login page
    return redirect(url_for('login'))

if __name__ == "__main__":
    app.run(debug=True)
Manuel Levi
Written by

Manuel Levi

Try to keep up.