From 01cd3f0464747973ec329e9fb1ea12743d3235cc Mon Sep 17 00:00:00 2001 From: gandharv Date: Fri, 23 Sep 2022 11:34:43 +0530 Subject: [PATCH] fix: add max file size validator for user avatar --- server/src/controllers/users.controller.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/server/src/controllers/users.controller.ts b/server/src/controllers/users.controller.ts index 5d4db2ec91..625fb4812f 100644 --- a/server/src/controllers/users.controller.ts +++ b/server/src/controllers/users.controller.ts @@ -1,4 +1,13 @@ -import { Body, Controller, Post, Patch, UseGuards, UseInterceptors, UploadedFile } from '@nestjs/common'; +import { + Body, + Controller, + Post, + Patch, + UseGuards, + UseInterceptors, + UploadedFile, + BadRequestException, +} from '@nestjs/common'; import { Express } from 'express'; import { FileInterceptor } from '@nestjs/platform-express'; import { JwtAuthGuard } from 'src/modules/auth/jwt-auth.guard'; @@ -7,6 +16,8 @@ import { UsersService } from 'src/services/users.service'; import { User } from 'src/decorators/user.decorator'; import { UpdateUserDto } from '@dto/user.dto'; +const MAX_AVATAR_FILE_SIZE = 1024 * 1024 * 2; // 2MB + @Controller('users') export class UsersController { constructor(private usersService: UsersService) {} @@ -27,6 +38,10 @@ export class UsersController { @UseGuards(JwtAuthGuard) @UseInterceptors(FileInterceptor('file')) async addAvatar(@User() user, @UploadedFile() file: Express.Multer.File) { + // TODO: use ParseFilePipe to validate file size from nestjs v9 + if (file.size > MAX_AVATAR_FILE_SIZE) { + throw new BadRequestException('File size is greater than 2MB'); + } return this.usersService.addAvatar(user.id, file.buffer, file.originalname); }