deleteUser needs to check the userId

This commit is contained in:
秦秋旭 2023-02-23 10:13:50 +08:00
parent 167d2e096a
commit 97094b36b5
3 changed files with 34 additions and 18 deletions

View File

@ -1,4 +1,9 @@
import { ConflictException, Inject, Injectable } from '@nestjs/common'
import {
ConflictException,
Inject,
Injectable,
NotFoundException,
} from '@nestjs/common'
import { securityConfig, SecurityConfig } from 'src/common/configs'
import { MailerService } from '@nestjs-modules/mailer'
import { JwtService } from '@nestjs/jwt'
@ -22,21 +27,21 @@ export class EmailService {
) {}
async sendEmailToken(email: string, scene: EmailScene) {
switch (scene) {
case EmailScene.register:
const user = await this.prismaService.user.findUnique({
where: { email },
})
switch (scene) {
case EmailScene.register:
case EmailScene.updateEmail:
if (user) {
throw new ConflictException(`邮箱${email}已注册`)
}
break
case EmailScene.updatePassword:
case EmailScene.updateEmail:
case EmailScene.deleteUser:
await this.prismaService.user.findUniqueOrThrow({
where: { email },
})
if (!user) {
throw new NotFoundException(`用户${email}不存在`)
}
break
}

View File

@ -43,8 +43,11 @@ export class UsersController {
@NeedAuth()
@ApiOperation({ summary: '删除用户' })
@Delete('me')
async deleteUser(@Body() userData: DeleteUserDto) {
return this.userService.deleteUser(userData)
async deleteUser(
@Body() userData: DeleteUserDto,
@User('userId') userId: string,
) {
return this.userService.deleteUser(userData, userId)
}
@ApiOperation({ summary: '修改密码' })

View File

@ -42,22 +42,30 @@ export class UsersService {
return this.tokenService.generateTokens({ userId: user.id })
}
async deleteUser(userData: DeleteUserDto) {
async deleteUser(userToDelete: DeleteUserDto, userId: string) {
await this.verifyEmail(
userData.email,
userData.token,
userData.verifyCode,
userToDelete.email,
userToDelete.token,
userToDelete.verifyCode,
EmailScene.deleteUser,
)
const user = await this.prismaService.user.findUnique({
where: { email: userData.email },
const user = await this.prismaService.user.findUniqueOrThrow({
where: { email: userToDelete.email },
})
const passwordValid = await bcrypt.compare(user.password, userData.password)
if (user.id !== userId) {
throw new ForbiddenException()
}
const passwordValid = await bcrypt.compare(
user.password,
userToDelete.password,
)
if (!passwordValid) {
throw new ForbiddenException('Invalid password')
}
return this.prismaService.user.delete({ where: { email: userData.email } })
return this.prismaService.user.delete({
where: { email: userToDelete.email },
})
}
async updatePassword(payload: UpdatePassword) {