📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Fixed user CRUD functionality
Blaumaus0be9bb23e4f3
diff --git a/src/user/dto/update-user.dto.ts b/src/user/dto/update-user.dto.tsnew file mode 100644index 000000000..53f095c70--- /dev/null+++ b/src/user/dto/update-user.dto.ts@@ -0,0 +1,11 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsEmail, IsNotEmpty } from 'class-validator'++export class UpdateUserProfileDTO {+ @ApiProperty({ example: '[email protected]', required: true })+ @IsEmail()+ email: string++ @ApiProperty({ example: 'your_password123' })+ password: string+}diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex 76abb9f4f..ec4f209d3 100644--- a/src/user/user.controller.ts+++ b/src/user/user.controller.ts@@ -5,21 +5,19 @@ import { Request } from 'express'import { ApiTags, ApiQuery } from '@nestjs/swagger'import { UserService } from './user.service'-import { UserType } from './entities/user.entity'+import { User, UserType, MAX_EMAIL_REQUESTS } from './entities/user.entity'import { Roles } from '../common/decorators/roles.decorator'-// import { Pagination } from '../common/pagination/pagination'-// import { User, UserType, MAX_EMAIL_REQUESTS } from './entities/user.entity'-// import { CustomerDto } from './dto/customer.dto'+import { Pagination } from '../common/pagination/pagination'import { RolesGuard } from 'src/common/guards/roles.guard'-// import { UsersService } from '../users/users.service'-// import { UpdateCustomerDto } from './dto/update-customer'+import { UpdateUserProfileDTO } from './dto/update-user.dto'import { CurrentUserId } from 'src/common/decorators/current-user-id.decorator'import { ActionTokensService } from '../action-tokens/action-tokens.service'import { MailerService } from '../mailer/mailer.service'-// import { ActionTokenType } from '../action-tokens/action-token.entity'+import { ActionTokenType } from '../action-tokens/action-token.entity'import { AuthService } from '../auth/auth.service'-// import { LetterTemplate } from 'src/mailer/lettter'+import { LetterTemplate } from 'src/mailer/lettter'import { AppLoggerService } from 'src/logger/logger.service'+import { UserProfileDTO } from './dto/user.dto'@ApiTags('User')@Controller('user')@@ -33,54 +31,47 @@ export class UserController {private readonly logger: AppLoggerService) {}- // @Get('/')- // @ApiQuery({ name: 'take', required: false })- // @ApiQuery({ name: 'skip', required: false })- // @Roles(UserType.ADMIN)- // async get(@Query('take') take: number | undefined, @Query('skip') skip: number | undefined):- // Promise<Pagination<Customer> | Customer[]>- // {- // this.logger.log({take, skip}, 'GET /customers')- // return await this.customersService.paginate({take, skip})- // }-- // @Get('/search')- // @ApiQuery({ name: 'query', required: false })- // @Roles(UserType.ADMIN)- // async searchCustomers(- // @Query('query') query: string | undefined,- // ) :Promise<Customer[]>- // {- // this.logger.log({query}, 'GET /customers/search')- // return await this.customersService.search(query)- // }-- // @Post('/')- // @Roles(UserType.ADMIN)- // async create(@Body() customerDto: CustomerDto): Promise<Customer> {- // this.logger.log({customerDto}, 'POST /customers')- // this.usersService.validatePassword(customerDto.password)- // customerDto.password = this.authService.hashPassword(customerDto.password)- // try {- // const customer = await this.customersService.create({...customerDto, isActive: true})- // return customer- // } catch(e){- // if(e.code === 'ER_DUP_ENTRY'){- // if(e.sqlMessage.includes(customerDto.email)) {- // throw new BadRequestException('User with this email already exists')- // } else if(e.sqlMessage.includes(customerDto.phone)) {- // throw new BadRequestException('User with this phone already exists')- // }- // }- // }- // }+ @Get('/')+ @ApiQuery({ name: 'take', required: false })+ @ApiQuery({ name: 'skip', required: false })+ @Roles(UserType.ADMIN)+ async get(@Query('take') take: number | undefined, @Query('skip') skip: number | undefined): Promise<Pagination<User> | User[]> {+ this.logger.log({ take, skip }, 'GET /user')+ return await this.userService.paginate({ take, skip })+ }++ @Get('/search')+ @ApiQuery({ name: 'query', required: false })+ @Roles(UserType.ADMIN)+ async searchUsers(@Query('query') query: string | undefined): Promise<User[]> {+ this.logger.log({ query }, 'GET /user/search')+ return await this.userService.search(query)+ }++ @Post('/')+ @Roles(UserType.ADMIN)+ async create(@Body() userDTO: UserProfileDTO): Promise<User> {+ this.logger.log({ userDTO }, 'POST /user')+ this.userService.validatePassword(userDTO.password)+ userDTO.password = this.authService.hashPassword(userDTO.password)++ try {+ const user = await this.userService.create({ ...userDTO, isActive: true })+ return user+ } catch(e) {+ if (e.code === 'ER_DUP_ENTRY'){+ if(e.sqlMessage.includes(userDTO.email)) {+ throw new BadRequestException('User with this email already exists')+ }+ }+ }+ }@Delete('/:id')@HttpCode(204)@Roles(UserType.ADMIN)- async delete(@Param('id') id: string, @CurrentUserId() uid: string):- Promise<any> {- this.logger.log({ id, uid }, 'DELETE /customers/:id')+ async delete(@Param('id') id: string, @CurrentUserId() uid: string): Promise<any> {+ this.logger.log({ id, uid }, 'DELETE /user/:id')const userToDelete = await this.userService.findOneWhere({ id })if (!userToDelete) {@@ -95,93 +86,86 @@ export class UserController {@HttpCode(204)@Roles(UserType.FREE)async deleteSelf(@CurrentUserId() uid: string): Promise<any> {- this.logger.log({ uid }, 'DELETE /customers')+ this.logger.log({ uid }, 'DELETE /user')await this.userService.delete(uid)return}- // @Put('/:id')- // @Roles(UserType.ADMIN)- // async update(@Body() customerDto: UpdateCustomerDto, @Param('id') id: string): Promise<Customer> {- // this.logger.log({customerDto, id}, 'DELETE /customers/:id')- // if(customerDto.password) {- // this.usersService.validatePassword(customerDto.password)- // customerDto.password = this.authService.hashPassword(customerDto.password)- // }- // const customer = await this.customersService.findOneWhere({id})- // if(!customer){- // throw new BadRequestException('User does not exist')- // }- // try {- // await this.customersService.update(id, {...customer, ...customerDto})- // return this.customersService.findOneWhere({id})- // } catch (e) {- // if(e.code === 'ER_DUP_ENTRY'){- // if(e.sqlMessage.includes(customerDto.email)) {- // throw new BadRequestException('User with this email already exists')- // } else if(e.sqlMessage.includes(customerDto.phone)) {- // throw new BadRequestException('User with this phone already exists')- // }- // }- // throw new BadRequestException(e.message)- // }- // }-- // @Post('/confirm_email')- // @Roles(UserType.FREE)- // async sendEmailConfirmation(@CurrentUserId() id: string, @Req() request: Request): Promise<boolean> {- // this.logger.log({ id }, 'POST /confirm_email')+ @Post('/confirm_email')+ @Roles(UserType.FREE)+ async sendEmailConfirmation(@CurrentUserId() id: string, @Req() request: Request): Promise<boolean> {+ this.logger.log({ id }, 'POST /confirm_email')++ const user = await this.userService.findOneWhere({ id })++ if (!user || !user.email || user.isActive || user.emailRequests >= MAX_EMAIL_REQUESTS) return false++ const token = await this.actionTokensService.createForUser(user, ActionTokenType.EMAIL_VERIFICATION, user.email)+ const url = `${request.headers.origin}/verify/${token.id}`- // const customer = await this.customersService.findOneWhere({ id })- // console.log(customer)- // if (!customer || !customer.email || customer.isActive || customer.emailRequests >= MAX_EMAIL_REQUESTS) return false+ await this.userService.update(id, { emailRequests: 1 + user.emailRequests })+ await this.mailerService.sendEmail(user.email, LetterTemplate.SignUp, { url })+ return true+ }- // const token = await this.actionTokensService.createForCustomer(customer, ActionTokenType.EMAIL_VERIFICATION, customer.email)- // const url = `${request.headers.origin}/verify/${token.id}`+ @Put('/:id')+ @Roles(UserType.ADMIN)+ async update(@Body() userDTO: UpdateUserProfileDTO, @Param('id') id: string): Promise<User> {+ this.logger.log({ userDTO, id }, 'DELETE /user/:id')- // await this.customersService.update(id, { emailRequests: 1 + customer.emailRequests })- // await this.mailerService.sendEmail(customer.email, LetterTemplate.SignUp, customer.locale, { url })- // return true- // }-- // @Put('/')- // @Roles(UserType.FREE)- // async updateCurrentCustomer(- // @Body() customerDto: UpdateCustomerDto,- // @CurrentUserId() customerId: string,- // @Req() request: Request):- // Promise<Customer> {- // this.logger.log({customerDto, customerId}, 'PUT /customers')- // const customer = await this.customersService.findOneWhere({id: customerId})- // if(customerDto.password && customerDto.password.length > 0) {- // this.usersService.validatePassword(customerDto.password)- // customerDto.password = this.authService.hashPassword(customerDto.password)- // await this.mailerService.sendEmail(customerDto.email, LetterTemplate.PasswordChanged, customerDto.locale )- // }- // try {- // if(customerDto.email && customer.email !== customerDto.email) {- // const userWithByEmail = this.customersService.findOneWhere({email: customerDto.email})- // if(userWithByEmail){- // customerDto.email = customer.email- // } else {- // throw new BadRequestException('User with this email already exists')- // }- // const token = await this.actionTokensService.createForCustomer(- // customer, ActionTokenType.EMAIL_CHANGE, customerDto.email)- // const url = `${request.headers.origin}/change-email/${token.id}`- // await this.mailerService.sendEmail(- // customer.email, LetterTemplate.MailAddressChangeConfirmation, customerDto.locale, { url })- // }- // await this.customersService.update(customerId, {...customerDto})-- // return this.customersService.findOneWhere({id: customerId})- // } catch (e) {- // if(e.code === 'ER_DUP_ENTRY'){- // if(e.sqlMessage.includes(customerDto.phone)) {- // throw new BadRequestException('User with this phone already exists')- // }- // }- // throw new BadRequestException(e.message)- // }- // }+ if (userDTO.password) {+ this.userService.validatePassword(userDTO.password)+ userDTO.password = this.authService.hashPassword(userDTO.password)+ }++ const user = await this.userService.findOneWhere({ id })++ if (!user) {+ throw new BadRequestException('User does not exist')+ }++ try {+ await this.userService.update(id, {...user, ...userDTO})+ return this.userService.findOneWhere({ id })+ } catch (e) {+ if(e.code === 'ER_DUP_ENTRY'){+ if(e.sqlMessage.includes(userDTO.email)) {+ throw new BadRequestException('User with this email already exists')+ }+ }+ throw new BadRequestException(e.message)+ }+ }++ @Put('/')+ @Roles(UserType.FREE)+ async updateCurrentUser(@Body() userDTO: UpdateUserProfileDTO, @CurrentUserId() id: string, @Req() request: Request): Promise<User> {+ this.logger.log({ userDTO, id }, 'PUT /user')+ const user = await this.userService.findOneWhere({ id })++ if (userDTO.password?.length > 0) {+ this.userService.validatePassword(userDTO.password)+ userDTO.password = this.authService.hashPassword(userDTO.password)+ await this.mailerService.sendEmail(userDTO.email, LetterTemplate.PasswordChanged)+ }++ try {+ if (userDTO.email && user.email !== userDTO.email) {+ const userWithByEmail = await this.userService.findOneWhere({ email: userDTO.email })++ if (userWithByEmail) {+ throw new BadRequestException('User with this email already exists')+ }++ const token = await this.actionTokensService.createForUser(user, ActionTokenType.EMAIL_CHANGE, userDTO.email)+ const url = `${request.headers.origin}/change-email/${token.id}`+ await this.mailerService.sendEmail(user.email, LetterTemplate.MailAddressChangeConfirmation, { url })+ }+ await this.userService.update(id, { ...userDTO })++ return this.userService.findOneWhere({ id })+ } catch (e) {+ throw new BadRequestException(e.message)+ }+ }}