0
0
FlaskHow-ToBeginner · 4 min read

How to Use current_user in Flask for User Authentication

In Flask, current_user is provided by the Flask-Login extension to access the currently logged-in user object anywhere in your code. You use it by importing current_user from flask_login after setting up Flask-Login in your app. It helps you check if a user is authenticated and access their properties easily.
📐

Syntax

The current_user object is imported from flask_login and represents the user currently logged in. You can check if a user is authenticated with current_user.is_authenticated and access user attributes like current_user.id or current_user.username.

Example usage:

  • from flask_login import current_user — import the object
  • current_user.is_authenticated — check login status
  • current_user.attribute — access user data
python
from flask_login import current_user

if current_user.is_authenticated:
    print(f"User ID: {current_user.id}")
else:
    print("No user logged in")
Output
User ID: 1 # (if logged in) or No user logged in
💻

Example

This example shows a minimal Flask app using Flask-Login with current_user to display a welcome message if the user is logged in or a prompt to log in otherwise.

python
from flask import Flask, render_template_string, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, current_user, logout_user

app = Flask(__name__)
app.secret_key = 'secret-key'

login_manager = LoginManager()
login_manager.init_app(app)

# Simple user class
class User(UserMixin):
    def __init__(self, id):
        self.id = id

# User loader callback
@login_manager.user_loader
def load_user(user_id):
    return User(user_id)

@app.route('/')
def index():
    if current_user.is_authenticated:
        return f"<h1>Welcome, User {current_user.id}!</h1><a href='/logout'>Logout</a>"
    else:
        return "<h1>Please log in</h1><a href='/login'>Login</a>"

@app.route('/login')
def login():
    user = User('1')
    login_user(user)
    return redirect(url_for('index'))

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)
Output
When visiting '/', shows 'Please log in' with a login link initially. After clicking login, shows 'Welcome, User 1!' with a logout link.
⚠️

Common Pitfalls

  • Not initializing LoginManager or not calling login_manager.init_app(app) causes current_user to be unavailable.
  • Forgetting to implement the user_loader callback means Flask-Login cannot load user objects.
  • Trying to use current_user outside a request context (like in background threads) will fail.
  • Assuming current_user is always authenticated without checking current_user.is_authenticated can cause errors.

Wrong way:

if current_user.id:
    print("User ID:", current_user.id)

Right way:

if current_user.is_authenticated:
    print("User ID:", current_user.id)
📊

Quick Reference

UsageDescription
from flask_login import current_userImport the current_user proxy object
current_user.is_authenticatedCheck if a user is logged in
current_user.idGet the logged-in user's ID
current_user.usernameGet the logged-in user's username (if defined)
login_user(user)Log in a user to set current_user
logout_user()Log out the current user

Key Takeaways

Import current_user from flask_login after setting up Flask-Login in your app.
Always check current_user.is_authenticated before accessing user attributes.
Implement user_loader callback to load user objects by ID.
Use current_user inside request context only, like in routes or templates.
current_user helps manage and access the logged-in user easily in Flask apps.