IC Improve Code Recipes

Recipe 16.1 · Python

Replacing the BasePage with Filters

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Every page in the application inherits from a BasePage class. It checks that the user is logged in, loads the user's permissions, decides whether this page is allowed, writes an audit record and sets the culture. It works, but it runs everything on every page whether the page needs it or not, it's impossible to test without a web server, and every new concern makes it longer.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The permission check is keyed on the file name, so renaming a page breaks security. The audit write runs synchronously against the database on every request, including postbacks. And because the user lives in session, a recycled app pool logs everyone out.

Requirements: Python 3.12+. Install: pip install flask

Python A base page class that does login, authorization, culture and auditing in one hook (p351_r16_1_base_page_init_before.py)
"""A base page class that does login, authorization, culture and auditing in one hook

Source: ImproveCode, Chapter 16, Recipe 16.1 "Replacing the BasePage with Filters"
Section: The way it's often written
Book page: 351  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
The Web Forms Page base class becomes a Flask MethodView base; Thread.CurrentCulture
becomes process-wide locale.setlocale; Security/AuditDb are placeholders as in the book.
"""

import locale
import posixpath
from typing import Any

from flask import redirect, request, session
from flask.views import MethodView


class Security:  # placeholder, as in the original
    @staticmethod
    def can_view(user_id: int, page: str) -> bool: ...


class AuditDb:  # placeholder, as in the original
    @staticmethod
    def log_page_view(user_id: int, page: str) -> None: ...


# Not to copy: one base class doing everything.
class BasePage(MethodView):
    current_user: Any = None

    def dispatch_request(self, *args: Any, **kwargs: Any) -> Any:
        self.current_user = session.get("User")
        if self.current_user is None:
            return redirect("/Login.aspx?ReturnUrl=" + request.full_path)

        page = posixpath.basename(request.path)
        if not Security.can_view(self.current_user["UserId"], page):
            return redirect("/NoAccess.aspx")

        locale.setlocale(locale.LC_ALL, self.current_user["Culture"])
        AuditDb.log_page_view(self.current_user["UserId"], page)
        return super().dispatch_request(*args, **kwargs)

The improved recipe

In ASP.NET Core, each job goes to the part of the pipeline built for it. Authentication and "is the user logged in" become a fallback authorization policy. Per-page permissions become an authorization filter. Auditing becomes an action filter. A base controller remains, but it holds only small conveniences.

The audit filter runs around every action and logs instead of writing to a table inline:

A thin base controller and the registration:

Usage snippet:

Requirements: Python 3.12+. Install: pip install fastapi

Python Permission check as a reusable, declarative authorization dependency (p351_r16_1_require_permission_dependency.py)
"""Permission check as a reusable, declarative authorization dependency

Source: ImproveCode, Chapter 16, Recipe 16.1 "Replacing the BasePage with Filters"
Section: The improved recipe
Book page: 351-352  -- original C# listing
Converted from C# to Python.
ASP.NET Core IAsyncAuthorizationFilter attribute becomes a FastAPI dependency class;
ClaimsPrincipal becomes a small frozen Principal (set on request.state.user by the
auth middleware); ChallengeResult/ForbidResult become HTTP 401/403.
"""

from dataclasses import dataclass, field
from typing import Annotated, Protocol

from fastapi import Depends, HTTPException, Request, status


@dataclass(frozen=True)
class Principal:
    name: str | None = None
    is_authenticated: bool = False
    claims: tuple[tuple[str, str], ...] = field(default=())

    def has_claim(self, claim_type: str, value: str) -> bool:
        return (claim_type, value) in self.claims

    def find_first_value(self, claim_type: str) -> str | None:
        return next((v for t, v in self.claims if t == claim_type), None)


ANONYMOUS = Principal()


class PermissionService(Protocol):
    async def has_permission(self, user: Principal, permission: str) -> bool: ...


