Skip to content

Middleware & Guards

Protecting an entire section of your application—like an admin dashboard or a user settings area—is as easy as dropping a _guard.py file into a directory.

How Guards Work

Albedo executes guards from the top down. If a user requests /admin/users/42, Albedo checks for a _guard.py file in /admin, then /admin/users, and finally /admin/users/42. These execute before your loader() or action() ever runs.

Guards are standard FastAPI dependencies. This means they support auto-injection for the request object and your database db session.

Redirecting Unauthorized Users

If a guard determines a user should not access a route, you do not return a standard response. Instead, raise an HTTPException with a 303 status code. Albedo catches this and instantly bounces the browser to the new location.

app/pages/admin/_guard.py

from fastapi import Request, HTTPException
from sqlalchemy.orm import Session
from app.models.user import User

def guard(request: Request, db: Session):
    auth_token = request.cookies.get("session_token")

    # If the user is missing a token, bounce them to login
    if not auth_token:
        raise HTTPException(status_code=303, headers={"Location": "/login"})

    # Example: Check the database to see if the user is an admin
    user = db.query(User).filter(User.token == auth_token).first()
    if not user or not user.is_admin:
        raise HTTPException(status_code=303, headers={"Location": "/unauthorized"})