Skip to content

Commit

Permalink
Merge pull request #118 from Me1tingPot/feature/#117
Browse files Browse the repository at this point in the history
Feature/#117
  • Loading branch information
yewonahn authored Jun 30, 2024
2 parents dd32294 + 9696ec8 commit c432782
Show file tree
Hide file tree
Showing 14 changed files with 59 additions and 160 deletions.
3 changes: 0 additions & 3 deletions src/main/java/meltingpot/server/auth/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import meltingpot.server.util.ResponseCode;
import meltingpot.server.util.SecurityUtil;
import meltingpot.server.util.TokenDto;
import meltingpot.server.util.push.PushService;
import meltingpot.server.util.r2.FileService;
import meltingpot.server.util.r2.FileUploadResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand Down Expand Up @@ -46,8 +45,6 @@ public class AuthService implements UserDetailsService {
private final FileService fileService;
private final AccountPushTokenRepository accountPushTokenRepository;

private final PushService pushService;

// 회원가입
@Transactional
public AccountResponseDto signup(SignupRequestDto signupRequest) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;

@Slf4j
@RestController
Expand All @@ -36,6 +37,16 @@ public void onConnect(SessionConnectEvent event){
log.info("sessionId = {}", socketSession.getSessionId());
}

@EventListener(SessionSubscribeEvent.class)
public void onSubscribe(SessionSubscribeEvent event){
final MessageHeaders headers = event.getMessage().getHeaders();

SocketSession socketSession = webSocketService.onSubscribe(headers);

log.info("sessionId = {}", socketSession.getSessionId());
}


@EventListener(SessionDisconnectEvent.class)
public void onDisconnect(SessionDisconnectEvent event) {
webSocketService.onDisconnect(event.getSessionId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public ChatRoomsPageResponse getChatRooms(Long userId, int page, int size) {

Slice<ChatRoomUser> chatRoomUserSlice = chatRoomUserRepository.findAllByUserId(userId, pageRequest);



return ChatRoomsPageResponse.from(chatRoomUserSlice);
}
}
19 changes: 0 additions & 19 deletions src/main/java/meltingpot/server/chat/service/ChatService.java

This file was deleted.

36 changes: 34 additions & 2 deletions src/main/java/meltingpot/server/chat/service/WebSocketService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package meltingpot.server.chat.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import meltingpot.server.chat.dto.ChatMessageGetResponse;
import meltingpot.server.chat.dto.ChatMessageSendRequest;
import meltingpot.server.chat.dto.UnreadChatMessageSendDTO;
Expand All @@ -16,7 +17,9 @@
import meltingpot.server.domain.repository.party.PartyRepository;
import meltingpot.server.exception.BadRequestException;
import meltingpot.server.exception.ResourceNotFoundException;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
Expand All @@ -29,6 +32,7 @@

import static meltingpot.server.util.ResponseCode.*;

@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
Expand Down Expand Up @@ -123,6 +127,7 @@ private void sendMessageToChatList(Account account, ChatMessage chatMessage, int
private void sendNotification(Account account, ChatMessage chatMessage) {
}

@Transactional
public SocketSession onConnect(MessageHeaders headers) {
UsernamePasswordAuthenticationToken user = (UsernamePasswordAuthenticationToken) headers.get("simpUser");
String simpSessionId = headers.get("simpSessionId").toString();
Expand All @@ -133,18 +138,45 @@ public SocketSession onConnect(MessageHeaders headers) {
UserDetails attributes = (UserDetails) user.getPrincipal();

String username = attributes.getUsername();
// Long chatRoomId = Long.parseLong(attributes.toString().split("chatRoomId=")[1].split(",")[0]);

SocketSession newSocketSession = SocketSession.builder()
.sessionId(simpSessionId)
.username(username)
.chatRoomId(1l)
.build();

return socketSessionRepository.save(newSocketSession);
}
}

@Transactional
public SocketSession onSubscribe(MessageHeaders headers) {
String simpSessionId = headers.get("simpSessionId").toString();

// Long chatRoomId = Long.parseLong(accessor.getFirstNativeHeader("chatRoomId"));
String chatRoomIdStr = (getChatRoomId(
Optional.ofNullable((String) headers.get("simpDestination"))
.orElse(CHAT_ROOM_NOT_FOUND.getDetail())));

Long chatRoomId;
try {
chatRoomId = Long.parseLong(chatRoomIdStr);
} catch (NumberFormatException e) {
throw new BadRequestException(CHAT_ROOM_NOT_FOUND);
}

SocketSession socketSession = socketSessionRepository.findBySessionId(simpSessionId);
socketSession.setChatRoomId(chatRoomId);

return socketSessionRepository.save(socketSession);
}

private String getChatRoomId(String destination) {
String[] test = destination.split("/");
String chatRoomId = test[test.length - 1];

return chatRoomId;
}

public void onDisconnect(String sessionId) {
SocketSession socketSession = socketSessionRepository.findBySessionId(sessionId);

Expand Down
2 changes: 2 additions & 0 deletions src/main/java/meltingpot/server/config/ChatErrorHandler.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package meltingpot.server.config;

import lombok.extern.slf4j.Slf4j;
import meltingpot.server.util.ErrorCode;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.stomp.StompCommand;
Expand All @@ -10,6 +11,7 @@

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class ChatErrorHandler extends StompSubProtocolErrorHandler {
// Interceptor 통해 jwt 검사하는 과정에서 에러 발생한 경우, 에러 핸들링
Expand Down
12 changes: 2 additions & 10 deletions src/main/java/meltingpot/server/config/JwtChannelInterceptor.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
package meltingpot.server.config;

import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import meltingpot.server.domain.entity.Account;
import meltingpot.server.domain.entity.chat.ChatRoom;
import meltingpot.server.domain.entity.chat.ChatRoomUser;
import meltingpot.server.domain.repository.AccountRepository;
import meltingpot.server.domain.repository.chat.ChatRoomUserRepository;
import meltingpot.server.exception.*;
import meltingpot.server.util.ResponseCode;
import org.springframework.core.Ordered;
Expand All @@ -19,13 +13,11 @@
import org.springframework.messaging.support.ChannelInterceptor;

import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import static meltingpot.server.util.ResponseCode.*;

Expand All @@ -35,8 +27,8 @@
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class JwtChannelInterceptor implements ChannelInterceptor {

private final String PUB_MESSAGE_PREFIX = "/pub/";
private final String SUB_MESSAGE_PREFIX = "/sub/";
private final String PUB_MESSAGE_PREFIX = "/chat/pub/";
private final String SUB_MESSAGE_PREFIX = "/chat/sub/";

private final TokenProvider tokenProvider;

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/meltingpot/server/config/JwtFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
|| request.getRequestURI().contains("/docs") || request.getRequestURI()
.contains("/favicon.ico") || request.getRequestURI().contains("/h2-console") ||
request.getRequestURI().contains("/swagger-ui") ||
request.getRequestURI().contains("/api-docs") || request.getRequestURI().equals("/chat")) {
request.getRequestURI().contains("/api-docs") ||
request.getRequestURI().contains("/chat")) {
filterChain.doFilter(request, response);
}
// 권한이 필요한 요청은 custom jwt filter를 거치도록 설정
Expand Down
19 changes: 0 additions & 19 deletions src/main/java/meltingpot/server/config/TokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ public TokenDto generateTokenDto(Authentication authentication){
.build();
}


// 재발급 TokenDto 반환
public TokenDto generateReissuedTokenDto(String accessToken) {
// accessToken에서 username 추출
Expand Down Expand Up @@ -124,24 +123,6 @@ public TokenDto generateReissuedTokenDto(String accessToken) {
.build();
}

public String generateSocketToken(Account account) {
final long now = (new Date()).getTime();
final long expiredTime = (long) 1000 * 60;
Date accessTokenExpiresIn = new Date(now + expiredTime);

String socketToken = Jwts.builder()
.setSubject(account.getUsername())
.setExpiration(accessTokenExpiresIn)
.signWith(key, SignatureAlgorithm.HS512)
.compact();

return socketToken;
}

public Claims getSocketTokenClaims(String accessToken) {
return parseClaims(accessToken);
}

// 저장되어있는 RefreshToken의 account와 접속한 계정이 동일한지 확인
public Boolean validRefreshToken(String refreshToken, String accessToken) {
String username = parseClaims(accessToken).getSubject();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBro
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.nullDestMatcher().permitAll()
.simpDestMatchers("/pub/**").authenticated()
.simpSubscribeDestMatchers("/sub/**").authenticated()
.simpDestMatchers("/chat/pub/**").authenticated()
.simpSubscribeDestMatchers("/chat/sub/**").authenticated()
.anyMessage().denyAll();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ public class SocketSession {
@Column(name = "username")
private String username;

@NotNull
@Column(name = "chatRoom_id")
private Long chatRoomId;

public void setChatRoomId(Long chatRoomId) {
this.chatRoomId = chatRoomId;
}
}
32 changes: 0 additions & 32 deletions src/main/java/meltingpot/server/util/push/PushConfig.java

This file was deleted.

42 changes: 0 additions & 42 deletions src/main/java/meltingpot/server/util/push/PushService.java

This file was deleted.

0 comments on commit c432782

Please sign in to comment.