fix(server): user update (#2143)

* fix(server): user update

* update dto

* generate api

* improve validation

* add e2e tests for updating user

---------

Co-authored-by: Michel Heusschen <59014050+michelheusschen@users.noreply.github.com>
This commit is contained in:
Alex
2023-04-01 11:43:45 -05:00
committed by GitHub
parent aaaf1a6cf8
commit d04f340b5b
10 changed files with 117 additions and 86 deletions

View File

@@ -1,28 +1,18 @@
import { IsEmail, IsNotEmpty, IsOptional } from 'class-validator';
import { IsBoolean, IsNotEmpty, IsOptional, IsUUID } from 'class-validator';
import { CreateUserDto } from './create-user.dto';
import { ApiProperty, PartialType } from '@nestjs/swagger';
export class UpdateUserDto {
export class UpdateUserDto extends PartialType(CreateUserDto) {
@IsNotEmpty()
@IsUUID('4')
@ApiProperty({ format: 'uuid' })
id!: string;
@IsEmail()
@IsOptional()
email?: string;
@IsOptional()
password?: string;
@IsOptional()
firstName?: string;
@IsOptional()
lastName?: string;
@IsOptional()
@IsBoolean()
isAdmin?: boolean;
@IsOptional()
@IsBoolean()
shouldChangePassword?: boolean;
@IsOptional()
profileImagePath?: string;
}

View File

@@ -21,12 +21,16 @@ export class UserCore {
constructor(private userRepository: IUserRepository, private cryptoRepository: ICryptoRepository) {}
async updateUser(authUser: AuthUserDto, id: string, dto: Partial<UserEntity>): Promise<UserEntity> {
if (!(authUser.isAdmin || authUser.id === id)) {
if (!authUser.isAdmin && authUser.id !== id) {
throw new ForbiddenException('You are not allowed to update this user');
}
if (dto.isAdmin && authUser.isAdmin && authUser.id !== id) {
throw new BadRequestException('Admin user exists');
if (!authUser.isAdmin) {
// Users can never update the isAdmin property.
delete dto.isAdmin;
} else if (dto.isAdmin && authUser.id !== id) {
// Admin cannot create another admin.
throw new BadRequestException('The server already has an admin');
}
if (dto.email) {

View File

@@ -90,6 +90,7 @@ export class UserService {
if (!user) {
throw new NotFoundException('User not found');
}
const updatedUser = await this.userCore.updateUser(authUser, dto.id, dto);
return mapUser(updatedUser);
}