class ClaimsPermissionService:
    async def has_permission(self, user: Principal, permission: str) -> bool:
        return user.has_claim("permission", permission)


def get_current_user(request: Request) -> Principal:
    return getattr(request.state, "user", ANONYMOUS)


def get_permission_service(request: Request) -> PermissionService:
    return request.app.state.permission_service


class RequirePermission:
    """Use as Depends(RequirePermission("Invoices.View")); several may be stacked."""

    def __init__(self, permission: str) -> None:
        self.permission = permission

    async def __call__(
        self,
        user: Annotated[Principal, Depends(get_current_user)],
        permissions: Annotated[PermissionService, Depends(get_permission_service)],
    ) -> None:
        if not user.is_authenticated:
            raise HTTPException(status.HTTP_401_UNAUTHORIZED)  # challenge

        if not await permissions.has_permission(user, self.permission):
            raise HTTPException(status.HTTP_403_FORBIDDEN)  # forbid

Requirements: Python 3.12+. Install: pip install starlette

Python Audit every action: who called it, what it returned and how long it took (p352_r16_1_page_audit_timing_middleware.py)
"""Audit every action: who called it, what it returned and how long it took

Source: ImproveCode, Chapter 16, Recipe 16.1 "Replacing the BasePage with Filters"
Section: The improved recipe
Book page: 352-353  -- original C# listing
Converted from C# to Python.
The global IAsyncActionFilter becomes Starlette HTTP middleware; ILogger becomes the
logging module; Stopwatch becomes time.perf_counter; the result type is reported as
the response status code.
"""

import logging
import time
from collections.abc import Awaitable, Callable

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response

logger = logging.getLogger(__name__)


class PageAuditMiddleware(BaseHTTPMiddleware):
    async def dispatch(
        self, request: Request, call_next: Callable[[Request], Awaitable[Response]]
    ) -> Response:
        started = time.perf_counter()
        response = await call_next(request)

        endpoint = request.scope.get("endpoint")
        user = getattr(request.state, "user", None)
        logger.info(
            "Action %s by %s returned %s in %.0f ms",
            getattr(endpoint, "__qualname__", request.url.path),
            getattr(user, "name", None) or "(anonymous)",
            response.status_code,
            (time.perf_counter() - started) * 1000,
        )
        return response

Requirements: Python 3.12+. Install: pip install fastapi

Python Thin controller helpers plus app-wide audit, fallback-auth and policy setup (p353_r16_1_app_controller_and_auth_setup.py)
"""Thin controller helpers plus app-wide audit, fallback-auth and policy setup

Source: ImproveCode, Chapter 16, Recipe 16.1 "Replacing the BasePage with Filters"
Section: The improved recipe
Book page: 353  -- original C# listing
Converted from C# to Python.
The AppController base becomes helper functions; AddAppMvc becomes add_app_mvc(app)
registering the audit middleware, a fallback "authenticated user" dependency, named
role policies and the permission service on app.state (FastAPI in place of ASP.NET Core).
"""

from collections.abc import Awaitable, Callable
from typing import Annotated
from urllib.parse import urlsplit

from fastapi import Depends, FastAPI, HTTPException, Request, status
from fastapi.responses import RedirectResponse

from p351_r16_1_require_permission_dependency import (
    ClaimsPermissionService,
    Principal,
    get_current_user,
)
from p352_r16_1_page_audit_timing_middleware import PageAuditMiddleware

NAME_IDENTIFIER = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
ROLE = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"


def current_user_id(user: Principal) -> str:
    value = user.find_first_value(NAME_IDENTIFIER)
    if value is None:
        raise RuntimeError("No signed-in user.")
    return value


def _is_local_url(url: str | None) -> bool:
    if not url:
        return False
    parts = urlsplit(url)
    return (
        not parts.scheme
        and not parts.netloc
        and url.startswith("/")
        and not url.startswith("//")
        and not url.startswith("/\\")
    )


