@authenticate(role='admin') def admin_only(): return 'secret'
Decorators & Metaclasses

Meaning

Applies a parameterized decorator to a function to enforce role-based access control before the function body executes. Eliminates the need to manually check permissions inside each handler, which scatters authorization logic and invites omission bugs. Reached for whenever a route or operation must be restricted to users holding a specific role.

Primary Function

Access control

Communicative Purpose

Ensures only authorized roles can invoke a function by declaratively attaching permission requirements at definition time

Pattern

@authenticate(role=role) def function_name(): ...

Core Structure

@authenticate(role=...) def ...(): ...

Função primária

Access control

Propósito comunicativo

Ensures only authorized roles can invoke a function by declaratively attaching permission requirements at definition time

Situações de gatilho

Web frameworks: guarding admin dashboard routes against regular user access REST APIs: restricting DELETE endpoints to users with the 'admin' role CLI applications: preventing non-privileged users from running destructive commands

Contextos

Flask, Django, FastAPI, Starlette, Click CLI, service middleware layers

Padrão

@authenticate(role=role) def function_name(): ...

Estrutura central

@authenticate(role=...) def ...(): ...

Slots de substituição

role: string naming the required authorization role, function_name: identifier for the protected function

Colocados típicos

  • functools.wraps
  • login_required
  • permission_required
  • request.user
  • session authentication
  • HTTPException

Substituições comuns

  • Manual if-check inside function body (more flexible but scatters auth logic)
  • class-based mixins (heavier but composable with multiple concerns)
  • middleware-level auth (centralized but less granular per-endpoint)

Erros comuns

1. Forgetting parentheses on decorator without args (@authenticate instead of @authenticate()) — causes the function object to be passed as the role parameter instead of being wrapped. 2. Applying decorator after function definition instead of before — Python syntax requires @ syntax before def. 3. Using a role string that doesn't match any defined role constant — silently grants no access or raises at runtime with no compile-time safety. 4. Not returning the wrapper's return value inside the decorator implementation — the decorated function appears to return None.

Similar / contraste

@login_required (checks authentication only, not role), @permission_required (Django-specific, checks specific permission not role), RBAC middleware (enforces at routing layer not function layer)

Interferências

Coming from Java: may expect annotation-based auth to be enforced at compile time — Python decorators execute at import time and enforce at runtime only

Família do chunk

  • decorator with parameters
  • role-based access control
  • function wrapping
  • authentication decorators
  • authorization patterns

Nuance

1. Not suitable when authorization depends on runtime request data beyond the user's role (e.g., ownership checks comparing request.user.id to object.owner_id). 2. The role argument is evaluated at decoration time (module import), not at call time, so it must be a static string or import-time constant. 3. Stacking multiple auth decorators evaluates top-to-bottom, so the outermost decorator runs first — order matters for combined checks.

Efeito pragmático

Prevents unauthorized access at the function boundary, keeping authorization logic centralized and auditable rather than scattered across handler bodies

Dica de memória

Like a bouncer checking VIP wristbands at the door — the decorator stands at the entrance and turns away anyone without the right role before they even get inside.

Nota

The decorator factory must return a closure that calls the original function and returns its result; otherwise the decorated function's return value is silently discarded.

Upgrade path

Custom parameterized decorators with multiple conditions, class-based permission mixins, or policy-based authorization frameworks like Casbin

Frequência: HighFormulaicidade: Semi-fixedTipo de construção: parameterized_decoratorPrioridade de aquisição: Active recallPrioridade de output: OutputTag de espaçamento: Short-term

Log in to save chunks.