diff --git a/apps/api/src/account/account.controller.ts b/apps/api/src/account/account.controller.ts index 6a7b006..7faae31 100644 --- a/apps/api/src/account/account.controller.ts +++ b/apps/api/src/account/account.controller.ts @@ -10,6 +10,7 @@ import { Get, HttpException, HttpStatus, + Patch, Post, Query, Req, @@ -68,6 +69,21 @@ export class AccountController { return this.accountService.delete(username); } + @Patch('/update') + @ApiResponse({ + status: HttpStatus.OK, + type: Account, + }) + async update(@Body() createAccountDto: CreateAccountDto, @Res() reply: FastifyReply) { + try { + const updatedAccount = await this.accountService.update(createAccountDto); + + return reply.status(HttpStatus.OK).send(updatedAccount); + } catch (error) { + throw new HttpException(error, HttpStatus.BAD_REQUEST); + } + } + @Post('/login') async login(@Body() credentials: Credentials, @Res() reply: FastifyReply) { try { diff --git a/apps/api/src/account/account.service.ts b/apps/api/src/account/account.service.ts index d1b123b..66d14d5 100644 --- a/apps/api/src/account/account.service.ts +++ b/apps/api/src/account/account.service.ts @@ -1,5 +1,5 @@ import type { CreateAccountDto } from './dto/create-account.dto'; -import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { InjectModel } from '@nestjs/mongoose'; import * as bcrypt from 'bcrypt'; @@ -18,6 +18,11 @@ export class AccountService { ) {} public async create(createAccountDto: CreateAccountDto): Promise { + Object.keys(createAccountDto).forEach((field) => { + if (['_id', '__v'].includes(field)) + throw new BadRequestException(`Prop ${field} is not allowed`); + }); + const password = createAccountDto.password || generatePassword(); const createdAccount = new this.accountModel({ ...createAccountDto, password }); @@ -35,6 +40,15 @@ export class AccountService { return this.accountModel.findOneAndDelete({ username }).exec(); } + public async update({ username, ...props }: CreateAccountDto): Promise { + Object.keys(props).forEach((field) => { + if (['_id', '__v', 'password'].includes(field)) + throw new BadRequestException(`Prop ${field} is not allowed`); + }); + + return this.accountModel.findOneAndUpdate({ username }, props).exec(); + } + public async login({ login, password }: Credentials) { try { const account = await this.accountModel.findOne({ username: login });