Skip to content

Commit

Permalink
[backend] room password save with hash (#217)
Browse files Browse the repository at this point in the history
  • Loading branch information
kotto5 authored Jan 19, 2024
1 parent b8d7d0d commit cda8f91
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
4 changes: 3 additions & 1 deletion backend/src/room/guards/enter-room.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Injectable,
} from '@nestjs/common';
import { RoomService } from '../room.service';
import { compare } from 'bcrypt';

@Injectable()
export class EnterRoomGuard implements CanActivate {
Expand All @@ -32,7 +33,8 @@ export class EnterRoomGuard implements CanActivate {
if (!req.body.password) {
throw new BadRequestException('password is required');
}
if (room.password !== req.body.password) {
const isPasswordValid = await compare(req.body.password, room.password);
if (!isPasswordValid) {
throw new ForbiddenException('invalid password');
}
return true;
Expand Down
14 changes: 13 additions & 1 deletion backend/src/room/room.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { UpdateUserOnRoomDto } from './dto/update-UserOnRoom.dto';
import { UpdateRoomDto } from './dto/update-room.dto';
import { UserOnRoomEntity } from './entities/UserOnRoom.entity';
import { RoomEntity } from './entities/room.entity';
import { hash } from 'bcrypt';

@Injectable()
export class RoomService {
Expand All @@ -22,10 +23,18 @@ export class RoomService {
private eventEmitter: EventEmitter2,
) {}

hashPassword(password: string): Promise<string> {
const saltRounds = 10;
return hash(password, saltRounds);
}

// room CRUD

async create(createRoomDto: CreateRoomDto, user: User): Promise<RoomEntity> {
const { userIds, ...rest } = createRoomDto;
if (rest.password) {
rest.password = await this.hashPassword(rest.password);
}

// validate if there are only one userIds when accessLevel is DIRECT
if (createRoomDto.accessLevel === 'DIRECT' && userIds.length !== 1) {
Expand Down Expand Up @@ -144,10 +153,13 @@ export class RoomService {
});
}

updateRoom(
async updateRoom(
roomId: number,
updateRoomDto: UpdateRoomDto,
): Promise<RoomEntity> {
if (updateRoomDto.password) {
updateRoomDto.password = await this.hashPassword(updateRoomDto.password);
}
return this.prisma.room.update({
where: { id: roomId },
data: updateRoomDto,
Expand Down

0 comments on commit cda8f91

Please sign in to comment.