Skip to content

Commit

Permalink
fix: error handling을 해보자(테스트 필요)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomatozil committed Jan 5, 2024
1 parent 880340a commit a51600e
Show file tree
Hide file tree
Showing 27 changed files with 430 additions and 305 deletions.
21 changes: 9 additions & 12 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import {
BadRequestException,
ConflictException,
Inject,
Injectable,
Logger,
UnauthorizedException,
} from '@nestjs/common';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { createCipheriv, createDecipheriv } from 'crypto';
Expand All @@ -18,6 +11,10 @@ import { UsersRepository } from '../users/users.repository';
import { FtUserParamDto } from './dto/ft-user-param.dto';
import { SigninMfaRequestDto } from './dto/signin-mfa-request.dto';
import { UserFindReturnDto } from './dto/user-find-return.dto';
import {
BadRequestException, ConflictException,
UnauthorizedException,
} from '../common/exception/custom-exception';

@Injectable()
export class AuthService {
Expand Down Expand Up @@ -105,7 +102,7 @@ export class AuthService {
async validateNickname(nickname: string) {
const user = await this.usersRepository.findUserByNickname(nickname);
if (user) {
throw new ConflictException('이미 존재하는 닉네임입니다.');
throw ConflictException('이미 존재하는 닉네임입니다.');
}
}

Expand Down Expand Up @@ -157,10 +154,10 @@ export class AuthService {
});

if (!user) {
throw new BadRequestException('존재하지 않는 유저입니다.');
throw BadRequestException('존재하지 않는 유저입니다.');
}
if (!user.mfaSecret) {
throw new BadRequestException('MFA가 활성화되어 있지 않습니다.');
throw BadRequestException('MFA가 활성화되어 있지 않습니다.');
}

// mfaCode(token) 검증
Expand All @@ -172,7 +169,7 @@ export class AuthService {
});

if (!verified) {
throw new UnauthorizedException('MFA 인증에 실패했습니다.');
throw UnauthorizedException('MFA 인증에 실패했습니다.');
}

return user;
Expand Down
12 changes: 4 additions & 8 deletions src/auth/ft-auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import {
Inject,
Injectable,
Logger,
UnauthorizedException,
} from '@nestjs/common';
import { Inject, Injectable, Logger } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import axios from 'axios';
import ftConfig from '../config/ft.config';
import { FtUserParamDto } from './dto/ft-user-param.dto';
import { FtOauthResponseDto } from './dto/ft-oauth-response.dto';
import { UnauthorizedException } from '../common/exception/custom-exception';

@Injectable()
export class FtAuthService {
Expand Down Expand Up @@ -41,7 +37,7 @@ export class FtAuthService {
return response.data.access_token;
} catch (error) {
this.logger.error(error);
throw new UnauthorizedException('Invalid 42 code');
throw UnauthorizedException('Invalid 42 code');
}
}

Expand All @@ -62,7 +58,7 @@ export class FtAuthService {
return userData;
} catch (error) {
this.logger.error(error);
throw new UnauthorizedException('Invalid 42 access token');
throw UnauthorizedException('Invalid 42 access token');
}
}
}
2 changes: 1 addition & 1 deletion src/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
// const user = await this.userRepository.findOneBy({ id });

// if (!user) {
// throw new UnauthorizedException();
// throw UnauthorizedException();
// }

// return user;
Expand Down
46 changes: 46 additions & 0 deletions src/auth/guards/ws-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
} from '@nestjs/common';
import { WSUnauthorizedException } from '../../common/exception/custom-exception';
import { SocketWithAuth } from '../../socket-adapter/socket-io.adapter';
import { JwtService } from '@nestjs/jwt';
import JwtConfig from '../../config/jwt.config';
import { ConfigType } from '@nestjs/config';
import { UsersRepository } from '../../users/users.repository';

@Injectable()
export class WsAuthGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
@Inject(JwtConfig.KEY)
private readonly jwtConfigure: ConfigType<typeof JwtConfig>,
private readonly usersRepository: UsersRepository,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const socket: SocketWithAuth = context.switchToWs().getClient();

const cookie = socket.handshake.headers.cookie;
if (!cookie) throw WSUnauthorizedException('no cookie');

const accessToken = cookie.split(';')[0].split('=')[1];
if (!accessToken) throw WSUnauthorizedException('no access token');
// accessToken 유효성 검사

const payload = await this.jwtService.verifyAsync(accessToken, {
secret: this.jwtConfigure.secret,
});
if (!payload) throw WSUnauthorizedException('no payload');

const user = await this.usersRepository.findOne({
where: { id: payload.id },
});
if (!user) throw WSUnauthorizedException('no user');

socket.user = user;
return true;
}
}
5 changes: 3 additions & 2 deletions src/auth/jwt-access.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Inject, Injectable} from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
Expand All @@ -7,6 +7,7 @@ import jwtConfig from 'src/config/jwt.config';
import { User } from 'src/users/entities/user.entity';
import { UsersRepository } from 'src/users/users.repository';
import { JwtAccessPayloadDto } from './dto/jwt-access-payload.dto';
import { UnauthorizedException } from '../common/exception/custom-exception';

@Injectable()
export class JwtAccessStrategy extends PassportStrategy(Strategy, 'access') {
Expand All @@ -31,7 +32,7 @@ export class JwtAccessStrategy extends PassportStrategy(Strategy, 'access') {
});

if (!user) {
throw new UnauthorizedException();
throw UnauthorizedException();
}

return user;
Expand Down
9 changes: 5 additions & 4 deletions src/auth/jwt-refresh.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Inject, Injectable} from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
Expand All @@ -9,6 +9,7 @@ import jwtConfig from 'src/config/jwt.config';
import { User } from 'src/users/entities/user.entity';
import { UsersRepository } from 'src/users/users.repository';
import { JwtRefreshPayloadDto } from './dto/jwt-refresh-payload.dto';
import { UnauthorizedException } from '../common/exception/custom-exception';

