Skip to content

Authentication

Authentication¶

The routes/authentication.py file defines the authentication subsystem for the Flask app as a reusable blueprint. it's purpose is to centralize login/logout behavior, enforce rate limiting on login attempts, and provide a blueprint that can be registered on the main Flask app to enable password-based access control using a single shared secret.

Functionally, it:

  • Creates an authentication blueprint
    • create_authentication_blueprint(limiter, logger=None) constructs and returns a Blueprint named "authenticator".
    • It accepts:
      • A Limiter instance (from flask_limiter) used to rate-limit login attempts.
      • An optional Logger for recording authentication-related events (with a NullLogger fallback, though the current code doesn’t explicitly log yet).
  • Implements login logic (POST /login)
    • Exposed as /login on the authentication blueprint.
    • Protected by @limiter.limit("5 per minute"), meaning each client can only attempt login five times per minute.
    • Reads the password field from request.form.
    • Compares the submitted password to current_app.secret_key:
      • If they match: sets session["authenticated"] = True.
      • If they do not match: uses flash("Invalid password", "danger") to send an error message to the UI.
    • Always redirects to / afterward (both success and failure).
  • Implements logout logic (GET /logout)
    • Exposed as /logout on the authentication blueprint.
    • Removes the authenticated flag from the session (session.pop("authenticated", None)).
    • Redirects the user back to / (the landing or main page).

The file src/auth.py defines simple authentication utilities for a Flask application. Its primary purpose is to:

  • Provide a helper to check whether the current user is authenticated based on the Flask session.
  • Provide a decorator to protect view functions, ensuring only authenticated users can access them and redirecting unauthenticated users to a landing page.

In the larger system, this module centralizes basic auth checks so route handlers can easily enforce authentication without duplicating logic.

🔌 API¶

authentication ¶

Functions:

Name Description
create_authentication_blueprint

Creates and configures the Flask blueprint for user authentication.

create_authentication_blueprint(limiter, logger=None) ¶

Creates and configures the Flask blueprint for user authentication.

Sets up routes for user login and logout, applies rate limiting to login attempts, and provides logging support.

Parameters:

Name Type Description Default
limiter Limiter

The Flask-Limiter instance for rate limiting login attempts.

required
logger Logger | None

Optional logger for logging authentication events. Uses NullLogger if not provided.

None

Returns:

Name Type Description
Blueprint Blueprint

The configured Flask blueprint for authentication.

Source code in src/routes/authentication.py
def create_authentication_blueprint(limiter: Limiter, logger: Logger | None = None) -> Blueprint:
    """
    Creates and configures the Flask blueprint for user authentication.

    Sets up routes for user login and logout, applies rate limiting to login attempts, and provides logging support.

    Args:
        limiter (Limiter): The Flask-Limiter instance for rate limiting login attempts.
        logger (Logger | None): Optional logger for logging authentication events. Uses NullLogger if not provided.

    Returns:
        Blueprint: The configured Flask blueprint for authentication.
    """

    authenticator = Blueprint("authenticator", __name__)

    logger: Logger = logger or NullLogger()

    # === Authentication Routes ===
    @authenticator.route("/login", methods=["POST"])
    @limiter.limit("5 per minute")
    def login() -> Response:
        """
        Authenticates a user based on the submitted password.

        Checks the provided password against the configured password and sets the session as authenticated if correct.
        Redirects to the mixtapes page on success or flashes an error and redirects to the landing page on failure.

        Returns:
            Response: The Flask response object for the appropriate redirect.
        """
        password = request.form.get("password")
        if password == current_app.secret_key:
            session["authenticated"] = True
        else:
            flash("Invalid password", "danger")
        return redirect("/")

    @authenticator.route("/logout")
    def logout() -> Response:
        """
        Logs out the current user by removing authentication from the session.

        Clears the user's session and redirects to the landing page.

        Returns:
            Response: The Flask response object for the redirect to the landing page.
        """
        session.pop("authenticated", None)
        return redirect("/")

    return authenticator

auth ¶

Functions:

Name Description
check_auth

Checks if the current user is authenticated.

require_auth

Decorator that enforces authentication for a view function.

check_auth() ¶

Checks if the current user is authenticated.

Returns True if the user is authenticated in the session, otherwise False.

Returns:

Name Type Description
bool bool

Authentication status of the current user. Returns True only if the

bool

session "authenticated" flag is explicitly set to True.

Source code in src/auth.py
def check_auth() -> bool:
    """
    Checks if the current user is authenticated.

    Returns True if the user is authenticated in the session, otherwise False.

    Returns:
        bool: Authentication status of the current user. Returns True only if the
        session "authenticated" flag is explicitly set to True.
    """
    return session.get("authenticated") is True

require_auth(view) ¶

Decorator that enforces authentication for a view function.

Redirects unauthenticated users to the landing page before allowing access to the decorated view.

Parameters:

Name Type Description Default
view Callable

The view function to be protected.

required

Returns:

Name Type Description
function Callable

The wrapped view function with authentication enforcement.

Source code in src/auth.py
def require_auth(view: Callable) -> Callable:
    """
    Decorator that enforces authentication for a view function.

    Redirects unauthenticated users to the landing page before allowing access to the decorated view.

    Args:
        view: The view function to be protected.

    Returns:
        function: The wrapped view function with authentication enforcement.
    """
    from functools import wraps
    @wraps(view)
    def wrapper(*args, **kwargs):
        if not check_auth():
            return redirect(url_for("landing"))
        return view(*args, **kwargs)
    return wrapper