Skip to main content

Overview

The @CrudAuth decorator is a class decorator that adds authentication and authorization capabilities to your CRUD controller. It allows you to filter queries based on user context, persist user data in create/update operations, and control serialization based on user permissions.

Signature

Parameters

AuthOptions
required
Authentication and authorization configuration
string
default:"user"
The property name where the authenticated user is stored in the request object (e.g., req.user)
(req: any) => SCondition | void
Function that returns filter conditions based on the request. These conditions are applied to all read operations using AND logic.Parameters:
  • req - The request object containing the authenticated user
Returns: Filter condition object or void
(req: any) => SCondition | void
Function that returns filter conditions to be applied using OR logic. Useful for scenarios where a user can access their own resources OR shared resources.Parameters:
  • req - The request object containing the authenticated user
Returns: Filter condition object or void
(req: any) => ObjectLiteral
Function that returns data to be persisted in create and update operations. Commonly used to set the owner/creator of a resource.Parameters:
  • req - The request object containing the authenticated user
Returns: Object with fields to persist
(req: any) => ClassTransformOptions
Function that returns class-transformer options for serialization based on the request context.Parameters:
  • req - The request object containing the authenticated user
Returns: ClassTransformOptions object
(req: any) => string[]
Function that returns serialization groups based on the request context. These groups are used by class-transformer to include/exclude fields.Parameters:
  • req - The request object containing the authenticated user
Returns: Array of group names

Usage

Basic Authentication Filter

This ensures users can only see their own posts.

Persist User Data on Create

When a user creates a post, their userId and email are automatically added to the entity.

Using OR Conditions

Users can access documents they own OR documents shared with them.

Role-Based Serialization

Combine with class-transformer groups in your entity:

Complete Example

Integration Test Example

From the source tests:
packages/crud/test/crud-request.interceptor.spec.ts:62-86

Implementation Details

The decorator stores auth options in metadata:
packages/crud/src/decorators/crud-auth.decorator.ts:4-8
The @CrudAuth decorator should be used in combination with @Crud. Apply both decorators to the controller class, with @Crud typically placed first.
Ensure your authentication guard is properly configured to populate the user object in the request. The property option should match where your guard stores the authenticated user.

See Also