Skip to content

Commit

Permalink
Merge pull request #161 from LocalMingle/heeyong
Browse files Browse the repository at this point in the history
[수정] auth 리팩토링
  • Loading branch information
HeeDragoN1123 authored Nov 7, 2023
2 parents d8091ea + 07fd7be commit 5de9d58
Show file tree
Hide file tree
Showing 13 changed files with 400 additions and 207 deletions.
1 change: 1 addition & 0 deletions .github/workflows/nest_lm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ jobs:
echo "NAVER_CLIENT_SECRET=${{ secrets.NAVER_CLIENT_SECRET }}" >> .env
echo "NAVER_CALLBACK_URL=${{ secrets.NAVER_CALLBACK_URL }}" >> .env
echo "MONGO_URL=${{ secrets.MONGO_URL }}" >> .env
echo "CLIENT_URL=${{ secrets.CLIENT_URL }}" >> .env
working-directory: ./

# 압축 파일 생성 - 이 부분과 s3 업로드 부분은 같은 job 에 있어야 됨 없으면 업로드 할 .zip 을 못 찾음
Expand Down
2 changes: 1 addition & 1 deletion src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ interface IOAuthUser {
@ApiTags('Auth')
@ApiOkResponse({ type: AuthEntity })
export class AuthController {
constructor(private readonly authService: AuthService) { }
constructor(private readonly authService: AuthService) {}
//-----------------------로그인-----------------------------//
@ApiOperation({ summary: '로그인' })
@ApiResponse({ status: 200, description: '로그인에 성공하셨습니다.' })
Expand Down
4 changes: 2 additions & 2 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { PrismaService } from './../prisma/prisma.service';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { UsersService } from 'src/users/users.service';
import { IAuthServiceLogin } from './interface/auth-service.interface';

@Injectable()
export class AuthService {
Expand All @@ -16,7 +17,7 @@ export class AuthService {
private jwtService: JwtService
) {}

async login({ email, password, res }): Promise<{
async login({ email, password, res }: IAuthServiceLogin): Promise<{
// 리팩토링 시 res 빼도 작동하는지 테스트
accessToken: string;
refreshToken: string;
Expand Down Expand Up @@ -86,7 +87,6 @@ export class AuthService {

const newAccessToken = await this.getAccessToken({
user: { userId }, // 사용자 ID를 전달
// res: null,
});
return newAccessToken;
}
Expand Down
5 changes: 3 additions & 2 deletions src/auth/interface/auth-service.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ export interface IUsersServiceFindByEmail {
export interface IAuthServiceLogin {
email: string;
password: string;
res: any;
}

export interface IAuthServiceGetAccessToken {
user: User;
res: any;
// res: any;
}

export interface IAuthServiceGetRefereshToken {
user: User;
res: any;
// res: any;
}
187 changes: 105 additions & 82 deletions src/chats/chats.gateway.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import { Chatting } from './models/chattings.model';
import { InjectModel } from '@nestjs/mongoose';
import { Logger } from '@nestjs/common';
import { Socket, Server } from 'socket.io';
import {
ConnectedSocket,
MessageBody,
Expand All @@ -12,103 +9,129 @@ import {
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { ChatsService } from './chats.service';
import { IMessage, IRoomRequest } from './interfaces/chats.interface';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
// import { IMessage } from './room.chats.interface';
// import { LocalDateTime } from '@js-joda/core';
import { LocalDateTime } from '@js-joda/core';
import { Chatting } from './models/chattings.model';

@WebSocketGateway({
namespace: 'chattings',
cors: {
origin: [
'http://localhost:5173',
'https://d2r603zvpf912o.cloudfront.net',
'https://totobon.store',
'https://local-mingle-fe.vercel.app',
'https://localmingle.store',
],
methods: ['GET', 'POST'],
credentials: true,
},
//WebSocket 서버가 모든 원격 호스트로부터의 연결을 허용
cors: true,
allowEIO3: true,
})
export class ChatsGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer() server: Server;
private logger = new Logger('chat');
constructor(
@InjectModel(Chatting.name) private readonly chattingModel: Model<Chatting>,
@InjectModel(Socket.name)
private readonly socketModel: Model<Socket>
) {
this.logger.log('constructor');
}
// WebSocketGateway가 초기화될 때 실행되는 메소드
// WebSocketGateway가 초기화되면 로그를 출력합니다.
afterInit() {
this.logger.log('init');
}
// 클라이언트와의 연결이 해제될 때 실행되는 메소드
// 클라이언트 소켓 연결이 끊기면 roomChatsService의 handleDisconnect 메소드 호출
async handleDisconnect(@ConnectedSocket() socket: Socket) {
const user = await this.socketModel.findOne({ id: socket.id });
if (user) {
socket.broadcast.emit('disconnect_user', user.data);
await user.deleteOne();
}
this.logger.log(`disconnected : ${socket.id} ${socket.nsp.name}`);
// this.logger.log(`disconnected : ${socket.id} ${socket.nsp.name}`);
// await this.roomChatsService.handleDisconnect(socket);
// this.logger.log(`disconnected : ${socket.id} ${socket.nsp.name}`);
}
// 클라이언트와의 연결이 수립될 때 실행되는 메소드
// 클라이언트가 연결되면 해당 클라이언트의 ID와 네임스페이스 정보를 로그에 출력
async handleConnection(@ConnectedSocket() socket: Socket) {
this.logger.log(`connected : ${socket.id} ${socket.nsp.name}`);
// await this.logger.log(`connected : ${socket.id} ${socket.nsp.name}`);
private logger: Logger = new Logger('AppGateway');

//의존성 주입
@InjectModel(Chatting.name) private readonly chattingModel: Model<Chatting>;
constructor(private readonly chatsService: ChatsService) {}

//유저가 연결 되었을때 기존은 socket: Socket
handleConnection(@ConnectedSocket() client: Socket) {
this.logger.log(`Client connected: ${client.id}`);
}
// 클라이언트가 'join_room' 메시지를 보낼 때 실행되는 메소드
@SubscribeMessage('join_room')
async handleJoinRoom(
@MessageBody()
payload: { nickname: string; roomId: number; profileImg: string },
@ConnectedSocket() socket: Socket
) {
socket.join(String(payload.roomId));
this.logger.log(
`Joined room: ${payload.roomId}, Nickname: ${payload.nickname}`
);
this.server.to(String(payload.roomId)).emit('user_connected', payload);

//유저가 연결해제 되었을때 로직
handleDisconnect(@ConnectedSocket() client: Socket) {
this.logger.log(`disconnected: ${client.id}`);
this.chatsService.disconnectClient(client, this.server);
}

// 클라이언트가 'submit_chat' 메시지를 보낼 때 실행되는 메소드
// 클라이언트가 'submit_chat' 메시지를 보낼 때 실행되는 메소드 (채팅을하고 그걸 다른유저에게 브로드캐스팅)
@SubscribeMessage('submit_chat')
async handleSubmitChat(
@MessageBody()
messageData: {
message: string;
nickname: string;
profileImg: string;
time: string;
roomId: number;
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@ConnectedSocket() _socket: Socket
) {
this.logger.log(
`New chat in room ${messageData.roomId}: ${messageData.message}`
);
@MessageBody() { roomId, nickname, profileImg, message }: IMessage
): Promise<void> {
const localDateTime = LocalDateTime.now().plusHours(9);
const period = localDateTime.hour() < 12 ? 'AM' : 'PM';
const formattedHour = localDateTime.hour() % 12 || 12;
const minute = localDateTime.minute().toString().padStart(2, '0');
const messageData: IMessage = {
message,
time: `${formattedHour}:${minute} ${period}`,
nickname,
roomId,
profileImg,
};

const socketObj = await this.socketModel.findOne({ id: _socket.id });
//const socketObj = await this.socketModel.findOne({ Socket });

// MongoDB에 채팅 메시지 저장
await this.chattingModel.create({
user: socketObj,
nickname: messageData.nickname,
profileImg: messageData.profileImg,
roomId: messageData.roomId,
time: messageData.time,
chat: messageData.message, // 수정: messageData.message를 사용하여 채팅 저장
// user: socketObj, // 메세지를보낸 소켓 정보
nickname: messageData.nickname, //메세지를 보낸 사용자의 닉네임
profileImg: messageData.profileImg, //메세지를 보낸 사용자의 프로필 이미지
roomId: messageData.roomId, // 채팅이 속한 방의 ID
time: messageData.time, // 메세지를 송신한 시간
chat: messageData.message, // 실제 채팅 메시지 내용.
created: new Date(), // 채팅 생성 시간 기록
});

this.logger.log(messageData);
this.server.to(String(messageData.roomId)).emit('new_chat', messageData);
}
}

// 일정기간(3일)이 지난 채팅을 db에서 삭제
async deleteOldChats() {
// 72시간(3일) 이상 지난 채팅 삭제
const chatScheduler = new Date();
// chatScheduler.setDate(chatScheduler.getDate() - 3); //3일
chatScheduler.setHours(chatScheduler.getHours() - 72); // 72시간
// chatScheduler.setMinutes(chatScheduler.getMinutes() - 2); // 4320분(3일) 테스트 2분
await this.chattingModel.deleteMany({ created: { $lt: chatScheduler } });
}

// 유저가 방에 참석할때
@SubscribeMessage('join_room') // 조인룸으로 태현님이 보내면 받는 on
async handleJoinRoom(
@ConnectedSocket() client: Socket,
@MessageBody() { nickname, roomId, profileImg, userId }: IRoomRequest
): Promise<void> {
client.leave(client.id);
client.join(String(roomId));

// 이전 채팅 내용을 불러옵니다.
const chatHistory = await this.chatsService.getChatHistory(roomId);

// 이전 채팅 내용과 함께 사용자 정보를 클라이언트에게 전송합니다.
client.emit('chat_history', chatHistory);
this.chatsService.joinRoom(client, this.server, {
nickname,
roomId,
profileImg,
userId,
});
}

// 유저가 방을 삭제할때
@SubscribeMessage('remove_room')
handleRemoveRoom(
@ConnectedSocket() client: Socket,
@MessageBody() { roomId }: IRoomRequest
): void {
this.chatsService.removeRoom(client, this.server, roomId);
}

// 유저가 방을 떠날때
@SubscribeMessage('leave_room')
handleLeaveRoom(
@ConnectedSocket() client: Socket,
@MessageBody() { roomId }: IRoomRequest
): void {
client.leave(String(roomId));
this.chatsService.leaveRoom(client, this.server, roomId);
}

// WebSocketGateway가 초기화될 때 실행되는 메소드
// WebSocketGateway가 초기화되면 로그를 출력합니다.
afterInit() {
this.logger.log('init');
}
} // 끝
4 changes: 2 additions & 2 deletions src/chats/chats.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Module } from '@nestjs/common';
import { ChatsGateway } from './chats.gateway';
import { MongooseModule } from '@nestjs/mongoose';
import { Chatting, ChattingSchema } from './models/chattings.model';
import { RoomChatsService } from './chats.service';
import { ChatsService } from './chats.service';

@Module({
imports: [
Expand All @@ -12,6 +12,6 @@ import { RoomChatsService } from './chats.service';
{ name: SocketModel.name, schema: SocketSchema },
]),
],
providers: [ChatsGateway, RoomChatsService],
providers: [ChatsGateway, ChatsService],
})
export class ChatsModule {}
Loading

0 comments on commit 5de9d58

Please sign in to comment.