Skip to content

Commit

Permalink
fix(user): hiding isAdmin and password property (#167)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kif-Fando authored and derevnjuk committed Feb 9, 2022
1 parent f9fdc50 commit a253b0c
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 42 deletions.
23 changes: 11 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@nestjs/swagger": "^4.7.12",
"axios": "^0.21.2",
"bcrypt": "^5.0.0",
"class-transformer": "^0.5.1",
"dot": "^1.1.3",
"dotenv": "^8.2.0",
"fastify-cookie": "^5.1.0",
Expand Down
2 changes: 1 addition & 1 deletion public/src/interfaces/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@ export interface UserData {
email: string;
lastName: string;
firstName: string;
isAdmin: boolean;
isAdmin?: boolean;
}
3 changes: 1 addition & 2 deletions public/src/pages/main/Userprofile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import AuthLayout from '../auth/AuthLayout';
const defaultUserData: UserData = {
email: '',
firstName: '',
lastName: '',
isAdmin: false
lastName: ''
};

export const Userprofile = () => {
Expand Down
19 changes: 17 additions & 2 deletions src/users/api/UserDto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { Exclude } from 'class-transformer';

export class UserDto {
@ApiProperty()
Expand All @@ -10,11 +11,25 @@ export class UserDto {
@ApiProperty()
lastName: string;

@Exclude()
@ApiHideProperty()
isAdmin: boolean;
isAdmin?: boolean;

@Exclude()
@ApiHideProperty()
password: string;
password?: string;

@Exclude()
id: number;

@Exclude()
photo: Buffer;

@Exclude()
updatedAt: Date;

@Exclude()
createdAt: Date;

constructor(
params: {
Expand Down
47 changes: 25 additions & 22 deletions src/users/users.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
Body,
ClassSerializerInterceptor,
Controller,
ForbiddenException,
Get,
Expand Down Expand Up @@ -56,6 +57,7 @@ import { AdminGuard } from './users.guard';
import { PermissionDto } from './api/PermissionDto';

@Controller('/api/users')
@UseInterceptors(ClassSerializerInterceptor)
@ApiTags('User controller')
export class UsersController {
private logger = new Logger(UsersController.name);
Expand All @@ -81,17 +83,24 @@ export class UsersController {
})
@ApiOkResponse({
type: UserDto,
description: 'Returns user object or empty object when user is not found',
description: 'Returns user object if it exists',
})
@ApiNotFoundResponse({
description: 'User not founded',
schema: {
type: 'object',
properties: {
statusCode: { type: 'number' },
message: { type: 'string' },
},
},
})
async getUser(@Param('email') email: string): Promise<UserDto> {
try {
this.logger.debug(`Find a user by email: ${email}`);
return new UserDto(await this.usersService.findByEmail(email));
} catch (err) {
throw new InternalServerErrorException({
error: err.message,
location: __filename,
});
throw new HttpException(err.message, err.status);
}
}

Expand Down Expand Up @@ -207,13 +216,13 @@ export class UsersController {
this.logger.debug(`Create a basic user: ${user}`);

const userExists = await this.usersService.findByEmail(user.email);

if (userExists) {
throw new HttpException('User already exists', 409);
}

return new UserDto(await this.usersService.createUser(user));
} catch (err) {
if (err.status === 404) {
return new UserDto(await this.usersService.createUser(user));
}
throw new HttpException(
err.message ?? 'Something went wrong',
err.status ?? 500,
Expand Down Expand Up @@ -281,21 +290,16 @@ export class UsersController {
@Body() newData: UserDto,
@Param('email') email: string,
@Req() req: FastifyRequest,
) {
): Promise<UserDto> {
try {
let user = await this.usersService.findByEmail(email);
const user = await this.usersService.findByEmail(email);
if (!user) {
throw new NotFoundException('Could not find user');
}
if (this.originEmail(req) !== email) {
throw new ForbiddenException();
}
user = await this.usersService.updateUserInfo(user, newData);
return {
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
};
return new UserDto(await this.usersService.updateUserInfo(user, newData));
} catch (err) {
throw new HttpException(
err.message || 'Internal server error',
Expand Down Expand Up @@ -325,7 +329,10 @@ export class UsersController {
@ApiOkResponse({
description: 'Returns user info',
})
async getUserInfo(@Param('email') email: string, @Req() req: FastifyRequest) {
async getUserInfo(
@Param('email') email: string,
@Req() req: FastifyRequest,
): Promise<UserDto> {
try {
const user = await this.usersService.findByEmail(email);

Expand All @@ -335,11 +342,7 @@ export class UsersController {
if (this.originEmail(req) !== email) {
throw new ForbiddenException();
}
return {
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
};
return new UserDto(user);
} catch (err) {
throw new HttpException(
err.message || 'Internal server error',
Expand Down
11 changes: 8 additions & 3 deletions src/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EntityRepository, NotFoundError, wrap } from '@mikro-orm/core';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, Logger } from '@nestjs/common';
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { PermissionDto } from './api/PermissionDto';
import { hashPassword } from '../auth/credentials.utils';
import { User } from '../model/user.entity';
Expand Down Expand Up @@ -53,7 +53,7 @@ export class UsersService {
return user;
}

async updateUserInfo(oldUser: User, newData: UserDto): Promise<User> {
async updateUserInfo(oldUser: User, newData: UserDto): Promise<UserDto> {
this.log.debug(`updateUserInfo ${oldUser.email}`);
const newUser = oldUser;
wrap(newUser).assign({
Expand All @@ -65,7 +65,12 @@ export class UsersService {

async findByEmail(email: string): Promise<User> {
this.log.debug(`Called findByEmail ${email}`);
return this.usersRepository.findOne({ email });
const user = await this.usersRepository.findOne({ email });
if (user) {
return user;
} else {
throw new NotFoundException('User not found');
}
}

async getPermissions(email: string): Promise<PermissionDto> {
Expand Down

0 comments on commit a253b0c

Please sign in to comment.