Labs ICT
โญ Pro Login

User Authentication

Login, logout, and session management.

User Authentication

Most web apps need user accounts. You need to let people register, log in, and protect certain pages so only authenticated users can see them. Flask-Login handles the heavy lifting of session management so you can focus on the actual logic.

Flask-Login Setup

Install Flask-Login and configure it with your app. You'll need a User model that follows Flask-Login's requirements.

from flask_login import LoginManager, UserMixin

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'auth.login'  # Redirect here if not logged in

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

The UserMixin class gives you default implementations of the methods Flask-Login needs. The user_loader callback is how Flask-Login fetches a user from the database using the stored session ID.

Password Hashing

Never, ever store plain text passwords. Use werkzeug's security functions to hash passwords before storing them and verify them on login.

from werkzeug.security import generate_password_hash, check_password_hash

class User(db.Model, UserMixin):
    # ... columns ...

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

generate_password_hash() creates a salted hash that's virtually impossible to reverse. check_password_hash() compares a plain password against the stored hash. Even if your database is compromised, attackers can't recover the original passwords.

Registration and Login

Here's how registration and login routes work with Flask-Login.

from flask_login import login_user, logout_user, login_required

@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if User.query.filter_by(username=username).first():
            flash('Username already taken')
            return redirect(url_for('auth.register'))

        user = User(username=username)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()

        login_user(user)
        return redirect(url_for('main.index'))
    return render_template('auth/register.html')

@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            login_user(user)
            return redirect(url_for('main.index'))
        flash('Invalid credentials')
    return render_template('auth/login.html')

@bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('main.index'))

@login_required

The @login_required decorator protects routes. If a user isn't logged in, they're redirected to the login page. Use it on any route that should be behind authentication.

@app.route('/dashboard')
@login_required
def dashboard():
    return render_template('dashboard.html')

Session Management

Flask-Login stores the user ID in Flask's session, which is a signed cookie. The session persists across requests but expires when the browser closes (unless you configure remember). You don't have to manage sessions manually โ€” Flask-Login handles it all.

Why Never Store Plain Passwords

If your database is ever exposed โ€” through a SQL injection, a backup leak, or a misconfigured server โ€” plain text passwords give attackers immediate access to every user's account. Hashed passwords are useless to attackers because they can't reverse the hash. It's one of the most important security practices in web development.

Try it Yourself ->

๐Ÿงช Quick Quiz

What is Flask-Login used for?