Skip to main content

Overview

The @CrudAuth() decorator provides built-in authentication and authorization for CRUD operations. It allows you to filter queries, persist user data, and control access based on the authenticated user.

Basic Usage

Apply the @CrudAuth() decorator to your controller:
me.controller.ts
This ensures users can only access their own data.

Configuration Options

The @CrudAuth() decorator accepts an AuthOptions object:

Filter

Automatically filter queries based on the authenticated user:
The filter is applied to all read operations (getMany, getOne).

Persist

Automatically add user data to create/update operations:
my-projects.controller.ts
The persist function automatically adds userId to all create and update requests.

OR Conditions

Add OR conditions to your filters:
This allows users to see records they own OR are assigned to.

Class Transform Options

Customize serialization based on the user:

Groups

Shorthand for setting serialization groups:

Global Configuration

Set global authentication settings in main.ts:
main.ts
The property option specifies where to find the authenticated user on the request object (e.g., req.user).

Complete Example

Here’s a comprehensive authentication setup:
projects.controller.ts

Using with Guards

Combine with NestJS guards for authentication:
auth.guard.ts
Apply globally:
app.module.ts

Multi-Tenancy Example

Implement multi-tenancy with company-based filtering:
users.controller.ts

Advanced Filtering

Use complex conditions in your filters:

Request Property

Access the user from different request properties:

Security Best Practices

Always validate and sanitize user input, even when using @CrudAuth(). The decorator filters data but doesn’t prevent malicious requests.
1

Always Use Guards

Combine @CrudAuth() with authentication guards to ensure only authenticated users can access endpoints.
2

Filter Sensitive Data

Use the filter option to ensure users can only access their own data or data they’re authorized to see.
3

Validate Ownership

For update and delete operations, ensure users can only modify resources they own.
4

Use Serialization

Combine with serialization to control which fields different user roles can see.

Troubleshooting

User Not Found on Request

If the user object is not found:
  1. Ensure your authentication guard sets request.user
  2. Verify the property configuration matches your setup
  3. Check that the guard executes before CRUD operations

Filters Not Applied

If filters aren’t working:
  1. Verify the filter function returns a valid condition object
  2. Check that field names match your entity properties
  3. Ensure the user object has the expected properties