def redirect_to_local(request: Request, return_url: str | None) -> RedirectResponse:
    if _is_local_url(return_url):
        return RedirectResponse(return_url, status.HTTP_302_FOUND)  # type: ignore[arg-type]
    return RedirectResponse(request.url_for("home_index"), status.HTTP_302_FOUND)


def require_authenticated_user(
    user: Annotated[Principal, Depends(get_current_user)],
) -> None:
    if not user.is_authenticated:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED)


def require_role(role: str) -> Callable[[Principal], Awaitable[None]]:
    async def check(user: Annotated[Principal, Depends(get_current_user)]) -> None:
        if not user.is_authenticated:
            raise HTTPException(status.HTTP_401_UNAUTHORIZED)
        if not user.has_claim(ROLE, role):
            raise HTTPException(status.HTTP_403_FORBIDDEN)

    return check


POLICIES = {
    "Finance": require_role("Finance"),
    "Admin": require_role("Admin"),
}


def add_app_mvc(app: FastAPI) -> FastAPI:
    app.add_middleware(PageAuditMiddleware)

    # Fallback policy: every route needs a signed-in user unless its router
    # is mounted without this dependency (the equivalent of [AllowAnonymous]).
    app.router.dependencies.append(Depends(require_authenticated_user))

    app.state.policies = POLICIES
    app.state.permission_service = ClaimsPermissionService()
    return app

Requirements: Python 3.12+. Install: pip install fastapi

Python Declare a permission requirement on a single endpoint (p354_r16_1_require_permission_on_endpoint.py)
"""Declare a permission requirement on a single endpoint

Source: ImproveCode, Chapter 16, Recipe 16.1 "Replacing the BasePage with Filters"
Section: The improved recipe
Book page: 354  -- original C# listing
Converted from C# to Python.
The [RequirePermission] attribute becomes a FastAPI route dependency.
"""

from fastapi import APIRouter, Depends

from p351_r16_1_require_permission_dependency import RequirePermission

router = APIRouter()


@router.get("/invoices", dependencies=[Depends(RequirePermission("Invoices.View"))])
async def index(page: int = 1) -> None:
    ...

How it works

The fallback policy applies to every endpoint that has no authorization attribute of its own, so a new controller is protected by default. That reverses the Web Forms habit of forgetting to inherit from BasePage on one page and leaving it open. Pages that must be public, such as the login page, opt out with [AllowAnonymous].

RequirePermissionAttribute is an authorization filter, which runs before model binding and before the action. It names the permission, not the file, so renaming a controller doesn't change who can see it. Returning ChallengeResult sends an anonymous user to sign in; ForbidResult gives a signed-in user without the permission a 403. The filter resolves IPermissionService from the request's services, so the real implementation can query a database and cache the result (Chapter 3) without the attribute knowing.

PageAuditFilter is registered globally, so it wraps every action. It awaits next(), measures the elapsed time and logs a structured event. If you need an audit table for compliance, have a logging sink or a background queue (Chapter 14) write it, not the request thread.

Culture, which the BasePage set by hand, is handled by the built-in request localization middleware (app.UseRequestLocalization()), and errors by the exception handler middleware from Chapter 5.

Variations and pitfalls

  • Keep the base controller thin. When it starts loading data in its constructor or overriding OnActionExecuting, you are rebuilding BasePage. Put behavior in filters and services; put only tiny helpers in the base class.
  • Razor Pages use page filters (IAsyncPageFilter) and work best with policies: [Authorize(Policy = "Finance")]. For permission-per-page schemes across MVC, Razor Pages and minimal APIs, write an IAuthorizationHandler with a custom requirement instead of a filter.
  • ClaimsPermissionService reads permissions from claims, which suits small permission sets. With hundreds of permissions, don't stuff them into the cookie; look them up and cache them.
  • Filters registered with options.Filters.Add<T>() are created per request through dependency injection, so constructor injection works. Attributes like RequirePermission are created once, which is why the service is resolved inside the method.