@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'refresh') {
Expand All @@ -35,14 +36,14 @@ export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'refresh') {

if (!user) {
console.log(`Invalid user`);
throw new UnauthorizedException();
throw UnauthorizedException();
}

console.log(`user.refreshToken: ${user.refreshToken}`);
console.log(`refreshToken: ${refreshToken}`);

if (!user.refreshToken || !refreshToken) {
throw new UnauthorizedException();
throw UnauthorizedException();
}

const isRefreshTokenValid = await bcrypt.compare(
Expand All @@ -52,7 +53,7 @@ export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'refresh') {

if (!isRefreshTokenValid) {
console.log(`token match failed`);
throw new UnauthorizedException();
throw UnauthorizedException();
}

console.log('jwt-refresh.strategy.ts: validate: user: ', user);
Expand Down
5 changes: 3 additions & 2 deletions src/channels/channel-users.repository.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { BadRequestException, Logger } from '@nestjs/common';
import { Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import {
BadRequestException,
DBQueryErrorException,
DBUpdateFailureException,
} from '../common/exception/custom-exception';
Expand All @@ -28,7 +29,7 @@ export class ChannelUsersRepository extends Repository<ChannelUser> {
},
});
if (isAlreadyJoined)
throw new BadRequestException('이미 채널에 참여한 유저입니다');
throw BadRequestException('이미 채널에 참여한 유저입니다');

const res = await this.save(newChannelUser);

Expand Down
53 changes: 23 additions & 30 deletions src/channels/channels.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Expand All @@ -17,6 +16,7 @@ import { GetUser } from 'src/auth/get-user.decorator';
import { ChannelEventType, ChannelType } from 'src/common/enum';
import { User } from 'src/users/entities/user.entity';
import { PositiveIntPipe } from '../common/pipes/positiveInt.pipe';
import { BadRequestException } from '../common/exception/custom-exception';
import { ChannelsGateway } from './channels.gateway';
import { ChannelsService } from './channels.service';
import { ChannelInvitationParamDto } from './dto/channel-Invitation.dto';
Expand Down Expand Up @@ -58,23 +58,23 @@ export class ChannelsController {

// DM 채널인 경우 userId가 필수
if (channelInfo.channelType === ChannelType.DM && !channelInfo.userId) {
throw new BadRequestException(`DM을 위한 userId를 입력해주세요.`);
throw BadRequestException(`DM을 위한 userId를 입력해주세요.`);
}

// DM 채널이 아닌데 channel name이 NULL인 경우 예외 처리
if (
channelInfo.channelType !== ChannelType.DM &&
channelInfo.name === null
) {
throw new BadRequestException(`채널 이름을 입력해주세요.`);
throw BadRequestException(`채널 이름을 입력해주세요.`);
}

const createChannelResponseDto =
await this.channelsService.createChannel(user.id, channelInfo);

if (user.channelSocketId) {
// 채널 룸에 join
this.channelsGateway.joinChannelRoom(
await this.channelsGateway.joinChannelRoom(
createChannelResponseDto.channelId.toString(),
user.channelSocketId,
);
Expand All @@ -94,7 +94,7 @@ export class ChannelsController {
@Param('channelId', ParseIntPipe, PositiveIntPipe) channelId: number,
) {
if (user.channelSocketId) {
this.channelsGateway.joinChannelRoom(
await this.channelsGateway.joinChannelRoom(
channelId.toString(),
user.channelSocketId,
);
Expand Down Expand Up @@ -151,7 +151,7 @@ export class ChannelsController {

if (user.channelSocketId) {
// 채널 룸에 join
this.channelsGateway.joinChannelRoom(
await this.channelsGateway.joinChannelRoom(
channelId.toString(),
user.channelSocketId,
);
Expand Down Expand Up @@ -182,7 +182,7 @@ export class ChannelsController {

if (user.channelSocketId) {
// 채널 룸에서 leave
this.channelsGateway.leaveChannelRoom(
await this.channelsGateway.leaveChannelRoom(
channelId.toString(),
user.channelSocketId,
);
Expand Down Expand Up @@ -392,30 +392,23 @@ export class ChannelsController {
@Body('invitationId', ParseIntPipe, PositiveIntPipe)
invitationId: number,
) {
try {
const createChannelUserParamDto: ChannelInvitationParamDto = {
invitedUserId: user.id,
invitationId: invitationId,
};
const channelId =
await this.channelsService.findChannelIdByInvitationId(
invitationId,
);
const channelsReturnDto =
await this.channelsService.acceptInvitation(
createChannelUserParamDto,
);
this.channelsGateway.channelNoticeMessage(channelId, {
channelId,
nickname: user.nickname,
eventType: ChannelEventType.JOIN,
});
return channelsReturnDto;
} catch (error) {
throw new BadRequestException(
"I'm just a little bit caught in the middle. Life is a maze and love is a riddle.",
const createChannelUserParamDto: ChannelInvitationParamDto = {
invitedUserId: user.id,
invitationId: invitationId,
};
const channelId =
await this.channelsService.findChannelIdByInvitationId(
invitationId,
);
}
const channelsReturnDto = await this.channelsService.acceptInvitation(
createChannelUserParamDto,
);
this.channelsGateway.channelNoticeMessage(channelId, {
channelId,
nickname: user.nickname,
eventType: ChannelEventType.JOIN,
});
return channelsReturnDto;
}

@Delete('/refuse/:channelInvitationId')
Expand Down
Loading

0 comments on commit a51600e

Please sign in to comment.