Validating data based on the authenticated user (accessible through request.user in many frameworks, including NestJS) within custom validators is a bit more involved than standard validation, as it requires accessing the request context within your validator. Here's a step-by-step guide on how to achieve this in NestJS:
1. Create a Custom Validator
First, create a custom validator. For this example, let's assume you want to validate if a user has permission to submit a certain type of content based on their role, which is stored in request.user.
typescript
// src/validators/is-authorized.validator.ts
import { ValidatorFn, ValidationArguments, registerDecorator } from 'class-validator';
export function IsAuthorized(allowedRoles: string[]) {
return (object: any, propertyName: string) => {
registerDecorator({
name: 'isAuthorized',
target: object.constructor,
propertyName: propertyName,
validator: {
async validate(value: any, args: ValidationArguments) {
// Access user roles from the object
const userRoles = args.object.userRoles;
// Check if the user has any of the allowed roles
return allowedRoles.some(role => userRoles.includes(role));
},
defaultMessage() {
return 'User does not have the required role';
},
},
});
};
}
export { IsAuthorized as isAuthorized }; // Optional alias
2. Accessing request.user within the Validator
To access request.user, you need to pass the user or the relevant user data to the validator. Since validators in Class-Validator (used by NestJS) are designed to work with the class-validator's constraints and not directly with the NestJS request context, you'll need to adapt your approach:
Approach A: Pass User Data Explicitly
Modify your validator to accept user data along with the allowed roles. This approach requires you to explicitly pass the user's role(s) when validating.
Usage in a DTO:
typescript
// src/dtos/example.dto.ts
import { IsAuthorized } from './validators/is-authorized.validator';
export class ExampleDto {
@IsAuthorized(['admin', 'moderator'])
content: string;
// You need to populate this field when calling the validation
userRoles: string[];
}
Populating userRoles and Validation in a Service:
typescript
// src/services/example.service.ts
import { Injectable } from '@nestjs/common';
import { ExampleDto } from './dtos/example.dto';
import { validate } from 'class-validator';
@Injectable()
export class ExampleService {
async doSomething(exampleDto: ExampleDto, userRoles: string[]) {
exampleDto.userRoles = userRoles; // Populate userRoles from request.user
const errors = await validate(exampleDto);
if (errors.length > 0) {
// Handle validation errors
}
// Proceed with validated data
}
}
In your controller, ensure that userRoles are extracted from request.user and passed to the service:
typescript
// src/controllers/example.controller.ts
import { Controller, Post, Body, Request } from '@nestjs/common';
import { ExampleService } from './example.service';
import { ExampleDto } from './dtos/example.dto';
@Controller('example')
export class ExampleController {
constructor(private readonly exampleService: ExampleService) {}
@Post()
async doSomething(@Body() exampleDto: ExampleDto, @Request() request: Request) {
const userRoles = request.user.roles; // Extract roles from request.user
await this.exampleService.doSomething(exampleDto, userRoles);
}
}
Approach B: Using a NestJS Guard or Interceptor for Authorization
For more complex authorization scenarios or to decouple authorization from validation, consider using NestJS Guards or Interceptors. These can check permissions based on request.user before the request even reaches your controller, thus protecting your endpoints.
// src/controllers/example.controller.ts
import { Controller, Post, UseGuards } from '@nestjs/common';
import { IsAuthorizedGuard } from './guards/is-authorized.guard';
@Controller('example')
export class ExampleController {
@Post()
@UseGuards(IsAuthorizedGuard)
@SetMetadata('allowedRoles', ['admin', 'moderator'])
async doSomething() {
// This will only be reached if the user is authorized
}
}
Choose the approach that best fits your application's requirements. For simple, data-related validations, explicitly passing user data might suffice. For more complex, endpoint-level authorization, using Guards is more idiomatic to NestJS.