diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index 89ceb17..a791920 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -1,6 +1,7 @@ import { Body, Controller, + Delete, Get, HttpCode, HttpStatus, @@ -57,6 +58,7 @@ import { UpdateUserCommand, VerifyEmailCommand, } from './use-cases' +import { DeleteCurrentAccountCommand } from './use-cases/delete-current-user-account-use-case' @ApiTags('Auth') @Controller('auth') @@ -94,6 +96,23 @@ export class AuthController { return await this.commandBus.execute(new UpdateUserCommand(userId, body, files?.avatar?.[0])) } + @ApiOperation({ + description: + 'Delete current user account. All the user data will be deleted forever. This action can not be undone', + summary: 'Delete current user account', + }) + @ApiUnauthorizedResponse({ description: 'Not logged in' }) + @ApiBadRequestResponse({ description: 'User not found' }) + @ApiBearerAuth() + @UseGuards(JwtAuthGuard) + @HttpCode(HttpStatus.NO_CONTENT) + @Delete('me') + async deleteUserAccount(@Request() req): Promise { + const userId = req.user.id + + return await this.commandBus.execute(new DeleteCurrentAccountCommand(userId)) + } + @ApiOperation({ description: 'Sign in using email and password. Must have an account to do so.', summary: 'Sign in using email and password. Must have an account to do so.', diff --git a/src/modules/auth/auth.module.ts b/src/modules/auth/auth.module.ts index ab3cea2..33b536d 100644 --- a/src/modules/auth/auth.module.ts +++ b/src/modules/auth/auth.module.ts @@ -19,10 +19,12 @@ import { VerifyEmailHandler, UpdateUserHandler, } from './use-cases' +import { DeleteCurrentUserAccountHandler } from './use-cases/delete-current-user-account-use-case' const commandHandlers = [ CreateUserHandler, GetCurrentUserDataHandler, + DeleteCurrentUserAccountHandler, LogoutHandler, RefreshTokenHandler, ResendVerificationEmailHandler, diff --git a/src/modules/auth/use-cases/delete-current-user-account-use-case.ts b/src/modules/auth/use-cases/delete-current-user-account-use-case.ts new file mode 100644 index 0000000..1ca8725 --- /dev/null +++ b/src/modules/auth/use-cases/delete-current-user-account-use-case.ts @@ -0,0 +1,18 @@ +import { CommandHandler, ICommandHandler } from '@nestjs/cqrs' + +import { UsersRepository } from '../../users/infrastructure/users.repository' + +export class DeleteCurrentAccountCommand { + constructor(public readonly userId: string) {} +} + +@CommandHandler(DeleteCurrentAccountCommand) +export class DeleteCurrentUserAccountHandler + implements ICommandHandler +{ + constructor(private readonly usersRepository: UsersRepository) {} + + async execute(command: DeleteCurrentAccountCommand): Promise { + return await this.usersRepository.deleteUserById(command.userId) + } +}