├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── test │ ├── resources │ │ ├── application.yml │ │ ├── application-test.yml │ │ ├── application-oauth.yml │ │ └── application-common.yml │ └── java │ │ └── com │ │ └── challenge │ │ └── chat │ │ ├── ChatApplicationTests.java │ │ ├── config │ │ └── JasyptConfigTest.java │ │ └── domain │ │ ├── member │ │ ├── service │ │ │ └── MemberServiceTest.java │ │ └── controller │ │ │ └── MemberControllerTest.java │ │ └── chat │ │ └── service │ │ └── ChatServiceTest.java └── main │ ├── resources │ ├── elastic │ │ ├── chat-setting.json │ │ └── chat-mapping.json │ ├── application.yml │ ├── static │ │ └── index.html │ ├── application-local.yml │ ├── application-oauth.yml │ ├── application-common.yml │ └── application-dev.yml │ └── java │ └── com │ └── challenge │ └── chat │ ├── domain │ ├── member │ │ ├── constant │ │ │ ├── SocialType.java │ │ │ └── MemberRole.java │ │ ├── dto │ │ │ ├── request │ │ │ │ ├── MemberAddRequest.java │ │ │ │ └── SignupRequest.java │ │ │ └── MemberDto.java │ │ ├── repository │ │ │ ├── MemberFriendRepository.java │ │ │ └── MemberRepository.java │ │ ├── entity │ │ │ ├── MemberFriend.java │ │ │ └── Member.java │ │ ├── controller │ │ │ └── MemberController.java │ │ └── service │ │ │ └── MemberService.java │ └── chat │ │ ├── entity │ │ ├── MessageType.java │ │ ├── TimeStamped.java │ │ ├── MemberChatRoom.java │ │ ├── ChatRoom.java │ │ ├── Chat.java │ │ └── ChatES.java │ │ ├── constant │ │ └── KafkaConstants.java │ │ ├── dto │ │ ├── request │ │ │ ├── ChatRoomAddRequest.java │ │ │ └── ChatRoomCreateRequest.java │ │ ├── ChatRoomDto.java │ │ └── ChatDto.java │ │ ├── repository │ │ ├── ChatRoomRepository.java │ │ ├── ChatSearchRepository.java │ │ ├── ChatRepository.java │ │ └── MemberChatRoomRepository.java │ │ ├── service │ │ ├── Producer.java │ │ ├── Consumer.java │ │ └── ChatService.java │ │ ├── config │ │ ├── ProducerConfig.java │ │ ├── ConsumerConfig.java │ │ └── RabbitConfig.java │ │ └── controller │ │ └── ChatController.java │ ├── exception │ ├── dto │ │ ├── ErrorCode.java │ │ ├── ErrorResponse.java │ │ ├── CommonErrorCode.java │ │ ├── MemberErrorCode.java │ │ └── ChatErrorCode.java │ ├── RestApiException.java │ └── GlobalExceptionHandler.java │ ├── security │ ├── oauth │ │ ├── dto │ │ │ ├── OAuth2UserInfo.java │ │ │ ├── GoogleOAuth2UserInfo.java │ │ │ ├── CustomOAuth2User.java │ │ │ └── OAuthAttributes.java │ │ ├── handler │ │ │ ├── OAuth2LoginFailureHandler.java │ │ │ └── OAuth2LoginSuccessHandler.java │ │ └── service │ │ │ └── CustomOAuth2UserService.java │ ├── jwt │ │ ├── util │ │ │ └── PasswordUtil.java │ │ ├── service │ │ │ └── JwtService.java │ │ └── filter │ │ │ └── JwtAuthenticationProcessingFilter.java │ └── login │ │ ├── handler │ │ ├── LoginFailureHandler.java │ │ └── LoginSuccessHandler.java │ │ ├── service │ │ └── LoginService.java │ │ └── filter │ │ └── CustomJsonUsernamePasswordAuthenticationFilter.java │ ├── config │ ├── CustomPrometheusConfig.java │ ├── ElasticSearchConfig.java │ ├── JasyptConfig.java │ ├── WebSocketConfig.java │ ├── MongoConfig.java │ └── SecurityConfig.java │ └── ChatApplication.java ├── appspec.yml ├── scripts ├── stop.sh └── start.sh ├── HELP.md ├── .github └── workflows │ └── main.yml ├── gradlew.bat ├── .gitignore ├── README.md └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'chat' 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/god-kao-talk/chat-challenge-BE/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | group: 4 | test: 5 | - common 6 | - oauth 7 | 8 | -------------------------------------------------------------------------------- /src/main/resources/elastic/chat-setting.json: -------------------------------------------------------------------------------- 1 | { 2 | "analysis": { 3 | "analyzer": { 4 | "korean": { 5 | "type": "nori" 6 | } 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/constant/SocialType.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.constant; 2 | 3 | public enum SocialType { 4 | KAKAO, NAVER, GOOGLE 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/entity/MessageType.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.entity; 2 | 3 | public enum MessageType { 4 | ENTER, 5 | TALK, 6 | LEAVE, 7 | IMAGE 8 | } 9 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | group: 4 | local: 5 | - common 6 | - oauth 7 | dev: 8 | - common 9 | - oauth 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | Kakao Login
2 | Google Login
3 | Naver Login
-------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/resources/application-local.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | activate: 4 | on-profile: local 5 | datasource: 6 | url: jdbc:h2:mem:db;MODE=MYSQL 7 | username: sa 8 | password: '' 9 | h2: 10 | console: 11 | enabled: true -------------------------------------------------------------------------------- /src/test/resources/application-test.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | activate: 4 | on-profile: local 5 | datasource: 6 | url: jdbc:h2:mem:db;MODE=MYSQL 7 | username: sa 8 | password: '' 9 | h2: 10 | console: 11 | enabled: true -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/exception/dto/ErrorCode.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.exception.dto; 2 | 3 | import org.springframework.http.HttpStatus; 4 | 5 | public interface ErrorCode { 6 | String name(); 7 | HttpStatus getHttpStatus(); 8 | String getMessage(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/dto/request/MemberAddRequest.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.dto.request; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | 6 | @Getter 7 | @NoArgsConstructor 8 | public class MemberAddRequest { 9 | private String email; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/constant/KafkaConstants.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.constant; 2 | 3 | public class KafkaConstants { 4 | public static final String KAFKA_TOPIC = "kafka-chat"; 5 | public static final String GROUP_ID = "foo"; 6 | public static final String KAFKA_BROKER = "broker:9092"; 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/constant/MemberRole.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.constant; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | 6 | @Getter 7 | @RequiredArgsConstructor 8 | public enum MemberRole { 9 | 10 | GUEST("ROLE_GUEST"), USER("ROLE_USER"); 11 | 12 | private final String key; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/exception/dto/ErrorResponse.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.exception.dto; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | 6 | @Getter 7 | @AllArgsConstructor 8 | public class ErrorResponse { 9 | 10 | private final String errorCode; 11 | private final String status; 12 | private final String message; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/dto/request/ChatRoomAddRequest.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.dto.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | 7 | @AllArgsConstructor 8 | @NoArgsConstructor 9 | @Getter 10 | public class ChatRoomAddRequest { 11 | private String roomCode; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/dto/request/ChatRoomCreateRequest.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.dto.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | 7 | @AllArgsConstructor 8 | @NoArgsConstructor 9 | @Getter 10 | public class ChatRoomCreateRequest { 11 | private String roomName; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/exception/RestApiException.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.exception; 2 | 3 | import com.challenge.chat.exception.dto.ErrorCode; 4 | 5 | import lombok.Getter; 6 | import lombok.RequiredArgsConstructor; 7 | 8 | @Getter 9 | @RequiredArgsConstructor 10 | public class RestApiException extends RuntimeException { 11 | 12 | private final ErrorCode errorCode; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/resources/elastic/chat-mapping.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties" : { 3 | "type" : {"type" : "text"}, 4 | "nickname" : {"type" : "text"}, 5 | "email" : {"type" : "text"}, 6 | "roomCode" : {"type" : "text"}, 7 | "message" : {"type" : "text", "analyzer" : "korean"}, 8 | "createdAt" : { 9 | "type" : "date" 10 | }, 11 | "imageUrl" : {"type" : "text"} 12 | } 13 | } -------------------------------------------------------------------------------- /appspec.yml: -------------------------------------------------------------------------------- 1 | version: 0.0 2 | os: linux 3 | 4 | files: 5 | - source: / 6 | destination: /home/ubuntu/spring-github-action 7 | overwrite: yes 8 | file_exists_behavior: OVERWRITE 9 | permissions: 10 | - object: / 11 | owner: ubuntu 12 | group: ubuntu 13 | 14 | hooks: 15 | AfterInstall: 16 | - location: scripts/stop.sh 17 | timeout: 60 18 | ApplicationStart: 19 | - location: scripts/start.sh 20 | timeout: 60 21 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/repository/ChatRoomRepository.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.repository; 2 | 3 | import com.challenge.chat.domain.chat.entity.ChatRoom; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | 7 | import java.util.Optional; 8 | public interface ChatRoomRepository extends JpaRepository { 9 | 10 | Optional findByRoomCode(String roomCode); 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/com/challenge/chat/ChatApplicationTests.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat; 2 | // 3 | // import org.junit.jupiter.api.DisplayName; 4 | // import org.junit.jupiter.api.Test; 5 | // import org.springframework.boot.test.context.SpringBootTest; 6 | // import org.springframework.test.context.ActiveProfiles; 7 | // 8 | // @SpringBootTest 9 | // @ActiveProfiles({"test"}) 10 | // class ChatApplicationTests { 11 | // @Test 12 | // @DisplayName("통합 테스트 성공") 13 | // void contextLoads() { 14 | // } 15 | // } 16 | -------------------------------------------------------------------------------- /scripts/stop.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ROOT_PATH="/home/ubuntu/spring-github-action" 4 | JAR="$ROOT_PATH/application-plain.jar" 5 | STOP_LOG="$ROOT_PATH/stop.log" 6 | CONTAINER="com.challenge.chat.ChatApplication" 7 | SERVICE_PID=$(pgrep -f $CONTAINER) # 실행중인 Spring 서버의 PID 8 | 9 | NOW=$(date +%c) 10 | 11 | 12 | if [ -z "$SERVICE_PID" ]; then 13 | echo " [$NOW] 서비스 NouFound" >> $STOP_LOG 14 | else 15 | echo " [$NOW] [$SERVICE_PID] 서비스 종료 " >> $STOP_LOG 16 | kill -9 "$SERVICE_PID" 17 | # kill -9 $SERVICE_PID # 강제 종료를 하고 싶다면 이 명령어 사용 18 | fi 19 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/repository/ChatSearchRepository.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat.domain.chat.repository; 2 | // 3 | // import java.util.List; 4 | // 5 | // import org.springframework.data.domain.Pageable; 6 | // import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 7 | // 8 | // import com.challenge.chat.domain.chat.entity.ChatES; 9 | // 10 | // public interface ChatSearchRepository extends ElasticsearchRepository { 11 | // 12 | // List findByMessage(String message); 13 | // } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/repository/MemberFriendRepository.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.repository; 2 | 3 | import com.challenge.chat.domain.member.entity.Member; 4 | import com.challenge.chat.domain.member.entity.MemberFriend; 5 | 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | 8 | import java.util.Optional; 9 | 10 | public interface MemberFriendRepository extends JpaRepository { 11 | 12 | Optional findByMemberAndFriend(Member member, Member friend); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/dto/request/SignupRequest.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.dto.request; 2 | 3 | import javax.validation.constraints.NotBlank; 4 | 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Getter 9 | @NoArgsConstructor 10 | public class SignupRequest { 11 | @NotBlank(message = "Email은 필수 값입니다.") 12 | private String email; 13 | 14 | @NotBlank(message = "Password는 필수 값입니다.") 15 | private String password; 16 | 17 | @NotBlank(message = "Nickname은 필수 값입니다.") 18 | private String nickname; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/exception/dto/CommonErrorCode.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.exception.dto; 2 | 3 | import org.springframework.http.HttpStatus; 4 | 5 | import lombok.Getter; 6 | import lombok.RequiredArgsConstructor; 7 | 8 | @Getter 9 | @RequiredArgsConstructor 10 | public enum CommonErrorCode implements ErrorCode { 11 | 12 | INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "내부 서버에서 문제가 발생했습니다"), 13 | INVALID_REQUEST_PARAMETER(HttpStatus.BAD_REQUEST, "유효하지 않은 파라미터 입니다") 14 | ; 15 | 16 | private final HttpStatus httpStatus; 17 | private final String message; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/oauth/dto/OAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.oauth.dto; 2 | 3 | import java.util.Map; 4 | 5 | public abstract class OAuth2UserInfo { 6 | 7 | protected Map attributes; 8 | 9 | public OAuth2UserInfo(Map attributes) { 10 | this.attributes = attributes; 11 | } 12 | 13 | public abstract String getId(); //소셜 식별 값 : 구글 - "sub", 카카오 - "id", 네이버 - "id" 14 | 15 | public abstract String getNickname(); 16 | 17 | public abstract String getImageUrl(); 18 | 19 | public abstract String getEmail(); 20 | } 21 | -------------------------------------------------------------------------------- /src/main/resources/application-oauth.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | activate: 4 | on-profile: oauth 5 | security: 6 | oauth2: 7 | client: 8 | registration: 9 | google: 10 | client-id: ENC(BqXz+zkPlztuGEnq087JZZvP5Jjy/TGDLCZsFAfqscsPkgcpWACpOMON4Bwg/9cHeYDYKJUB25jGq5t6COe4MtZr3Ra7BBosNYP0TlMyRBxyxzfPEX71gQ==) 11 | client-secret: ENC(O9Lq7E1QZO39aoVW0Z55fctcP/WmrzyVO/LmQByTzU2Ww2Hu+lDq6p3AYAvvcwVs) 12 | scope: 13 | - profile 14 | - email 15 | # redirect-uri: https://www.hhaegg.o-r.kr/login/oauth2/code/google -------------------------------------------------------------------------------- /src/test/resources/application-oauth.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | activate: 4 | on-profile: oauth 5 | security: 6 | oauth2: 7 | client: 8 | registration: 9 | google: 10 | client-id: ENC(BqXz+zkPlztuGEnq087JZZvP5Jjy/TGDLCZsFAfqscsPkgcpWACpOMON4Bwg/9cHeYDYKJUB25jGq5t6COe4MtZr3Ra7BBosNYP0TlMyRBxyxzfPEX71gQ==) 11 | client-secret: ENC(O9Lq7E1QZO39aoVW0Z55fctcP/WmrzyVO/LmQByTzU2Ww2Hu+lDq6p3AYAvvcwVs) 12 | scope: 13 | - profile 14 | - email 15 | # redirect-uri: https://www.hhaegg.o-r.kr/login/oauth2/code/google -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/dto/ChatRoomDto.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.dto; 2 | 3 | import com.challenge.chat.domain.chat.entity.ChatRoom; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | 9 | @Getter 10 | @Setter 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class ChatRoomDto { 14 | private String roomCode; 15 | private String roomName; 16 | 17 | public static ChatRoomDto from(ChatRoom chatRoom) { 18 | return new ChatRoomDto(chatRoom.getRoomCode(), chatRoom.getRoomName()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/resources/application-common.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | activate: 4 | on-profile: common 5 | jpa: 6 | open-in-view: false 7 | jwt: 8 | secretKey: ENC(uvRR3r/GGDxBWH5fuINwi8uQVmhDV9lkuDtiDmEJeKnEMNYLlIZ/lfPYSrpn/LLPUtJflpTdSDxXGd6qRIfWrWmvtdS88f8JI3B1yQQ0VQRsywHyg/wB7w==) 9 | access: 10 | expiration: 604800000 # 1시간(60분) (1000L(ms -> s) * 60L(s -> m) * 60L(m -> h)) 11 | header: Authorization 12 | refresh: 13 | expiration: 604800000 # (1000L(ms -> s) * 60L(s -> m) * 60L(m -> h) * 24L(h -> 하루) * 14(2주)) 14 | header: Authorization-refresh 15 | logging: 16 | level: 17 | org.springframework.data.elasticsearch.client.WIRE: TRACE -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/repository/ChatRepository.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.repository; 2 | 3 | import com.challenge.chat.domain.chat.entity.Chat; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | 6 | import java.util.List; 7 | import java.util.Optional; 8 | 9 | public interface ChatRepository extends MongoRepository { 10 | // Spring Data MongoDB -> https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/ 11 | 12 | Optional> findByRoomCode(String roomCode); 13 | 14 | Optional> findByRoomCodeAndMessageContaining(String roomCode, String message); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/config/CustomPrometheusConfig.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.config; 2 | 3 | import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | import io.micrometer.core.instrument.MeterRegistry; 8 | import lombok.extern.slf4j.Slf4j; 9 | 10 | @Configuration 11 | @Slf4j 12 | public class CustomPrometheusConfig { 13 | 14 | @Bean 15 | MeterRegistryCustomizer metricsCommonTags() { 16 | return registry -> registry.config().commonTags("application", "PROMETHEUS-SAMPLE-SERVER"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/exception/dto/MemberErrorCode.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.exception.dto; 2 | 3 | import org.springframework.http.HttpStatus; 4 | 5 | import lombok.Getter; 6 | import lombok.RequiredArgsConstructor; 7 | 8 | @Getter 9 | @RequiredArgsConstructor 10 | public enum MemberErrorCode implements ErrorCode { 11 | 12 | MEMBER_NOT_FOUND(HttpStatus.NOT_FOUND, "회원을 찾을 수 없습니다"), 13 | DUPLICATED_EMAIL(HttpStatus.BAD_REQUEST, "이미 존재하는 email 입니다"), 14 | DUPLICATED_MEMBER(HttpStatus.BAD_REQUEST, "이미 추가된 친구 입니다"), 15 | ADDED_FRIEND(HttpStatus.BAD_REQUEST, "이미 추가된 친구 입니다") 16 | ; 17 | 18 | private final HttpStatus httpStatus; 19 | private final String message; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/repository/MemberChatRoomRepository.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.repository; 2 | 3 | import com.challenge.chat.domain.chat.entity.ChatRoom; 4 | import com.challenge.chat.domain.chat.entity.MemberChatRoom; 5 | import com.challenge.chat.domain.member.entity.Member; 6 | 7 | import org.springframework.data.jpa.repository.JpaRepository; 8 | 9 | import java.util.List; 10 | import java.util.Optional; 11 | 12 | public interface MemberChatRoomRepository extends JpaRepository { 13 | 14 | Optional> findByMember(Member member); 15 | Optional findByMemberAndRoom(Member member, ChatRoom room); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/exception/dto/ChatErrorCode.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.exception.dto; 2 | 3 | import org.springframework.http.HttpStatus; 4 | 5 | import lombok.Getter; 6 | import lombok.RequiredArgsConstructor; 7 | 8 | @Getter 9 | @RequiredArgsConstructor 10 | public enum ChatErrorCode implements ErrorCode { 11 | 12 | CHATROOM_NOT_FOUND(HttpStatus.NOT_FOUND, "채팅방이 존재하지 않습니다"), 13 | KAFKA_PRODUCER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "채팅 전송에 실패했습니다"), 14 | KAFKA_CONSUMER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "채팅 수신에 실패했습니다"), 15 | SOCKET_CONNECTION_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "소켓 통신이 불안정 합니다"), 16 | ; 17 | 18 | private final HttpStatus httpStatus; 19 | private final String message; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/oauth/dto/GoogleOAuth2UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.oauth.dto; 2 | 3 | import java.util.Map; 4 | 5 | public class GoogleOAuth2UserInfo extends OAuth2UserInfo { 6 | 7 | public GoogleOAuth2UserInfo(Map attributes) { 8 | super(attributes); 9 | } 10 | 11 | @Override 12 | public String getId() { 13 | return (String) attributes.get("sub"); 14 | } 15 | 16 | @Override 17 | public String getNickname() { 18 | return (String) attributes.get("name"); 19 | } 20 | 21 | @Override 22 | public String getImageUrl() { 23 | return (String) attributes.get("picture"); 24 | } 25 | 26 | @Override 27 | public String getEmail() { 28 | return (String) attributes.get("email"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/entity/TimeStamped.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.entity; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.EntityListeners; 7 | import javax.persistence.MappedSuperclass; 8 | 9 | import org.springframework.data.annotation.CreatedDate; 10 | import org.springframework.data.annotation.LastModifiedDate; 11 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 12 | 13 | import lombok.Getter; 14 | 15 | @Getter 16 | @MappedSuperclass 17 | @EntityListeners(AuditingEntityListener.class) 18 | public abstract class TimeStamped { 19 | 20 | @CreatedDate 21 | @Column(updatable = false) 22 | private LocalDateTime createdAt; 23 | 24 | @LastModifiedDate 25 | private LocalDateTime modifiedAt; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/repository/MemberRepository.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.repository; 2 | 3 | import com.challenge.chat.domain.member.constant.SocialType; 4 | import com.challenge.chat.domain.member.entity.Member; 5 | 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | 8 | import java.util.Optional; 9 | 10 | public interface MemberRepository extends JpaRepository { 11 | 12 | Optional findByEmail(String email); 13 | 14 | Optional findByRefreshToken(String refreshToken); 15 | 16 | /** 17 | * 소셜 타입과 소셜의 식별값으로 회원 찾는 메소드 18 | * 정보 제공을 동의한 순간 DB에 저장해야하지만, 아직 추가 정보(사는 도시, 나이 등)를 입력받지 않았으므로 19 | * 유저 객체는 DB에 있지만, 추가 정보가 빠진 상태이다. 20 | * 따라서 추가 정보를 입력받아 회원 가입을 진행할 때 소셜 타입, 식별자로 해당 회원을 찾기 위한 메소드 21 | */ 22 | Optional findBySocialTypeAndSocialId(SocialType socialType, String socialId); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/dto/MemberDto.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.dto; 2 | 3 | import com.challenge.chat.domain.member.entity.Member; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Getter 8 | @NoArgsConstructor 9 | public class MemberDto { 10 | 11 | private Long id; 12 | private String email; 13 | private String imageUrl; 14 | private String nickname; 15 | 16 | private MemberDto(Long id, String email, String imageUrl, String nickname) { 17 | this.id = id; 18 | this.email = email; 19 | this.imageUrl = imageUrl; 20 | this.nickname = nickname; 21 | } 22 | 23 | public static MemberDto from(Member member) { 24 | return new MemberDto( 25 | member.getId(), 26 | member.getEmail(), 27 | member.getImageUrl(), 28 | member.getNickname() 29 | ); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /scripts/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ROOT_PATH="/home/ubuntu/spring-github-action" 4 | JAR="$ROOT_PATH/application-plain.jar" 5 | #CONTAINER="com.challenge.chat.ChatApplication" 6 | #IMAGE="chat-challenge" 7 | #TAG="latest" 8 | 9 | APP_LOG="$ROOT_PATH/application.log" 10 | ERROR_LOG="$ROOT_PATH/error.log" 11 | START_LOG="$ROOT_PATH/start.log" 12 | PROFILES_ACTIVE="Dspring.profiles.active=dev" 13 | 14 | NOW=$(date +%c) 15 | 16 | echo "[$NOW] $JAR 복사" >> $START_LOG 17 | cp $ROOT_PATH/build/libs/chat-0.0.1-SNAPSHOT.jar $JAR 18 | 19 | # echo "[$NOW] > $JAR 실행" >> $START_LOG 20 | # nohup java -jar -$PROFILES_ACTIVE $JAR > $APP_LOG 2> $ERROR_LOG & 21 | 22 | #echo "[$NOW] JIB 도커 빌드" >> $START_LOG 23 | #cd $ROOT_PATH 24 | #./gradlew jibDockerBuild 25 | # 26 | #echo "[$NOW] > $IMAGE 실행" >> $START_LOG 27 | #docker run -d -p 8080:8080 --name $IMAGE $IMAGE:$TAG 28 | # 29 | #SERVICE_PID=$(pgrep -f $CONTAINER 30 | #echo "[$NOW] > 서비스 PID: $SERVICE_PID" >> $START_LOG 31 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/jwt/util/PasswordUtil.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.jwt.util; 2 | 3 | import java.util.Random; 4 | 5 | public class PasswordUtil { 6 | 7 | public static String generateRandomPassword() { 8 | int index = 0; 9 | char[] charSet = new char[] { 10 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 11 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 12 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 13 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 14 | 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' 15 | }; //배열안의 문자 숫자는 원하는대로 16 | 17 | StringBuffer password = new StringBuffer(); 18 | Random random = new Random(); 19 | 20 | for (int i = 0; i < 8 ; i++) { 21 | double rd = random.nextDouble(); 22 | index = (int) (charSet.length * rd); 23 | 24 | password.append(charSet[index]); 25 | } 26 | System.out.println(password); 27 | return password.toString(); 28 | //StringBuffer를 String으로 변환해서 return 하려면 toString()을 사용하면 된다. 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/oauth/handler/OAuth2LoginFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.oauth.handler; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.ServletException; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.springframework.security.core.AuthenticationException; 10 | import org.springframework.security.web.authentication.AuthenticationFailureHandler; 11 | import org.springframework.stereotype.Component; 12 | 13 | import lombok.extern.slf4j.Slf4j; 14 | 15 | @Slf4j 16 | @Component 17 | public class OAuth2LoginFailureHandler implements AuthenticationFailureHandler { 18 | @Override 19 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws 20 | IOException, 21 | ServletException { 22 | response.setStatus(HttpServletResponse.SC_BAD_REQUEST); 23 | response.getWriter().write("소셜 로그인 실패! 서버 로그를 확인해주세요."); 24 | log.info("소셜 로그인에 실패했습니다. 에러 메시지 : {}", exception.getMessage()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/service/Producer.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.service; 2 | 3 | import com.challenge.chat.domain.chat.dto.ChatDto; 4 | import com.challenge.chat.domain.chat.entity.Chat; 5 | import com.challenge.chat.exception.RestApiException; 6 | import com.challenge.chat.exception.dto.ChatErrorCode; 7 | 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.kafka.core.KafkaTemplate; 11 | import org.springframework.stereotype.Component; 12 | 13 | @Component 14 | @Slf4j 15 | public class Producer { 16 | 17 | @Autowired 18 | private KafkaTemplate kafkaTemplate; 19 | 20 | public void send(String topic, ChatDto data) { 21 | log.info("sending data='{}' to topic='{}'", data, topic); 22 | try { 23 | kafkaTemplate.send(topic, data).get(); // send to react clients via websocket (STOMP) 24 | } catch (Exception e) { 25 | throw new RestApiException(ChatErrorCode.KAFKA_PRODUCER_ERROR); 26 | } 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/test/resources/application-common.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | activate: 4 | on-profile: common 5 | jpa: 6 | properties: 7 | hibernate: 8 | show_sql: true 9 | format_sql: true 10 | hbm2ddl: 11 | auto: update 12 | open-in-view: false 13 | 14 | jwt: 15 | secretKey: ENC(uvRR3r/GGDxBWH5fuINwi8uQVmhDV9lkuDtiDmEJeKnEMNYLlIZ/lfPYSrpn/LLPUtJflpTdSDxXGd6qRIfWrWmvtdS88f8JI3B1yQQ0VQRsywHyg/wB7w==) 16 | 17 | access: 18 | expiration: 3600000 # 1시간(60분) (1000L(ms -> s) * 60L(s -> m) * 60L(m -> h)) 19 | header: Authorization 20 | 21 | refresh: 22 | expiration: 1209600000 # (1000L(ms -> s) * 60L(s -> m) * 60L(m -> h) * 24L(h -> 하루) * 14(2주)) 23 | header: Authorization-refresh 24 | 25 | cloud: 26 | aws: 27 | s3: 28 | bucket: chatchallengebucket 29 | stack.auto: false 30 | region.static: ENC(0bq5sPO9vq8ID5qNhZiAJw1Kllk8pwUn) 31 | credentials: 32 | accessKey: ENC(DlgOorwSMoUWRgJVRCLT5bMjNYRFF63S3ZSnOEghuU0=) 33 | secretKey: ENC(CMos8FOe37EVh8yf5UYKcSH7zuDzlNCd8gt69yogP8SrBogWqOg0/+vNbJW14Rsw4iyeZxpsjoA=) 34 | 35 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/service/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.service; 2 | 3 | import com.challenge.chat.domain.chat.constant.KafkaConstants; 4 | import com.challenge.chat.domain.chat.dto.ChatDto; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.kafka.annotation.KafkaListener; 8 | import org.springframework.messaging.simp.SimpMessagingTemplate; 9 | import org.springframework.stereotype.Component; 10 | 11 | @Slf4j 12 | @Component 13 | public class Consumer { 14 | /** 15 | * @KafkaLister 어노테이션을 통해 Kafka로부터 메세지를 받을 수 있음 16 | * template.convertAndSend를 통해 WebSocket으로 메시지를 전송 17 | * Message를 작성할 때 경로 잘 보고 import 18 | */ 19 | @Autowired 20 | SimpMessagingTemplate msgOperation; 21 | 22 | // @KafkaListener( 23 | // topics = KafkaConstants.KAFKA_TOPIC, 24 | // groupId = KafkaConstants.GROUP_ID 25 | // ) 26 | // public void consume(ChatDto chatDto) { 27 | // msgOperation.convertAndSend("/topic/chat/room/" + chatDto.getRoomCode(), chatDto); 28 | // } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/entity/MemberFriend.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import javax.persistence.JoinColumn; 8 | import javax.persistence.ManyToOne; 9 | 10 | import lombok.Getter; 11 | import lombok.NoArgsConstructor; 12 | 13 | @Entity 14 | @Getter 15 | @NoArgsConstructor 16 | public class MemberFriend { 17 | 18 | @Id 19 | @GeneratedValue(strategy = GenerationType.IDENTITY) 20 | private Long id; 21 | 22 | @ManyToOne 23 | @JoinColumn(name = "MEMBER_ID") 24 | private Member member; 25 | 26 | @ManyToOne 27 | @JoinColumn(name = "FRIEND_ID") 28 | private Member friend; 29 | 30 | private MemberFriend(Member member, Member friend) { 31 | this.member = member; 32 | this.friend = friend; 33 | // member.getFriendList().add(this); 34 | } 35 | 36 | public static MemberFriend of(Member member, Member friend) { 37 | return new MemberFriend(member, friend); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/config/ElasticSearchConfig.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat.config; 2 | // 3 | // import org.elasticsearch.client.RestHighLevelClient; 4 | // import org.springframework.context.annotation.Configuration; 5 | // import org.springframework.data.elasticsearch.client.ClientConfiguration; 6 | // import org.springframework.data.elasticsearch.client.RestClients; 7 | // import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; 8 | // import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; 9 | // 10 | // import com.challenge.chat.domain.chat.repository.ChatSearchRepository; 11 | // 12 | // @Configuration 13 | // @EnableElasticsearchRepositories(basePackageClasses = {ChatSearchRepository.class}) 14 | // public class ElasticSearchConfig extends AbstractElasticsearchConfiguration { 15 | // @Override 16 | // public RestHighLevelClient elasticsearchClient() { 17 | // // http port 와 통신할 주소 18 | // ClientConfiguration configuration = ClientConfiguration.builder() 19 | // .connectedTo("es:9200") 20 | // .build(); 21 | // return RestClients.create(configuration).rest(); 22 | // } 23 | // } 24 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/entity/MemberChatRoom.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.GenerationType; 6 | import javax.persistence.Id; 7 | import javax.persistence.JoinColumn; 8 | import javax.persistence.ManyToOne; 9 | 10 | import com.challenge.chat.domain.member.entity.Member; 11 | 12 | import lombok.Getter; 13 | import lombok.NoArgsConstructor; 14 | 15 | @Entity 16 | @Getter 17 | @NoArgsConstructor 18 | public class MemberChatRoom { 19 | @Id 20 | @GeneratedValue(strategy = GenerationType.IDENTITY) 21 | private Long id; 22 | 23 | @ManyToOne 24 | @JoinColumn(name = "ROOM_ID") 25 | private ChatRoom room; 26 | 27 | @ManyToOne 28 | @JoinColumn(name = "MEMBER_ID") 29 | private Member member; 30 | 31 | private MemberChatRoom(ChatRoom room, Member member) { 32 | this.room = room; 33 | this.member = member; 34 | // room.getMemberList().add(this); 35 | // member.getRoomList().add(this); 36 | } 37 | 38 | public static MemberChatRoom of(ChatRoom room, Member member) { 39 | return new MemberChatRoom(room, member); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/ChatApplication.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.context.annotation.ComponentScan; 6 | import org.springframework.context.annotation.FilterType; 7 | import org.springframework.data.elasticsearch.config.EnableElasticsearchAuditing; 8 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 9 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 10 | import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 11 | 12 | import com.challenge.chat.domain.chat.repository.ChatRepository; 13 | 14 | @EnableElasticsearchAuditing 15 | @EnableJpaAuditing 16 | @EnableJpaRepositories(excludeFilters = @ComponentScan.Filter( 17 | type = FilterType.ASSIGNABLE_TYPE, 18 | classes = {ChatRepository.class})) 19 | @EnableMongoRepositories(basePackageClasses = {ChatRepository.class}) 20 | @SpringBootApplication 21 | public class ChatApplication { 22 | 23 | public static void main(String[] args) { 24 | SpringApplication.run(ChatApplication.class, args); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/login/handler/LoginFailureHandler.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.login.handler; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | import org.springframework.security.core.AuthenticationException; 9 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; 10 | 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | /** 14 | * JWT 로그인 실패 시 처리하는 핸들러 15 | * SimpleUrlAuthenticationFailureHandler를 상속받아서 구현 16 | */ 17 | @Slf4j 18 | public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler { 19 | 20 | @Override 21 | public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, 22 | AuthenticationException exception) throws IOException { 23 | response.setStatus(HttpServletResponse.SC_BAD_REQUEST); 24 | response.setCharacterEncoding("UTF-8"); 25 | response.setContentType("text/plain;charset=UTF-8"); 26 | response.getWriter().write("로그인 실패! 이메일이나 비밀번호를 확인해주세요."); 27 | log.info("로그인에 실패했습니다. 메시지 : {}", exception.getMessage()); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/entity/ChatRoom.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.entity; 2 | 3 | import java.util.List; 4 | import java.util.UUID; 5 | 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | 9 | import javax.persistence.CascadeType; 10 | import javax.persistence.Column; 11 | import javax.persistence.Entity; 12 | import javax.persistence.GeneratedValue; 13 | import javax.persistence.GenerationType; 14 | import javax.persistence.Id; 15 | import javax.persistence.OneToMany; 16 | 17 | @Entity 18 | @Getter 19 | @NoArgsConstructor 20 | public class ChatRoom extends TimeStamped { 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | @Column(name = "ROOM_ID") 24 | private Long id; 25 | 26 | private String roomCode; 27 | 28 | @Column(nullable = false) 29 | private String roomName; 30 | 31 | @OneToMany(mappedBy = "room", orphanRemoval = true, cascade = CascadeType.ALL) 32 | private List memberList; 33 | 34 | private ChatRoom(String roomName) { 35 | this.roomCode = UUID.randomUUID().toString(); 36 | this.roomName = roomName; 37 | } 38 | 39 | public static ChatRoom of(String roomName) { 40 | return new ChatRoom(roomName); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/entity/Chat.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | import java.time.Instant; 9 | 10 | import org.springframework.data.mongodb.core.mapping.Document; 11 | 12 | @Getter 13 | @Setter 14 | @Document(collection = "chat") 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | public class Chat { 18 | // @Id 19 | // private String id; 20 | 21 | private MessageType type; 22 | 23 | private String nickname; 24 | 25 | private String email; 26 | 27 | private String roomCode; 28 | 29 | private String message; 30 | 31 | // @CreatedDate 32 | private String createdAt; 33 | 34 | private String imageUrl; 35 | 36 | private Chat(MessageType type, String nickname, String email, String roomCode, String message) { 37 | this.type = type; 38 | this.nickname = nickname; 39 | this.email = email; 40 | this.roomCode = roomCode; 41 | this.message = message; 42 | } 43 | 44 | public static Chat of(MessageType type, String nickname, String email, String roomCode, String message) { 45 | return new Chat(type, nickname, email, roomCode, message); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/com/challenge/chat/config/JasyptConfigTest.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat.config; 2 | // 3 | // import static org.assertj.core.api.Assertions.*; 4 | // 5 | // import org.jasypt.encryption.StringEncryptor; 6 | // import org.junit.jupiter.api.DisplayName; 7 | // import org.junit.jupiter.api.Test; 8 | // import org.springframework.beans.factory.annotation.Autowired; 9 | // import org.springframework.beans.factory.annotation.Qualifier; 10 | // import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 11 | // import org.springframework.boot.test.mock.mockito.MockBean; 12 | // import org.springframework.data.jpa.mapping.JpaMetamodelMappingContext; 13 | // 14 | // @WebMvcTest(JasyptConfig.class) 15 | // @MockBean(JpaMetamodelMappingContext.class) 16 | // class JasyptConfigTest { 17 | // 18 | // @Autowired 19 | // @Qualifier("jasyptStringEncryptor") 20 | // StringEncryptor encryptor; 21 | // 22 | // @Test 23 | // @DisplayName("Jasypt 암복호화 테스트") 24 | // public void jasyptEncryptDecryptTest() { 25 | // String plainText = "TestText"; 26 | // 27 | // String encryptedText = encryptor.encrypt(plainText); 28 | // String decryptedText = encryptor.decrypt(encryptedText); 29 | // 30 | // assertThat(plainText).isEqualTo(decryptedText); 31 | // } 32 | // } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/oauth/dto/CustomOAuth2User.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.oauth.dto; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.oauth2.core.user.DefaultOAuth2User; 8 | 9 | import com.challenge.chat.domain.member.constant.MemberRole; 10 | 11 | import lombok.Getter; 12 | 13 | /** 14 | * DefaultOAuth2User를 상속하고, email과 role 필드를 추가로 가진다. 15 | */ 16 | @Getter 17 | public class CustomOAuth2User extends DefaultOAuth2User { 18 | 19 | private String email; 20 | private MemberRole role; 21 | 22 | /** 23 | * Constructs a {@code DefaultOAuth2User} using the provided parameters. 24 | * 25 | * @param authorities the authorities granted to the user 26 | * @param attributes the attributes about the user 27 | * @param nameAttributeKey the key used to access the user's "name" from 28 | * {@link #getAttributes()} 29 | */ 30 | public CustomOAuth2User(Collection authorities, 31 | Map attributes, String nameAttributeKey, String email, MemberRole role) { 32 | 33 | super(authorities, attributes, nameAttributeKey); 34 | this.email = email; 35 | this.role = role; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | activate: 4 | on-profile: dev 5 | datasource: 6 | hikari: 7 | connection-timeout: 60000 8 | url: ENC(AtbAmjmXqguvVjtmxT14rzHAGZXtPCNJJ/VUUG7ajPBIGeY/tCv9Dht1wHSnTu4xRD1qFg0jI2J3+4Kky0ZeXYY7CmzGw8RI9/VJuDR4vReoyTkWgVtqEVbd0v2EJNiQRbK+XW1vy3hdZ3wluhgFU7SZZCsAjwM+u2v5S76msntjxsDpjHU7qdrShxqjX3H67+0X59IZjqjr6HPMRjFYhQ==) 9 | username: ENC(nZEFzHuwF4wasrpbc2TcJQ==) 10 | password: ENC(mJyIfhz6z46U9Q4Exy4LQamYMyEBiJiG) 11 | driver-class-name: com.mysql.cj.jdbc.Driver 12 | data: 13 | mongodb: 14 | uri: mongodb+srv://admin:chat1122@thiscode.cpaiaoh.mongodb.net/thiscode?retryWrites=true&w=majority 15 | auto-index-creation: true 16 | jpa: 17 | properties: 18 | hibernate: 19 | show_sql: false 20 | format_sql: false 21 | hbm2ddl: 22 | auto: update 23 | # rabbitmq: 24 | # host: rabbitMQ 25 | # port: 5672 26 | # username: guest 27 | # password: guest 28 | 29 | application: 30 | name: monitoring 31 | 32 | management: 33 | endpoint: 34 | metrics: 35 | enabled: true 36 | prometheus: 37 | enabled: true 38 | 39 | endpoints: 40 | web: 41 | exposure: 42 | include: health, info, metrics, prometheus 43 | 44 | metrics: 45 | tags: 46 | application: ${spring.application.name} 47 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/config/JasyptConfig.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.config; 2 | 3 | import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties; 4 | import org.jasypt.encryption.StringEncryptor; 5 | import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; 6 | import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration 12 | @EnableEncryptableProperties 13 | public class JasyptConfig { 14 | 15 | @Value("${jasypt.password}") 16 | private String password; 17 | 18 | @Bean("jasyptStringEncryptor") 19 | public StringEncryptor stringEncryptor() { 20 | PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); 21 | SimpleStringPBEConfig config = new SimpleStringPBEConfig(); 22 | config.setPassword(password); 23 | config.setAlgorithm("PBEWithMD5AndDES"); 24 | config.setKeyObtentionIterations("1000"); 25 | config.setPoolSize("1"); 26 | config.setProviderName("SunJCE"); 27 | config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); 28 | config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator"); 29 | config.setStringOutputType("base64"); 30 | encryptor.setConfig(config); 31 | return encryptor; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/config/WebSocketConfig.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.messaging.simp.config.MessageBrokerRegistry; 5 | import org.springframework.util.AntPathMatcher; 6 | import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; 7 | import org.springframework.web.socket.config.annotation.StompEndpointRegistry; 8 | import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; 9 | 10 | @Configuration 11 | @EnableWebSocketMessageBroker 12 | public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 13 | 14 | @Override 15 | public void configureMessageBroker(MessageBrokerRegistry config) { 16 | // config.setPathMatcher(new AntPathMatcher(".")); // url을 chat/room/3 -> chat.room.3으로 참조하기 위한 설정 17 | config.enableSimpleBroker("/queue", "/topic"); 18 | // config.enableStompBrokerRelay("/queue", "/topic", "/exchange", "/amq/queue") 19 | // .setRelayHost("rabbitMQ") 20 | // .setClientLogin("guest") 21 | // .setClientPasscode("guest"); 22 | config.setApplicationDestinationPrefixes("/app"); 23 | } 24 | 25 | @Override 26 | public void registerStompEndpoints(StompEndpointRegistry registry) { 27 | registry.addEndpoint("/ws-chat") 28 | .setAllowedOriginPatterns("*").withSockJS(); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/config/MongoConfig.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.data.mongodb.MongoDatabaseFactory; 7 | import org.springframework.data.mongodb.core.convert.DbRefResolver; 8 | import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; 9 | import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper; 10 | import org.springframework.data.mongodb.core.convert.MappingMongoConverter; 11 | import org.springframework.data.mongodb.core.mapping.MongoMappingContext; 12 | 13 | @Configuration 14 | public class MongoConfig { 15 | // MongoDB 에 "_class" 들어가지 않게 설정 16 | @Autowired 17 | private MongoMappingContext mongoMappingContext; 18 | 19 | @Bean 20 | public MappingMongoConverter mappingMongoConverter( 21 | MongoDatabaseFactory mongoDatabaseFactory, 22 | MongoMappingContext mongoMappingContext 23 | ) { 24 | DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory); 25 | MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext); 26 | converter.setTypeMapper(new DefaultMongoTypeMapper(null)); 27 | return converter; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/login/service/LoginService.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.login.service; 2 | 3 | import org.springframework.security.core.userdetails.UserDetails; 4 | import org.springframework.security.core.userdetails.UserDetailsService; 5 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 6 | import org.springframework.stereotype.Service; 7 | 8 | import com.challenge.chat.domain.member.entity.Member; 9 | import com.challenge.chat.domain.member.repository.MemberRepository; 10 | import com.challenge.chat.exception.RestApiException; 11 | import com.challenge.chat.exception.dto.MemberErrorCode; 12 | 13 | import lombok.RequiredArgsConstructor; 14 | import lombok.extern.slf4j.Slf4j; 15 | 16 | @Slf4j 17 | @Service 18 | @RequiredArgsConstructor 19 | public class LoginService implements UserDetailsService { 20 | 21 | private final MemberRepository memberRepository; 22 | 23 | @Override 24 | public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { 25 | Member member = memberRepository.findByEmail(email) 26 | .orElseThrow(() -> new RestApiException(MemberErrorCode.MEMBER_NOT_FOUND)); 27 | 28 | log.info("일반 로그인 서비스 로직입니다."); 29 | return org.springframework.security.core.userdetails.User.builder() 30 | .username(member.getEmail()) 31 | .password(member.getPassword()) 32 | .roles(member.getRole().name()) 33 | .build(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/entity/Member.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.entity; 2 | 3 | import java.util.List; 4 | 5 | import com.challenge.chat.domain.chat.entity.MemberChatRoom; 6 | import com.challenge.chat.domain.member.constant.MemberRole; 7 | import com.challenge.chat.domain.member.constant.SocialType; 8 | import lombok.*; 9 | 10 | import javax.persistence.CascadeType; 11 | import javax.persistence.Column; 12 | import javax.persistence.Entity; 13 | import javax.persistence.EnumType; 14 | import javax.persistence.Enumerated; 15 | import javax.persistence.GeneratedValue; 16 | import javax.persistence.GenerationType; 17 | import javax.persistence.Id; 18 | import javax.persistence.OneToMany; 19 | 20 | @Entity 21 | @Getter 22 | @NoArgsConstructor 23 | @Builder 24 | @AllArgsConstructor 25 | public class Member { 26 | 27 | @Id 28 | @GeneratedValue(strategy = GenerationType.IDENTITY) 29 | @Column(name = "MEMBER_ID") 30 | private Long id; 31 | 32 | private String email; // 이메일 33 | private String password; // 비밀번호 34 | private String nickname; // 닉네임 35 | private String imageUrl; // 프로필 이미지 36 | 37 | @Enumerated(EnumType.STRING) 38 | private MemberRole role; 39 | 40 | @Enumerated(EnumType.STRING) 41 | private SocialType socialType; // KAKAO, NAVER, GOOGLE 42 | 43 | private String socialId; // 로그인한 소셜 타입의 식별자 값 (일반 로그인인 경우 null) 44 | 45 | private String refreshToken; // 리프레시 토큰 46 | 47 | @OneToMany(mappedBy = "member", orphanRemoval = true, cascade = CascadeType.ALL) 48 | private List roomList; 49 | 50 | @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) 51 | private List friendList; 52 | 53 | public void updateRefreshToken(String updateRefreshToken) { 54 | this.refreshToken = updateRefreshToken; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/dto/ChatDto.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.dto; 2 | 3 | import com.challenge.chat.domain.chat.entity.Chat; 4 | import com.challenge.chat.domain.chat.entity.MessageType; 5 | import lombok.*; 6 | 7 | import java.time.Instant; 8 | 9 | @Getter 10 | @Setter 11 | @Builder 12 | @AllArgsConstructor 13 | @NoArgsConstructor 14 | public class ChatDto { 15 | 16 | private MessageType type; 17 | private String nickname; 18 | private String email; 19 | private String roomCode; 20 | private String message; 21 | private Instant createdAt; 22 | private String imageUrl; 23 | 24 | public static ChatDto from(Chat chat) { 25 | 26 | Instant instant; 27 | if (chat.getCreatedAt() == null) { 28 | instant = null; 29 | } else { 30 | double timestampValue = Double.parseDouble(chat.getCreatedAt()); 31 | long epochSeconds = (long) timestampValue; 32 | instant = Instant.ofEpochSecond( 33 | epochSeconds, 34 | (int) ((timestampValue - epochSeconds) * 1_000_000_000)); 35 | } 36 | 37 | return new ChatDto( 38 | chat.getType(), 39 | chat.getNickname(), 40 | chat.getEmail(), 41 | chat.getRoomCode(), 42 | chat.getMessage(), 43 | instant, 44 | chat.getImageUrl() 45 | ); 46 | } 47 | 48 | public static Chat toEntity(ChatDto chatDto) { 49 | return Chat.of( 50 | chatDto.getType(), 51 | chatDto.getNickname(), 52 | chatDto.getEmail(), 53 | chatDto.getRoomCode(), 54 | chatDto.getMessage() 55 | ); 56 | } 57 | 58 | // public static ChatDto from(ChatES chat) { 59 | // return new ChatDto( 60 | // chat.getType(), 61 | // chat.getNickname(), 62 | // chat.getEmail(), 63 | // chat.getRoomCode(), 64 | // chat.getMessage(), 65 | // Instant.ofEpochMilli(chat.getCreatedAt()), 66 | // chat.getImageUrl() 67 | // ); 68 | // } 69 | } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/entity/ChatES.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat.domain.chat.entity; 2 | // 3 | // import java.time.Instant; 4 | // 5 | // import javax.persistence.Id; 6 | // 7 | // import org.springframework.data.elasticsearch.annotations.DateFormat; 8 | // import org.springframework.data.elasticsearch.annotations.Document; 9 | // import org.springframework.data.elasticsearch.annotations.Field; 10 | // import org.springframework.data.elasticsearch.annotations.FieldType; 11 | // import org.springframework.data.elasticsearch.annotations.Mapping; 12 | // import org.springframework.data.elasticsearch.annotations.Setting; 13 | // 14 | // import lombok.AccessLevel; 15 | // import lombok.Builder; 16 | // import lombok.Getter; 17 | // import lombok.NoArgsConstructor; 18 | // 19 | // @Mapping(mappingPath = "elastic/chat-mapping.json") 20 | // @Setting(settingPath = "elastic/chat-setting.json") 21 | // @NoArgsConstructor(access = AccessLevel.PROTECTED) 22 | // @Getter 23 | // @Document(indexName = "kafka-chat") 24 | // public class ChatES { 25 | // 26 | // @Id 27 | // private String id; 28 | // 29 | // private MessageType type; 30 | // 31 | // private String nickname; 32 | // 33 | // private String email; 34 | // 35 | // private String roomCode; 36 | // 37 | // private String message; 38 | // 39 | // @Field(type = FieldType.Date, format = {DateFormat.date_hour_minute_second_millis, DateFormat.epoch_millis}) 40 | // private long createdAt; 41 | // 42 | // private String imageUrl; 43 | // 44 | // 45 | // // @Builder 46 | // // public ChatES(String id, MessageType type, String nickname, String email, String roomCode, String message, 47 | // // Instant createdAt) { 48 | // // this.id = id; 49 | // // this.type = type; 50 | // // this.nickname = nickname; 51 | // // this.email = email; 52 | // // this.roomCode = roomCode; 53 | // // this.message = message; 54 | // // this.createdAt = createdAt; 55 | // // } 56 | // } -------------------------------------------------------------------------------- /HELP.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ### Reference Documentation 4 | For further reference, please consider the following sections: 5 | 6 | * [Official Gradle documentation](https://docs.gradle.org) 7 | * [Spring Boot Gradle Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/3.0.7/gradle-plugin/reference/html/) 8 | * [Create an OCI image](https://docs.spring.io/spring-boot/docs/3.0.7/gradle-plugin/reference/html/#build-image) 9 | * [Spring Web](https://docs.spring.io/spring-boot/docs/3.0.7/reference/htmlsingle/#web) 10 | * [Spring Security](https://docs.spring.io/spring-boot/docs/3.0.7/reference/htmlsingle/#web.security) 11 | * [Spring Data JPA](https://docs.spring.io/spring-boot/docs/3.0.7/reference/htmlsingle/#data.sql.jpa-and-spring-data) 12 | * [OAuth2 Client](https://docs.spring.io/spring-boot/docs/3.0.7/reference/htmlsingle/#web.security.oauth2.client) 13 | * [WebSocket](https://docs.spring.io/spring-boot/docs/3.0.7/reference/htmlsingle/#messaging.websockets) 14 | 15 | ### Guides 16 | The following guides illustrate how to use some features concretely: 17 | 18 | * [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) 19 | * [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) 20 | * [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) 21 | * [Securing a Web Application](https://spring.io/guides/gs/securing-web/) 22 | * [Spring Boot and OAuth2](https://spring.io/guides/tutorials/spring-boot-oauth2/) 23 | * [Authenticating a User with LDAP](https://spring.io/guides/gs/authenticating-ldap/) 24 | * [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) 25 | * [Using WebSocket to build an interactive web application](https://spring.io/guides/gs/messaging-stomp-websocket/) 26 | 27 | ### Additional Links 28 | These additional references should also help you: 29 | 30 | * [Gradle Build Scans – insights for your project's build](https://scans.gradle.com#gradle) 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/controller/MemberController.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.controller; 2 | 3 | import com.challenge.chat.domain.member.dto.MemberDto; 4 | import com.challenge.chat.domain.member.dto.request.SignupRequest; 5 | import com.challenge.chat.domain.member.dto.request.MemberAddRequest; 6 | import com.challenge.chat.domain.member.service.MemberService; 7 | 8 | import lombok.RequiredArgsConstructor; 9 | import lombok.extern.slf4j.Slf4j; 10 | 11 | import org.springframework.http.HttpStatus; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 14 | import org.springframework.security.core.userdetails.User; 15 | import org.springframework.web.bind.annotation.GetMapping; 16 | import org.springframework.web.bind.annotation.PostMapping; 17 | import org.springframework.web.bind.annotation.RequestBody; 18 | import org.springframework.web.bind.annotation.RestController; 19 | 20 | import java.util.List; 21 | 22 | import javax.validation.Valid; 23 | 24 | @RestController 25 | @Slf4j 26 | @RequiredArgsConstructor 27 | public class MemberController { 28 | 29 | private final MemberService memberService; 30 | 31 | @PostMapping("/users/signup") 32 | public ResponseEntity signup(@RequestBody @Valid final SignupRequest signupRequest) { 33 | memberService.signup(signupRequest); 34 | return ResponseEntity.status(HttpStatus.OK).body("회원가입 성공"); 35 | } 36 | 37 | @PostMapping("/users/friend") 38 | public ResponseEntity addFriend( 39 | @AuthenticationPrincipal final User user, 40 | @RequestBody @Valid final MemberAddRequest memberAddRequest) { 41 | memberService.addFriend(user.getUsername(), memberAddRequest.getEmail()); 42 | return ResponseEntity.status(HttpStatus.OK).body("친구추가 성공"); 43 | } 44 | 45 | 46 | @GetMapping("/users/friend") 47 | public ResponseEntity> getFriendList(@AuthenticationPrincipal final User user) { 48 | return ResponseEntity.status(HttpStatus.OK) 49 | .body(memberService.searchFriendList(user.getUsername())); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/config/ProducerConfig.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.config; 2 | 3 | import com.challenge.chat.domain.chat.constant.KafkaConstants; 4 | import com.challenge.chat.domain.chat.dto.ChatDto; 5 | import com.challenge.chat.domain.chat.entity.Chat; 6 | 7 | import org.apache.kafka.common.serialization.StringSerializer; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.kafka.annotation.EnableKafka; 11 | import org.springframework.kafka.core.DefaultKafkaProducerFactory; 12 | import org.springframework.kafka.core.KafkaTemplate; 13 | import org.springframework.kafka.core.ProducerFactory; 14 | import org.springframework.kafka.support.serializer.JsonSerializer; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | @EnableKafka 20 | @Configuration 21 | public class ProducerConfig { 22 | /** 23 | * producer는 TOPIC에 메시지를 작성 24 | * KafkaTemplate을 통해 TOPIC에 메시지를 보낼 수 있음 25 | * BOOTSTRAP_SERVERS_CONFIG는 Kafka가 실행되는 주소를 설정 26 | * KEY_SERIALIZER_CLASS_CONFIG와 VALUE_SERIALIZER_CLASS_CONFIG는 Kafka로 보내는 데이터의 키와 값을 직렬화함 27 | * 문자열을 넘길땐 StringSerializer.class를, JSON 데이터를 넘길 땐 JsonSerializer.class를 적어주면 됨 28 | * properties나 yaml으로 설정할 수도 있고, 아래처럼 @Bean으로 설정해줄 수도 있음 29 | */ 30 | @Bean 31 | public ProducerFactory producerFactory() { 32 | return new DefaultKafkaProducerFactory<>(producerConfigurations()); 33 | } 34 | 35 | @Bean 36 | public Map producerConfigurations() { 37 | Map configurations = new HashMap<>(); 38 | configurations.put(org.apache.kafka.clients.producer.ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KafkaConstants.KAFKA_BROKER); 39 | configurations.put(org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); 40 | configurations.put(org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); 41 | return configurations; 42 | } 43 | 44 | @Bean 45 | public KafkaTemplate kafkaTemplate() { 46 | return new KafkaTemplate<>(producerFactory()); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/login/handler/LoginSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.login.handler; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.security.core.Authentication; 8 | import org.springframework.security.core.userdetails.UserDetails; 9 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; 10 | 11 | import com.challenge.chat.domain.member.repository.MemberRepository; 12 | import com.challenge.chat.security.jwt.service.JwtService; 13 | 14 | import lombok.RequiredArgsConstructor; 15 | import lombok.extern.slf4j.Slf4j; 16 | 17 | @Slf4j 18 | @RequiredArgsConstructor 19 | public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { 20 | 21 | private final JwtService jwtService; 22 | private final MemberRepository memberRepository; 23 | 24 | @Value("${jwt.access.expiration}") 25 | private String accessTokenExpiration; 26 | 27 | @Override 28 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, 29 | Authentication authentication) { 30 | String email = extractUsername(authentication); // 인증 정보에서 Username(email) 추출 31 | String accessToken = jwtService.createAccessToken(email); // JwtService의 createAccessToken을 사용하여 AccessToken 발급 32 | String refreshToken = jwtService.createRefreshToken(); // JwtService의 createRefreshToken을 사용하여 RefreshToken 발급 33 | 34 | jwtService.sendAccessAndRefreshToken(response, accessToken, refreshToken); // 응답 헤더에 AccessToken, RefreshToken 실어서 응답 35 | 36 | // memberRepository.findByEmail(email) 37 | // .ifPresent(user -> { 38 | // user.updateRefreshToken(refreshToken); 39 | // memberRepository.save(user); 40 | // }); 41 | log.info("로그인에 성공하였습니다. 이메일 : {}", email); 42 | log.info("로그인에 성공하였습니다. AccessToken : {}", accessToken); 43 | log.info("로그인에 성공하였습니다. RefreshToken : {}", refreshToken); 44 | log.info("발급된 AccessToken 만료 기간 : {}", accessTokenExpiration); 45 | } 46 | 47 | private String extractUsername(Authentication authentication) { 48 | UserDetails userDetails = (UserDetails) authentication.getPrincipal(); 49 | return userDetails.getUsername(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/oauth/dto/OAuthAttributes.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.oauth.dto; 2 | 3 | import com.challenge.chat.domain.member.constant.MemberRole; 4 | import com.challenge.chat.domain.member.constant.SocialType; 5 | import com.challenge.chat.domain.member.entity.Member; 6 | import com.challenge.chat.security.jwt.util.PasswordUtil; 7 | import lombok.Builder; 8 | import lombok.Getter; 9 | 10 | import java.util.Map; 11 | import java.util.UUID; 12 | 13 | /** 14 | * 각 소셜에서 받아오는 데이터가 다르므로 15 | * 소셜별로 데이터를 받는 데이터를 분기 처리하는 DTO 클래스 16 | */ 17 | @Getter 18 | public class OAuthAttributes { 19 | 20 | private String nameAttributeKey; // OAuth2 로그인 진행 시 키가 되는 필드 값, PK와 같은 의미 21 | private OAuth2UserInfo oauth2UserInfo; // 소셜 타입별 로그인 유저 정보(닉네임, 이메일, 프로필 사진 등등) 22 | private PasswordUtil passwordUtil; 23 | 24 | @Builder 25 | public OAuthAttributes(String nameAttributeKey, OAuth2UserInfo oauth2UserInfo) { 26 | this.nameAttributeKey = nameAttributeKey; 27 | this.oauth2UserInfo = oauth2UserInfo; 28 | } 29 | 30 | /** 31 | * SocialType에 맞는 메소드 호출하여 OAuthAttributes 객체 반환 32 | * 파라미터 : userNameAttributeName -> OAuth2 로그인 시 키(PK)가 되는 값 / attributes : OAuth 서비스의 유저 정보들 33 | * 소셜별 of 메소드(ofGoogle, ofKaKao, ofNaver)들은 각각 소셜 로그인 API에서 제공하는 34 | * 회원의 식별값(id), attributes, nameAttributeKey를 저장 후 build 35 | */ 36 | public static OAuthAttributes of(SocialType socialType, 37 | String userNameAttributeName, Map attributes) { 38 | 39 | return ofGoogle(userNameAttributeName, attributes); 40 | } 41 | 42 | public static OAuthAttributes ofGoogle(String userNameAttributeName, Map attributes) { 43 | return OAuthAttributes.builder() 44 | .nameAttributeKey(userNameAttributeName) 45 | .oauth2UserInfo(new GoogleOAuth2UserInfo(attributes)) 46 | .build(); 47 | } 48 | 49 | /** 50 | * of메소드로 OAuthAttributes 객체가 생성되어, 유저 정보들이 담긴 OAuth2UserInfo가 소셜 타입별로 주입된 상태 51 | * OAuth2UserInfo에서 socialId(식별값), nickname, imageUrl을 가져와서 build 52 | * email에는 UUID로 중복 없는 랜덤 값 생성 53 | * role은 GUEST로 설정 54 | */ 55 | public Member toEntity(SocialType socialType, OAuth2UserInfo oauth2UserInfo) { 56 | return Member.builder() 57 | .socialType(socialType) 58 | .socialId(oauth2UserInfo.getId()) 59 | .email(oauth2UserInfo.getEmail()) 60 | .nickname(oauth2UserInfo.getNickname()) 61 | .imageUrl(oauth2UserInfo.getImageUrl()) 62 | .role(MemberRole.GUEST) 63 | .password(passwordUtil.generateRandomPassword()) 64 | .build(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.exception; 2 | 3 | import com.challenge.chat.exception.dto.CommonErrorCode; 4 | import com.challenge.chat.exception.dto.ErrorCode; 5 | import com.challenge.chat.exception.dto.ErrorResponse; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.ExceptionHandler; 9 | import org.springframework.web.bind.annotation.RestControllerAdvice; 10 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 11 | 12 | @Slf4j 13 | @RestControllerAdvice 14 | public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { 15 | 16 | @ExceptionHandler({RestApiException.class}) 17 | public ResponseEntity handleRestApiException(final RestApiException exception) { 18 | 19 | log.warn("RestApiException occur: ", exception); 20 | 21 | return this.makeErrorResponseEntity(exception.getErrorCode()); 22 | } 23 | 24 | @ExceptionHandler({Exception.class}) 25 | public ResponseEntity handleException(final RestApiException exception) { 26 | 27 | log.warn("Exception occur: ", exception); 28 | 29 | return this.makeErrorResponseEntity(CommonErrorCode.INTERNAL_SERVER_ERROR); 30 | } 31 | 32 | // @Override 33 | // protected ResponseEntity handleMethodArgumentNotValid( 34 | // MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { 35 | // 36 | // final List errorList = ex.getBindingResult() 37 | // .getAllErrors() 38 | // .stream() 39 | // .map(DefaultMessageSourceResolvable::getDefaultMessage) 40 | // .collect(Collectors.toList()); 41 | // 42 | // log.warn("Invalid Request Parameter errors : {}", errorList); 43 | // 44 | // return this.makeErrorResponseEntity(errorList.toString(), CommonErrorCode.INVALID_REQUEST_PARAMETER); 45 | // } 46 | 47 | private ResponseEntity makeErrorResponseEntity(final ErrorCode errorCode) { 48 | 49 | return ResponseEntity 50 | .status(errorCode.getHttpStatus()) 51 | .body(new ErrorResponse(errorCode.name(), errorCode.getHttpStatus().toString(), errorCode.getMessage())); 52 | } 53 | 54 | // private ResponseEntity makeErrorResponseEntity(final String errorDescription, final ErrorCode errorCode) { 55 | // 56 | // return ResponseEntity 57 | // .status(errorCode.getHttpStatus()) 58 | // .body(new ErrorResponse(errorCode.name(), errorCode.getHttpStatus().toString(), errorDescription)); 59 | // } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/config/ConsumerConfig.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.config; 2 | 3 | import com.challenge.chat.domain.chat.constant.KafkaConstants; 4 | import com.challenge.chat.domain.chat.dto.ChatDto; 5 | 6 | import org.apache.kafka.common.serialization.StringDeserializer; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.kafka.annotation.EnableKafka; 10 | import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; 11 | import org.springframework.kafka.core.ConsumerFactory; 12 | import org.springframework.kafka.core.DefaultKafkaConsumerFactory; 13 | import org.springframework.kafka.support.serializer.JsonDeserializer; 14 | 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | 18 | @EnableKafka 19 | @Configuration 20 | public class ConsumerConfig { 21 | /** 22 | * listener(consumer)는 Kafka로부터 메시지를 받는 곳 23 | * GROUP_ID_CONFIG는 consumer group id를 설정 24 | * KEY_DESERIALIZER_CLASS_CONFIG와 VALUE_DESERIALIZER_CLASS_CONFIG는 Kafka에서 받은 데이터의 키와 값을 역직렬화함 25 | * AUTO_OFFSET_RESET_CONFIG에는 latest(가장 최근에 생성된 메시지를 offset reset), earliest(가장 오래된 메시지를), none의 값을 입력할 수 있음 26 | */ 27 | @Bean 28 | ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { 29 | ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); 30 | factory.setConsumerFactory(consumerFactory()); 31 | return factory; 32 | } 33 | 34 | @Bean 35 | public ConsumerFactory consumerFactory() { 36 | return new DefaultKafkaConsumerFactory<>(consumerConfigurations(), new StringDeserializer(), new JsonDeserializer<>(ChatDto.class)); 37 | } 38 | 39 | @Bean 40 | public Map consumerConfigurations() { 41 | Map configurations = new HashMap<>(); 42 | configurations.put(org.apache.kafka.clients.consumer.ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KafkaConstants.KAFKA_BROKER); 43 | configurations.put(org.apache.kafka.clients.consumer.ConsumerConfig.GROUP_ID_CONFIG, KafkaConstants.GROUP_ID); 44 | configurations.put(org.apache.kafka.clients.consumer.ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 45 | configurations.put(org.apache.kafka.clients.consumer.ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); 46 | configurations.put(org.apache.kafka.clients.consumer.ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); 47 | return configurations; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Build and Deploy Spring Boot to AWS EC2 2 | 3 | # main 브랜치에 푸쉬 했을때 4 | on: 5 | push: 6 | branches: [ dev ] 7 | 8 | # 해당 코드에서 사용될 변수 설정 9 | env: 10 | PROJECT_NAME: chatchallenge 11 | BUCKET_NAME: chatchallengebucket 12 | CODE_DEPLOY_APP_NAME: codeDeploy-test 13 | DEPLOYMENT_GROUP_NAME: codeDeploy-group 14 | # DOCKER_USERNAME: ${{secrets.DOCKER_USERNAME}} 15 | # DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}} 16 | 17 | permissions: write-all 18 | 19 | jobs: 20 | build-with-gradle: 21 | runs-on: ubuntu-20.04 22 | steps: 23 | - name: main 브랜치로 이동 24 | uses: actions/checkout@v3 25 | 26 | - name: JDK 17 설치 27 | uses: actions/setup-java@v3 28 | with: 29 | java-version: '17' 30 | distribution: 'temurin' 31 | 32 | - name: Jasypt 키 주입 33 | run: | 34 | echo ${{secrets.JASYPT}} | base64 --decode >> ./src/main/resources/application-common.yml 35 | echo ${{secrets.JASYPT}} | base64 --decode >> ./src/test/resources/application-common.yml 36 | 37 | # - name: Docker 계정 환경변수로 등록하기 38 | # run: | 39 | # export $DOCKER_USERNAME 40 | # export $DOCKER_PASSWORD 41 | 42 | - name: gradlew에 실행 권한 부여 43 | run: chmod +x ./gradlew 44 | 45 | - name: 프로젝트 빌드 46 | run: ./gradlew clean build 47 | 48 | # 프로젝트 압축 49 | - name: Make zip file 50 | run: zip -r ./chatchallenge.zip . 51 | shell: bash 52 | 53 | - name: 테스트 결과를 PR에 코멘트로 등록합니다 54 | uses: EnricoMi/publish-unit-test-result-action@v1 55 | if: always() 56 | with: 57 | files: '**/build/test-results/test/TEST-*.xml' 58 | 59 | - name: 테스트 실패 시, 실패한 코드 라인에 Check 코멘트를 등록합니다 60 | uses: mikepenz/action-junit-report@v3 61 | if: always() 62 | with: 63 | report_paths: '**/build/test-results/test/TEST-*.xml' 64 | 65 | # AWS 권한 확인 66 | - name: Configure AWS credentials 67 | uses: aws-actions/configure-aws-credentials@v1 68 | with: 69 | aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} 70 | aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 71 | aws-region: ${{ secrets.AWS_REGION }} 72 | 73 | # 압축한 프로젝트를 S3로 전송 74 | - name: Upload to S3 75 | run: aws s3 cp --region ap-northeast-2 ./chatchallenge.zip s3://chatchallengebucket/chatchallenge.zip 76 | 77 | # Send application to deployment group 78 | - name: Code Deploy 79 | run: aws deploy create-deployment --application-name $CODE_DEPLOY_APP_NAME --deployment-config-name CodeDeployDefault.AllAtOnce --deployment-group-name $DEPLOYMENT_GROUP_NAME --s3-location bucket=$BUCKET_NAME,bundleType=zip,key=chatchallenge.zip 80 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/member/service/MemberService.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.member.service; 2 | 3 | import com.challenge.chat.domain.member.constant.MemberRole; 4 | import com.challenge.chat.domain.member.dto.MemberDto; 5 | import com.challenge.chat.domain.member.dto.request.SignupRequest; 6 | import com.challenge.chat.domain.member.entity.Member; 7 | import com.challenge.chat.domain.member.entity.MemberFriend; 8 | import com.challenge.chat.domain.member.repository.MemberFriendRepository; 9 | import com.challenge.chat.domain.member.repository.MemberRepository; 10 | 11 | import com.challenge.chat.exception.RestApiException; 12 | import com.challenge.chat.exception.dto.MemberErrorCode; 13 | 14 | import lombok.RequiredArgsConstructor; 15 | import lombok.extern.slf4j.Slf4j; 16 | 17 | import org.springframework.security.crypto.password.PasswordEncoder; 18 | import org.springframework.stereotype.Service; 19 | import org.springframework.transaction.annotation.Transactional; 20 | 21 | import java.util.List; 22 | import java.util.stream.Collectors; 23 | 24 | 25 | @Service 26 | @RequiredArgsConstructor 27 | @Transactional 28 | @Slf4j 29 | public class MemberService { 30 | 31 | private final MemberRepository memberRepository; 32 | private final MemberFriendRepository memberFriendRepository; 33 | private final PasswordEncoder passwordEncoder; 34 | 35 | public void addFriend(final String memberEmail, final String friendEmail) { 36 | 37 | Member member = findMemberByEmail(memberEmail); 38 | Member friend = findMemberByEmail(friendEmail); 39 | 40 | if (memberFriendRepository.findByMemberAndFriend(member, friend).isPresent()) { 41 | throw new RestApiException(MemberErrorCode.ADDED_FRIEND); 42 | } 43 | memberFriendRepository.save(MemberFriend.of(member, friend)); 44 | } 45 | 46 | @Transactional(readOnly = true) 47 | public List searchFriendList(final String memberEmail) { 48 | 49 | Member member = findMemberByEmail(memberEmail); 50 | 51 | return member.getFriendList() 52 | .stream() 53 | .map(a -> MemberDto.from(a.getFriend())) 54 | .collect(Collectors.toList()); 55 | } 56 | 57 | public void signup(final SignupRequest signupRequest) { 58 | 59 | if (memberRepository.findByEmail(signupRequest.getEmail()).isPresent()) { 60 | throw new RestApiException(MemberErrorCode.DUPLICATED_EMAIL); 61 | } 62 | 63 | Member member = Member.builder() 64 | .email(signupRequest.getEmail()) 65 | .password(passwordEncoder.encode(signupRequest.getPassword())) 66 | .nickname(signupRequest.getNickname()) 67 | .role(MemberRole.USER) 68 | .build(); 69 | 70 | memberRepository.save(member); 71 | } 72 | 73 | public Member findMemberByEmail(String email) { 74 | return memberRepository.findByEmail(email).orElseThrow( 75 | () -> new RestApiException(MemberErrorCode.MEMBER_NOT_FOUND)); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/oauth/handler/OAuth2LoginSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.oauth.handler; 2 | 3 | import java.io.IOException; 4 | import java.net.URLEncoder; 5 | 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.security.core.Authentication; 11 | import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 12 | import org.springframework.stereotype.Component; 13 | 14 | import com.challenge.chat.domain.member.repository.MemberRepository; 15 | import com.challenge.chat.security.jwt.service.JwtService; 16 | import com.challenge.chat.security.oauth.dto.CustomOAuth2User; 17 | 18 | import lombok.RequiredArgsConstructor; 19 | import lombok.extern.slf4j.Slf4j; 20 | 21 | @Slf4j 22 | @Component 23 | @RequiredArgsConstructor 24 | public class OAuth2LoginSuccessHandler implements AuthenticationSuccessHandler { 25 | 26 | private final JwtService jwtService; 27 | private final MemberRepository memberRepository; 28 | 29 | @Override 30 | public void onAuthenticationSuccess( 31 | HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, 32 | ServletException { 33 | log.info("OAuth2 Login 성공!"); 34 | try { 35 | CustomOAuth2User oAuth2User = (CustomOAuth2User)authentication.getPrincipal(); 36 | 37 | // User의 Role이 GUEST일 경우 처음 요청한 회원이므로 회원가입 페이지로 리다이렉트 38 | // if(oAuth2User.getRole() == MemberRole.GUEST) { 39 | // String accessToken = jwtService.createAccessToken(oAuth2User.getEmail()); 40 | // response.addHeader(jwtService.getAccessHeader(), "Bearer " + accessToken); 41 | // response.addCookie(new Cookie(jwtService.getAccessHeader(), 42 | // URLEncoder.encode("Bearer " + accessToken, "utf-8").replaceAll("\\+", "%20"))); 43 | 44 | // response.sendRedirect("oauth2/sign-up"); // 프론트의 회원가입 추가 정보 입력 폼으로 리다이렉트 45 | 46 | // jwtService.sendAccessAndRefreshToken(response, accessToken, null); 47 | // 48 | // // User의 Role을 USER로 전환 49 | // Member findUser = memberRepository.findByEmail(oAuth2User.getEmail()) 50 | // .orElseThrow(() -> new IllegalArgumentException("이메일에 해당하는 유저가 없습니다.")); 51 | // findUser.authorizeUser(); 52 | // log.info("이메일에 해당하는 유저를 db에서 찾았습니다!" + findUser.getRole()); 53 | // } else { 54 | loginSuccess(response, oAuth2User); // 로그인에 성공한 경우 access, refresh 토큰 생성 55 | // } 56 | } catch (Exception e) { 57 | throw e; 58 | } 59 | 60 | } 61 | 62 | // TODO : 소셜 로그인 시에도 무조건 토큰 생성하지 말고 JWT 인증 필터처럼 RefreshToken 유/무에 따라 다르게 처리해보기 63 | private void loginSuccess(HttpServletResponse response, CustomOAuth2User oAuth2User) throws IOException { 64 | String accessToken = jwtService.createAccessToken(oAuth2User.getEmail()); 65 | String refreshToken = jwtService.createRefreshToken(); 66 | 67 | // response.addHeader(jwtService.getAccessHeader(), "Bearer " + accessToken); 68 | // response.addHeader(jwtService.getRefreshHeader(), "Bearer " + refreshToken); 69 | 70 | jwtService.sendAccessAndRefreshToken(response, accessToken, refreshToken); 71 | // jwtService.updateRefreshToken(oAuth2User.getEmail(), refreshToken); 72 | 73 | String redirectUrl = "http://this.code.s3-website-us-east-1.amazonaws.com/userslist?" + "Authorization" + "=" + 74 | URLEncoder.encode("Bearer " + accessToken, "UTF-8") + 75 | "&" + "Authorization-refresh" + "=" + URLEncoder.encode("Bearer " + refreshToken, "UTF-8"); 76 | response.sendRedirect(redirectUrl); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/login/filter/CustomJsonUsernamePasswordAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.login.filter; 2 | 3 | import java.io.IOException; 4 | import java.nio.charset.StandardCharsets; 5 | import java.util.Map; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.security.authentication.AuthenticationServiceException; 11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 12 | import org.springframework.security.core.Authentication; 13 | import org.springframework.security.core.AuthenticationException; 14 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 15 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 16 | import org.springframework.util.StreamUtils; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | 20 | /** 21 | * 스프링 시큐리티의 폼 기반의 UsernamePasswordAuthenticationFilter를 참고하여 만든 커스텀 필터 22 | * 거의 구조가 같고, Type이 Json인 Login만 처리하도록 설정한 부분만 다르다. (커스텀 API용 필터 구현) 23 | * Username : 회원 아이디 -> email로 설정 24 | * "/login" 요청 왔을 때 JSON 값을 매핑 처리하는 필터 25 | */ 26 | public class CustomJsonUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter { 27 | 28 | private static final String DEFAULT_LOGIN_REQUEST_URL = "/login"; // "/login"으로 오는 요청을 처리 29 | private static final String HTTP_METHOD = "POST"; // 로그인 HTTP 메소드는 POST 30 | private static final String CONTENT_TYPE = "application/json"; // JSON 타입의 데이터로 오는 로그인 요청만 처리 31 | private static final String USERNAME_KEY = "email"; // 회원 로그인 시 이메일 요청 JSON Key : "email" 32 | private static final String PASSWORD_KEY = "password"; // 회원 로그인 시 비밀번호 요청 JSon Key : "password" 33 | private static final AntPathRequestMatcher DEFAULT_LOGIN_PATH_REQUEST_MATCHER = 34 | new AntPathRequestMatcher(DEFAULT_LOGIN_REQUEST_URL, HTTP_METHOD); // "/login" + POST로 온 요청에 매칭된다. 35 | 36 | private final ObjectMapper objectMapper; 37 | 38 | public CustomJsonUsernamePasswordAuthenticationFilter(ObjectMapper objectMapper) { 39 | super(DEFAULT_LOGIN_PATH_REQUEST_MATCHER); // 위에서 설정한 "login" + POST로 온 요청을 처리하기 위해 설정 40 | this.objectMapper = objectMapper; 41 | } 42 | 43 | /** 44 | * 인증 처리 메소드 45 | * 46 | * UsernamePasswordAuthenticationFilter와 동일하게 UsernamePasswordAuthenticationToken 사용 47 | * StreamUtils를 통해 request에서 messageBody(JSON) 반환 48 | * 요청 JSON Example 49 | * { 50 | * "email" : "aaa@bbb.com" 51 | * "password" : "test123" 52 | * } 53 | * 꺼낸 messageBody를 objectMapper.readValue()로 Map으로 변환 (Key : JSON의 키 -> email, password) 54 | * Map의 Key(email, password)로 해당 이메일, 패스워드 추출 후 55 | * UsernamePasswordAuthenticationToken의 파라미터 principal, credentials에 대입 56 | * 57 | * AbstractAuthenticationProcessingFilter(부모)의 getAuthenticationManager()로 AuthenticationManager 객체를 반환 받은 후 58 | * authenticate()의 파라미터로 UsernamePasswordAuthenticationToken 객체를 넣고 인증 처리 59 | * (여기서 AuthenticationManager 객체는 ProviderManager -> SecurityConfig에서 설정) 60 | */ 61 | 62 | @Override 63 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws 64 | AuthenticationException, 65 | IOException { 66 | if(request.getContentType() == null || !request.getContentType().equals(CONTENT_TYPE) ) { 67 | throw new AuthenticationServiceException("Authentication Content-Type not supported: " + request.getContentType()); 68 | } 69 | 70 | String messageBody = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8); 71 | 72 | Map usernamePasswordMap = objectMapper.readValue(messageBody, Map.class); 73 | 74 | String email = usernamePasswordMap.get(USERNAME_KEY); 75 | String password = usernamePasswordMap.get(PASSWORD_KEY); 76 | 77 | 78 | UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(email, password);//principal 과 credentials 전달 79 | 80 | return this.getAuthenticationManager().authenticate(authRequest); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/config/RabbitConfig.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat.domain.chat.config; 2 | // 3 | // import org.springframework.amqp.core.Binding; 4 | // import org.springframework.amqp.core.BindingBuilder; 5 | // import org.springframework.amqp.core.Queue; 6 | // import org.springframework.amqp.core.TopicExchange; 7 | // import org.springframework.amqp.rabbit.annotation.EnableRabbit; 8 | // import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; 9 | // import org.springframework.amqp.rabbit.connection.ConnectionFactory; 10 | // import org.springframework.amqp.rabbit.core.RabbitTemplate; 11 | // import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; 12 | // import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; 13 | // import org.springframework.beans.factory.annotation.Value; 14 | // import org.springframework.context.annotation.Bean; 15 | // import org.springframework.context.annotation.Configuration; 16 | // 17 | // import com.fasterxml.jackson.databind.ObjectMapper; 18 | // import com.fasterxml.jackson.databind.SerializationFeature; 19 | // import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; 20 | // 21 | // @Configuration 22 | // @EnableRabbit 23 | // public class RabbitConfig { 24 | // 25 | // @Value("${spring.rabbitmq.host}") 26 | // private String host; 27 | // 28 | // @Value("${spring.rabbitmq.username}") 29 | // private String username; 30 | // 31 | // @Value("${spring.rabbitmq.password}") 32 | // private String password; 33 | // 34 | // 35 | // private static final String CHAT_QUEUE_NAME = "chat.queue"; 36 | // private static final String CHAT_EXCHANGE_NAME = "chat.exchange"; 37 | // private static final String ROUTING_KEY = "room.*"; 38 | // 39 | // // Queue 등록 40 | // @Bean 41 | // public Queue queue() { 42 | // return new Queue(CHAT_QUEUE_NAME, true); 43 | // } 44 | // 45 | // // Exchange 등록 46 | // @Bean 47 | // public TopicExchange exchange() { 48 | // return new TopicExchange(CHAT_EXCHANGE_NAME); 49 | // } 50 | // 51 | // // Exchange 와 Queue 바인딩 52 | // @Bean 53 | // public Binding binding() { 54 | // return BindingBuilder.bind(queue()).to(exchange()).with(ROUTING_KEY); 55 | // } 56 | // 57 | // 58 | // @Bean 59 | // public com.fasterxml.jackson.databind.Module dateTimeModule() { 60 | // return new JavaTimeModule(); 61 | // } 62 | // 63 | // 64 | // // Spring 에서 자동생성해주는 ConnectionFactory 는 SimpleConnectionFactory 65 | // // 여기서 사용하는 건 CachingConnectionFactory 라 새로 등록해줌 66 | // @Bean 67 | // public ConnectionFactory connectionFactory() { 68 | // CachingConnectionFactory factory = new CachingConnectionFactory(); 69 | // factory.setHost(host); 70 | // factory.setUsername(username); 71 | // factory.setPassword(password); 72 | // return factory; 73 | // } 74 | // 75 | // /** 76 | // * messageConverter를 커스터마이징 하기 위해 Bean 새로 등록 77 | // */ 78 | // 79 | // @Bean 80 | // public RabbitTemplate rabbitTemplate() { 81 | // RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory()); 82 | // rabbitTemplate.setMessageConverter(jsonMessageConverter()); 83 | // rabbitTemplate.setRoutingKey(CHAT_QUEUE_NAME); 84 | // return rabbitTemplate; 85 | // } 86 | // 87 | // @Bean 88 | // public SimpleMessageListenerContainer container() { 89 | // SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); 90 | // container.setConnectionFactory(connectionFactory()); 91 | // container.setQueueNames(CHAT_QUEUE_NAME); 92 | // // container.setMessageListener(null); 93 | // return container; 94 | // } 95 | // 96 | // @Bean 97 | // public Jackson2JsonMessageConverter jsonMessageConverter() { 98 | // //LocalDateTime serializable 을 위해 99 | // ObjectMapper objectMapper = new ObjectMapper(); 100 | // objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); 101 | // objectMapper.registerModule(dateTimeModule()); 102 | // return new Jackson2JsonMessageConverter(objectMapper); 103 | // } 104 | // } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/java,gradle,windows,macos,intellij+all 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=java,gradle,windows,macos,intellij+all 3 | 4 | ### Intellij+all ### 5 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 6 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 7 | 8 | # User-specific stuff 9 | .idea/**/workspace.xml 10 | .idea/**/tasks.xml 11 | .idea/**/usage.statistics.xml 12 | .idea/**/dictionaries 13 | .idea/**/shelf 14 | 15 | # AWS User-specific 16 | .idea/**/aws.xml 17 | 18 | # Generated files 19 | .idea/**/contentModel.xml 20 | 21 | # Sensitive or high-churn files 22 | .idea/**/dataSources/ 23 | .idea/**/dataSources.ids 24 | .idea/**/dataSources.local.xml 25 | .idea/**/sqlDataSources.xml 26 | .idea/**/dynamic.xml 27 | .idea/**/uiDesigner.xml 28 | .idea/**/dbnavigator.xml 29 | 30 | # Gradle 31 | .idea/**/gradle.xml 32 | .idea/**/libraries 33 | 34 | # Gradle and Maven with auto-import 35 | # When using Gradle or Maven with auto-import, you should exclude module files, 36 | # since they will be recreated, and may cause churn. Uncomment if using 37 | # auto-import. 38 | # .idea/artifacts 39 | # .idea/compiler.xml 40 | # .idea/jarRepositories.xml 41 | # .idea/modules.xml 42 | # .idea/*.iml 43 | # .idea/modules 44 | # *.iml 45 | # *.ipr 46 | 47 | # CMake 48 | cmake-build-*/ 49 | 50 | # Mongo Explorer plugin 51 | .idea/**/mongoSettings.xml 52 | 53 | # File-based project format 54 | *.iws 55 | 56 | # IntelliJ 57 | out/ 58 | 59 | # mpeltonen/sbt-idea plugin 60 | .idea_modules/ 61 | 62 | # JIRA plugin 63 | atlassian-ide-plugin.xml 64 | 65 | # Cursive Clojure plugin 66 | .idea/replstate.xml 67 | 68 | # SonarLint plugin 69 | .idea/sonarlint/ 70 | 71 | # Crashlytics plugin (for Android Studio and IntelliJ) 72 | com_crashlytics_export_strings.xml 73 | crashlytics.properties 74 | crashlytics-build.properties 75 | fabric.properties 76 | 77 | # Editor-based Rest Client 78 | .idea/httpRequests 79 | 80 | # Android studio 3.1+ serialized cache file 81 | .idea/caches/build_file_checksums.ser 82 | 83 | ### Intellij+all Patch ### 84 | # Ignore everything but code style settings and run configurations 85 | # that are supposed to be shared within teams. 86 | 87 | .idea/* 88 | 89 | !.idea/codeStyles 90 | !.idea/runConfigurations 91 | 92 | ### Java ### 93 | # Compiled class file 94 | *.class 95 | 96 | # Log file 97 | *.log 98 | 99 | # BlueJ files 100 | *.ctxt 101 | 102 | # Mobile Tools for Java (J2ME) 103 | .mtj.tmp/ 104 | 105 | # Package Files # 106 | *.jar 107 | *.war 108 | *.nar 109 | *.ear 110 | *.zip 111 | *.tar.gz 112 | *.rar 113 | 114 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 115 | hs_err_pid* 116 | replay_pid* 117 | 118 | ### macOS ### 119 | # General 120 | .DS_Store 121 | .AppleDouble 122 | .LSOverride 123 | 124 | # Icon must end with two \r 125 | Icon 126 | 127 | 128 | # Thumbnails 129 | ._* 130 | 131 | # Files that might appear in the root of a volume 132 | .DocumentRevisions-V100 133 | .fseventsd 134 | .Spotlight-V100 135 | .TemporaryItems 136 | .Trashes 137 | .VolumeIcon.icns 138 | .com.apple.timemachine.donotpresent 139 | 140 | # Directories potentially created on remote AFP share 141 | .AppleDB 142 | .AppleDesktop 143 | Network Trash Folder 144 | Temporary Items 145 | .apdisk 146 | 147 | ### macOS Patch ### 148 | # iCloud generated files 149 | *.icloud 150 | 151 | ### Windows ### 152 | # Windows thumbnail cache files 153 | Thumbs.db 154 | Thumbs.db:encryptable 155 | ehthumbs.db 156 | ehthumbs_vista.db 157 | 158 | # Dump file 159 | *.stackdump 160 | 161 | # Folder config file 162 | [Dd]esktop.ini 163 | 164 | # Recycle Bin used on file shares 165 | $RECYCLE.BIN/ 166 | 167 | # Windows Installer files 168 | *.cab 169 | *.msi 170 | *.msix 171 | *.msm 172 | *.msp 173 | 174 | # Windows shortcuts 175 | *.lnk 176 | 177 | ### Gradle ### 178 | .gradle 179 | **/build/ 180 | !src/**/build/ 181 | 182 | # Ignore Gradle GUI config 183 | gradle-app.setting 184 | 185 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 186 | !gradle-wrapper.jar 187 | 188 | # Avoid ignore Gradle wrappper properties 189 | !gradle-wrapper.properties 190 | 191 | # Cache of project 192 | .gradletasknamecache 193 | 194 | # Eclipse Gradle plugin generated files 195 | # Eclipse Core 196 | .project 197 | # JDT-specific (Eclipse Java Development Tools) 198 | .classpath 199 | 200 | ### Gradle Patch ### 201 | # Java heap dump 202 | *.hprof 203 | 204 | 205 | 206 | 207 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/controller/ChatController.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.controller; 2 | 3 | import com.challenge.chat.domain.chat.constant.KafkaConstants; 4 | import com.challenge.chat.domain.chat.dto.ChatDto; 5 | import com.challenge.chat.domain.chat.dto.ChatRoomDto; 6 | import com.challenge.chat.domain.chat.dto.request.ChatRoomAddRequest; 7 | import com.challenge.chat.domain.chat.dto.request.ChatRoomCreateRequest; 8 | import com.challenge.chat.domain.chat.service.ChatService; 9 | import com.challenge.chat.domain.chat.service.Producer; 10 | 11 | import lombok.RequiredArgsConstructor; 12 | import lombok.extern.slf4j.Slf4j; 13 | 14 | import org.springframework.http.HttpStatus; 15 | import org.springframework.http.ResponseEntity; 16 | import org.springframework.messaging.handler.annotation.MessageMapping; 17 | import org.springframework.messaging.simp.SimpMessageHeaderAccessor; 18 | import org.springframework.messaging.simp.SimpMessagingTemplate; 19 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 20 | import org.springframework.security.core.userdetails.User; 21 | import org.springframework.web.bind.annotation.*; 22 | 23 | import java.util.List; 24 | 25 | @RestController 26 | @Slf4j 27 | @CrossOrigin 28 | @RequiredArgsConstructor 29 | public class ChatController { 30 | 31 | private final ChatService chatService; 32 | private final Producer producer; 33 | private final SimpMessagingTemplate msgOperation; 34 | 35 | // private final RabbitTemplate rabbitTemplate; 36 | 37 | // private final static String CHAT_EXCHANGE_NAME = "chat.exchange"; 38 | 39 | @PostMapping("/chat") 40 | public ResponseEntity createChatRoom( 41 | @RequestBody final ChatRoomCreateRequest request, 42 | @AuthenticationPrincipal final User user) { 43 | 44 | return ResponseEntity.status(HttpStatus.OK) 45 | .body(chatService.makeChatRoom(request.getRoomName(), user.getUsername())); 46 | } 47 | 48 | @PostMapping("/chat/room") 49 | public ResponseEntity addChatRoom( 50 | @RequestBody final ChatRoomAddRequest request, 51 | @AuthenticationPrincipal final User user) { 52 | 53 | return ResponseEntity.status(HttpStatus.OK) 54 | .body(chatService.registerChatRoom(request.getRoomCode(), user.getUsername())); 55 | } 56 | 57 | @GetMapping("/chat/room") 58 | public ResponseEntity> showChatRoomList( 59 | @AuthenticationPrincipal final User user) { 60 | 61 | return ResponseEntity.status(HttpStatus.OK) 62 | .body(chatService.searchChatRoomList(user.getUsername())); 63 | } 64 | 65 | @GetMapping("/chat/{room-code}") 66 | public ResponseEntity> showChatList( 67 | @PathVariable("room-code") final String roomCode, 68 | @AuthenticationPrincipal final User user) { 69 | 70 | return ResponseEntity.status(HttpStatus.OK) 71 | .body(chatService.searchChatList(roomCode, user.getUsername())); 72 | } 73 | 74 | @MessageMapping("/chat/enter") 75 | public void enterChatRoom( 76 | @RequestBody ChatDto chatDto, 77 | SimpMessageHeaderAccessor headerAccessor) { 78 | 79 | ChatDto newChatDto = chatService.makeEnterMessageAndSetSessionAttribute(chatDto, headerAccessor); 80 | // producer.send( 81 | // KafkaConstants.KAFKA_TOPIC, 82 | // newchatDto 83 | // ); 84 | 85 | msgOperation.convertAndSend("/topic/chat/room/" + chatDto.getRoomCode(), newChatDto); 86 | // rabbitTemplate.convertAndSend(CHAT_EXCHANGE_NAME, "room." + newChatDto.getRoomCode(), newChatDto); 87 | } 88 | 89 | @MessageMapping("/chat/send") 90 | public void sendChatRoom( 91 | @RequestBody ChatDto chatDto) { 92 | 93 | producer.send( 94 | KafkaConstants.KAFKA_TOPIC, 95 | chatDto 96 | ); 97 | // rabbitTemplate.convertAndSend(CHAT_EXCHANGE_NAME, "room." + chatDto.getRoomCode(), chatDto); 98 | // chatService.sendChatRoom(chatDto); 99 | msgOperation.convertAndSend("/topic/chat/room/" + chatDto.getRoomCode(), chatDto); 100 | } 101 | 102 | @GetMapping("/chat/{room-code}/{message}") 103 | public ResponseEntity> searchChatList( 104 | @PathVariable("room-code") final String roomCode, 105 | @PathVariable("message") final String message) { 106 | 107 | log.info("Controller : 채팅 메시지 검색"); 108 | 109 | return ResponseEntity.status(HttpStatus.OK) 110 | .body(chatService.findChatList(roomCode, message)); 111 | } 112 | 113 | // @EventListener 114 | // public void webSocketDisconnectListener(SessionDisconnectEvent event) { 115 | // StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage()); 116 | // log.info("Controller webSocketDisconnectListener, 채팅방 나가기"); 117 | // ChatDto chatDto = chatService.leaveChatRoom(headerAccessor); 118 | // msgOperation.convertAndSend("/topic/chat/room/" + chatDto.getRoomId(), chatDto); 119 | // } 120 | } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/oauth/service/CustomOAuth2UserService.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.oauth.service; 2 | 3 | import com.challenge.chat.domain.member.constant.SocialType; 4 | import com.challenge.chat.domain.member.entity.Member; 5 | import com.challenge.chat.domain.member.repository.MemberRepository; 6 | import com.challenge.chat.security.jwt.service.JwtService; 7 | import com.challenge.chat.security.oauth.dto.CustomOAuth2User; 8 | import com.challenge.chat.security.oauth.dto.OAuthAttributes; 9 | import lombok.RequiredArgsConstructor; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; 13 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; 14 | import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; 15 | import org.springframework.security.oauth2.core.OAuth2AuthenticationException; 16 | import org.springframework.security.oauth2.core.user.OAuth2User; 17 | import org.springframework.stereotype.Service; 18 | 19 | import java.util.Collections; 20 | import java.util.Map; 21 | 22 | @Slf4j 23 | @Service 24 | @RequiredArgsConstructor 25 | public class CustomOAuth2UserService implements OAuth2UserService { 26 | 27 | private final MemberRepository memberRepository; 28 | private final JwtService jwtService; 29 | 30 | private static final String NAVER = "naver"; 31 | private static final String KAKAO = "kakao"; 32 | 33 | @Override 34 | public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { 35 | log.info("CustomOAuth2UserService.loadUser() 실행 - OAuth2 로그인 요청 진입"); 36 | 37 | /** 38 | * DefaultOAuth2UserService 객체를 생성하여, loadUser(userRequest)를 통해 DefaultOAuth2User 객체를 생성 후 반환 39 | * DefaultOAuth2UserService의 loadUser()는 소셜 로그인 API의 사용자 정보 제공 URI로 요청을 보내서 40 | * 사용자 정보를 얻은 후, 이를 통해 DefaultOAuth2User 객체를 생성 후 반환한다. 41 | * 결과적으로, OAuth2User는 OAuth 서비스에서 가져온 유저 정보를 담고 있는 유저 42 | */ 43 | OAuth2UserService delegate = new DefaultOAuth2UserService(); 44 | OAuth2User oAuth2User = delegate.loadUser(userRequest); 45 | 46 | /** 47 | * userRequest에서 registrationId 추출 후 registrationId으로 SocialType 저장 48 | * http://localhost:8080/oauth2/authorization/kakao에서 kakao가 registrationId 49 | * userNameAttributeName은 이후에 nameAttributeKey로 설정된다. 50 | */ 51 | String registrationId = userRequest.getClientRegistration().getRegistrationId(); 52 | SocialType socialType = getSocialType(registrationId); 53 | String userNameAttributeName = userRequest.getClientRegistration() 54 | .getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName(); // OAuth2 로그인 시 키(PK)가 되는 값 55 | Map attributes = oAuth2User.getAttributes(); // 소셜 로그인에서 API가 제공하는 userInfo의 Json 값(유저 정보들) 56 | 57 | // socialType에 따라 유저 정보를 통해 OAuthAttributes 객체 생성 58 | OAuthAttributes extractAttributes = OAuthAttributes.of(socialType, userNameAttributeName, attributes); 59 | 60 | Member createdUser = getUser(extractAttributes, socialType); // getUser() 메소드로 User 객체 생성 후 반환 61 | 62 | // DefaultOAuth2User를 구현한 CustomOAuth2User 객체를 생성해서 반환 63 | return new CustomOAuth2User( 64 | Collections.singleton(new SimpleGrantedAuthority(createdUser.getRole().getKey())), 65 | attributes, 66 | extractAttributes.getNameAttributeKey(), 67 | createdUser.getEmail(), 68 | createdUser.getRole() 69 | ); 70 | } 71 | 72 | private SocialType getSocialType(String registrationId) { 73 | if(NAVER.equals(registrationId)) { 74 | return SocialType.NAVER; 75 | } 76 | if(KAKAO.equals(registrationId)) { 77 | return SocialType.KAKAO; 78 | } 79 | return SocialType.GOOGLE; 80 | } 81 | 82 | /** 83 | * SocialType과 attributes에 들어있는 소셜 로그인의 식별값 id를 통해 회원을 찾아 반환하는 메소드 84 | * 만약 찾은 회원이 있다면, 그대로 반환하고 없다면 saveUser()를 호출하여 회원을 저장한다. 85 | */ 86 | private Member getUser(OAuthAttributes attributes, SocialType socialType) { 87 | Member findUser = memberRepository.findBySocialTypeAndSocialId(socialType, 88 | attributes.getOauth2UserInfo().getId()).orElse(null); 89 | 90 | if(findUser == null) { 91 | return saveUser(attributes, socialType); 92 | } 93 | if (!jwtService.isTokenValid(findUser.getRefreshToken())){ 94 | findUser.updateRefreshToken(jwtService.createRefreshToken()); 95 | } 96 | return findUser; 97 | } 98 | 99 | /** 100 | * OAuthAttributes의 toEntity() 메소드를 통해 빌더로 User 객체 생성 후 반환 101 | * 생성된 User 객체를 DB에 저장 : socialType, socialId, email, role 값만 있는 상태 102 | */ 103 | private Member saveUser(OAuthAttributes attributes, SocialType socialType) { 104 | Member createdUser = attributes.toEntity(socialType, attributes.getOauth2UserInfo()); 105 | createdUser.updateRefreshToken(jwtService.createRefreshToken()); 106 | return memberRepository.save(createdUser); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/test/java/com/challenge/chat/domain/member/service/MemberServiceTest.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat.domain.member.service; 2 | // 3 | // import com.challenge.chat.domain.member.constant.MemberRole; 4 | // import com.challenge.chat.domain.member.constant.SocialType; 5 | // import com.challenge.chat.domain.member.dto.MemberDto; 6 | // import com.challenge.chat.domain.member.entity.Member; 7 | // import com.challenge.chat.domain.member.repository.MemberRepository; 8 | // import com.challenge.chat.exception.RestApiException; 9 | // import org.junit.jupiter.api.DisplayName; 10 | // import org.junit.jupiter.api.Test; 11 | // import org.junit.jupiter.api.extension.ExtendWith; 12 | // import org.mockito.InjectMocks; 13 | // import org.mockito.Mock; 14 | // import org.mockito.junit.jupiter.MockitoExtension; 15 | // 16 | // import java.util.ArrayList; 17 | // import java.util.List; 18 | // import java.util.Optional; 19 | // 20 | // import static org.assertj.core.api.Assertions.assertThat; 21 | // import static org.assertj.core.api.Assertions.assertThatThrownBy; 22 | // import static org.mockito.BDDMockito.any; 23 | // import static org.mockito.BDDMockito.given; 24 | // 25 | // @ExtendWith(MockitoExtension.class) 26 | // class MemberServiceTest { 27 | // 28 | // @InjectMocks 29 | // private MemberService memberService; 30 | // 31 | // @Mock //스프링빈에 등록이 안되는 가짜 객체 32 | // private MemberRepository memberRepository; 33 | // 34 | // @Test 35 | // @DisplayName("멤버 리스트 조회 성공") 36 | // void getMemberList() { 37 | // //given 38 | // List memberList = new ArrayList<>(); 39 | // Member member1 = setMember("objectId1", "email1@test.com"); 40 | // Member member2 = setMember("objectId2", "email2@test.com"); 41 | // Member member3 = setMember("objectId3", "email3@test.com"); 42 | // memberList.add(member1); 43 | // memberList.add(member2); 44 | // memberList.add(member3); 45 | // given(memberRepository.findAll()).willReturn(memberList); 46 | // 47 | // //when 48 | // List memberDtoList = memberService.getMemberList(); 49 | // 50 | // //then 51 | // for (int i = 0; i < memberDtoList.size(); i++) { 52 | // assertThat(memberDtoList.get(i).getEmail()).isEqualTo(memberList.get(i).getEmail()); 53 | // assertThat(memberDtoList.get(i).getImageUrl()).isEqualTo(memberList.get(i).getImageUrl()); 54 | // assertThat(memberDtoList.get(i).getId()).isEqualTo(memberList.get(i).getId()); 55 | // assertThat(memberDtoList.get(i).getNickname()).isEqualTo(memberList.get(i).getNickname()); 56 | // } 57 | // } 58 | // 59 | // @Test 60 | // @DisplayName("email로 단일 멤버 조회 성공") 61 | // void getMemberByEmail() { 62 | // //given 63 | // String email = "test1234@test.com"; 64 | // Member member = setMember("objectId1", email); 65 | // given(memberRepository.findByEmail(email)).willReturn(Optional.of(member)); 66 | // 67 | // //when 68 | // MemberDto memberDtoList = memberService.getMemberByEmail(email); 69 | // 70 | // //then 71 | // assertThat(memberDtoList.getEmail()).isEqualTo(member.getEmail()); 72 | // assertThat(memberDtoList.getImageUrl()).isEqualTo(member.getImageUrl()); 73 | // assertThat(memberDtoList.getId()).isEqualTo(member.getId()); 74 | // assertThat(memberDtoList.getNickname()).isEqualTo(member.getNickname()); 75 | // } 76 | // 77 | // @Test 78 | // @DisplayName("email로 단일 멤버 조회 실패") 79 | // void getMemberByEmailFail() { 80 | // //given 81 | // String email = "test1234@test.com"; 82 | // given(memberRepository.findByEmail(any())).willReturn(Optional.empty()); 83 | // 84 | // //when, then 85 | // assertThatThrownBy(() -> memberService.getMemberByEmail(email)) 86 | // .isInstanceOf(RestApiException.class); 87 | // } 88 | // 89 | // @Test 90 | // @DisplayName("id로 정보 조회 성공") 91 | // void getMemberByUserId() { 92 | // //given 93 | // String id = "objectId1"; 94 | // String email = "test1234@test.com"; 95 | // Member member = setMember(id, email); 96 | // given(memberRepository.findById(id)).willReturn(Optional.of(member)); 97 | // 98 | // //when 99 | // MemberDto resultMember = memberService.getMemberByUserId(id); 100 | // 101 | // //then 102 | // assertThat(resultMember.getEmail()).isEqualTo(member.getEmail()); 103 | // assertThat(resultMember.getImageUrl()).isEqualTo(member.getImageUrl()); 104 | // assertThat(resultMember.getId()).isEqualTo(member.getId()); 105 | // assertThat(resultMember.getNickname()).isEqualTo(member.getNickname()); 106 | // } 107 | // 108 | // @Test 109 | // @DisplayName("id로 정보 조회 실패") 110 | // void getMemberByUserIdFail() { 111 | // //given 112 | // long id = 1L; 113 | // given(memberRepository.findById(any())).willReturn(Optional.empty()); 114 | // 115 | // //when, then 116 | // assertThatThrownBy(() -> memberService.findMemberById(id)) 117 | // .isInstanceOf(RestApiException.class); 118 | // } 119 | // 120 | // private Member setMember(String id, String email) { 121 | // return new Member(id, email, "password", "nickName" 122 | // , "image", MemberRole.USER, SocialType.GOOGLE, null 123 | // , "refreshToken", null); 124 | // } 125 | // } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/domain/chat/service/ChatService.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.domain.chat.service; 2 | 3 | import com.challenge.chat.domain.chat.dto.ChatDto; 4 | import com.challenge.chat.domain.chat.dto.ChatRoomDto; 5 | import com.challenge.chat.domain.chat.entity.Chat; 6 | import com.challenge.chat.domain.chat.entity.ChatRoom; 7 | import com.challenge.chat.domain.chat.entity.MemberChatRoom; 8 | import com.challenge.chat.domain.chat.entity.MessageType; 9 | import com.challenge.chat.domain.chat.repository.ChatRepository; 10 | import com.challenge.chat.domain.chat.repository.ChatRoomRepository; 11 | import com.challenge.chat.domain.chat.repository.MemberChatRoomRepository; 12 | import com.challenge.chat.domain.member.entity.Member; 13 | import com.challenge.chat.domain.member.service.MemberService; 14 | import com.challenge.chat.exception.RestApiException; 15 | import com.challenge.chat.exception.dto.ChatErrorCode; 16 | import lombok.RequiredArgsConstructor; 17 | import lombok.extern.slf4j.Slf4j; 18 | 19 | import org.springframework.data.elasticsearch.core.ElasticsearchOperations; 20 | import org.springframework.messaging.simp.SimpMessageHeaderAccessor; 21 | import org.springframework.stereotype.Service; 22 | import org.springframework.transaction.annotation.Transactional; 23 | 24 | import java.util.Collections; 25 | import java.util.Comparator; 26 | import java.util.List; 27 | import java.util.Objects; 28 | import java.util.stream.Collectors; 29 | 30 | @Service 31 | @RequiredArgsConstructor 32 | @Slf4j 33 | public class ChatService { 34 | 35 | private final MemberChatRoomRepository memberChatRoomRepository; 36 | private final ChatRoomRepository chatRoomRepository; 37 | private final ChatRepository chatRepository; 38 | private final MemberService memberService; 39 | private final ElasticsearchOperations elasticsearchOperations; 40 | 41 | @Transactional 42 | public ChatRoomDto makeChatRoom(final String roomName, final String memberEmail) { 43 | 44 | ChatRoom chatRoom = ChatRoom.of(roomName); 45 | Member member = memberService.findMemberByEmail(memberEmail); 46 | 47 | // TODO : 비동기적으로 chatRoom 과 memberChatRoom을 저장하기 48 | chatRoomRepository.save(chatRoom); 49 | memberChatRoomRepository.save(MemberChatRoom.of(chatRoom, member)); 50 | 51 | return ChatRoomDto.from(chatRoom); 52 | } 53 | 54 | @Transactional 55 | public ChatRoomDto registerChatRoom(final String roomCode, final String memberEmail) { 56 | 57 | ChatRoom chatRoom = findChatRoom(roomCode); 58 | Member member = memberService.findMemberByEmail(memberEmail); 59 | if (memberChatRoomRepository.findByMemberAndRoom(member, chatRoom).isEmpty()){ 60 | memberChatRoomRepository.save(MemberChatRoom.of(chatRoom, member)); 61 | } 62 | 63 | return ChatRoomDto.from(chatRoom); 64 | } 65 | 66 | @Transactional(readOnly = true) 67 | public List searchChatRoomList(final String memberEmail) { 68 | 69 | // TODO : 채팅방 리스트를 가져오는 동작이 2번의 쿼리를 동기적으로 실행해서 오히려 느려질 수 있는 지점이 될 수 있음 70 | Member member = memberService.findMemberByEmail(memberEmail); 71 | List memberChatRoomList = findChatRoomByMember(member); 72 | 73 | return memberChatRoomList 74 | .stream() 75 | .map(a -> ChatRoomDto.from(a.getRoom())) 76 | .collect(Collectors.toList()); 77 | } 78 | 79 | @Transactional(readOnly = true) 80 | public List searchChatList(final String roomCode, final String memberEmail) { 81 | 82 | List chatList = chatRepository.findByRoomCode(roomCode).orElse(Collections.emptyList()); 83 | 84 | return chatList.stream() 85 | .map(ChatDto::from) 86 | .sorted(Comparator.comparing(ChatDto::getCreatedAt)) 87 | .collect(Collectors.toList()); 88 | } 89 | 90 | @Transactional(readOnly = true) 91 | public ChatDto makeEnterMessageAndSetSessionAttribute(ChatDto chatDto, SimpMessageHeaderAccessor headerAccessor) { 92 | 93 | // socket session에 사용자의 정보 저장 94 | try { 95 | Objects.requireNonNull(headerAccessor.getSessionAttributes()).put("email", chatDto.getEmail()); 96 | headerAccessor.getSessionAttributes().put("roomCode", chatDto.getRoomCode()); 97 | headerAccessor.getSessionAttributes().put("nickname", chatDto.getNickname()); 98 | } catch (Exception e) { 99 | throw new RestApiException(ChatErrorCode.SOCKET_CONNECTION_ERROR); 100 | } 101 | 102 | chatDto.setMessage(chatDto.getNickname() + "님 입장!! ο(=•ω<=)ρ⌒☆"); 103 | 104 | return chatDto; 105 | } 106 | 107 | // public void sendChatRoom(ChatDto chatDto) { 108 | // chatRepository.save(ChatDto.toEntity(chatDto)); 109 | // } 110 | 111 | public List findChatList(final String roomCode, final String message) { 112 | 113 | List chatList = chatRepository.findByRoomCodeAndMessageContaining(roomCode, message) 114 | .orElse(Collections.emptyList()); 115 | 116 | return chatList.stream() 117 | .map(ChatDto::from) 118 | .collect(Collectors.toList()); 119 | 120 | // QueryBuilder queryBuilder = QueryBuilders.boolQuery() 121 | // .must(QueryBuilders.matchQuery("message", message)) 122 | // .must(QueryBuilders.matchQuery("roomCode", roomCode)); 123 | // 124 | // NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() 125 | // .withQuery(queryBuilder) 126 | // .build(); 127 | // 128 | // SearchHits searchHits = elasticsearchOperations.search(searchQuery, ChatES.class); 129 | // 130 | // return searchHits.stream() 131 | // .map(SearchHit::getContent) 132 | // .map(ChatDto::from) 133 | // .collect(Collectors.toList()); 134 | } 135 | 136 | public ChatDto leaveChatRoom(SimpMessageHeaderAccessor headerAccessor) { 137 | 138 | String roomCode = (String)headerAccessor.getSessionAttributes().get("roomCode"); 139 | String nickName = (String)headerAccessor.getSessionAttributes().get("nickName"); 140 | String userId = (String)headerAccessor.getSessionAttributes().get("userId"); 141 | 142 | return ChatDto.builder() 143 | .type(MessageType.LEAVE) 144 | .roomCode(roomCode) 145 | .nickname(nickName) 146 | .email(userId) 147 | .message(nickName + "님 퇴장!! ヽ(*。>Д<)o゜") 148 | .build(); 149 | } 150 | 151 | public ChatRoom findChatRoom(String roomCode) { 152 | return chatRoomRepository.findByRoomCode(roomCode).orElseThrow( 153 | () -> new RestApiException(ChatErrorCode.CHATROOM_NOT_FOUND)); 154 | } 155 | 156 | private List findChatRoomByMember(Member member) { 157 | return memberChatRoomRepository.findByMember(member).orElseThrow( 158 | () -> new RestApiException(ChatErrorCode.CHATROOM_NOT_FOUND)); 159 | } 160 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![tc3](https://github.com/god-kao-talk/.github/assets/54833128/c0ccb62e-4940-40e9-9ffd-60326cce5a89) 2 | 3 | # this.code 👩‍💻 4 | ### 대규모 트래픽 처리가 가능한 실시간 채팅 서비스 💬 5 | - 현대 사회에 필수불가결한 메신저 어플의 대용량 데이터 발생과 이로 인한 부하를 견뎌내기 위해 필요한 대책을 직접 리서치 및 적용 6 | - 매번 업그레이드 한 버전 별로 테스트를 진행하고 결과를 수치화, 시각화하여 개선 과정 신뢰도 향상 7 | 8 | --- 9 | ## 프로젝트 목표 10 | ### 1. 초당 5000건의 동시 트래픽을 감당하는 채팅 서비스 ⚡ 11 | - 채팅 메세지 전송/수신 max 1000ms 12 | - 채팅 메세지 영구 저장 13 | - 실시간 서버 모니터링 14 | - 스케일 아웃 가능한 서버 15 | 16 | ### 2. 스파이크 테스트로 안정성 있는 트래픽 관리 📈 17 | - 단계별로 아래의 테스트 조건들을 상향시키면서 에러율과 최대지연시간의 결과와 원인을 분석하며 성능 개선 18 | - 동시간대 접속 유저 : 100~5000명 19 | - 초당 보내는 채팅 수 : 100~5000개 20 | - 분당 보내는 총 채팅 수 : 6000~300,000개 21 | - 응답 시간 제한 : 1000ms, 2000ms 22 | 23 | ### 3. 실시간으로 누적되는 데이터 처리 💾 24 | - 분당 최대 300000건의 데이터들을 수용하기 위한 DB 성능 개선 25 | - 경제적이고 효율적인 DB선정을 위한 데이터베이스 시스템 분석 26 | - MySQL 27 | - MongoDB 28 | - Cassandra 29 | 30 | ### 4. 채팅 검색 기능 🔎 31 | - 검색 성능 개선 32 | 33 | --- 34 | ## 영상 📽️ 35 | - [최종 발표 영상](https://www.youtube.com/watch?v=T1Iw6dhlZkQ) 36 | - [간단 홍보 영상](https://www.youtube.com/watch?v=yDGTc6K40o4) 37 | - 핵심 기능 시연 영상 38 | 39 | |채팅방 추가|채팅 기능| 40 | |---|---| 41 | |채팅방 추가|채팅 내용| 42 | 43 | - 부하 테스트 시연 영상 44 | 45 | |1. 도커 스웜을 통한 클러스터 환경 구축|2. JMeter를 통한 부하 테스트 시작| 46 | |---|---| 47 | |도커 스웜|부하 테스트 시작| 48 | |3. 도커 컨테이너 리소스 사용률 및 서버 로그 확인|4. 그라파나를 통한 서버 모니터링| 49 | |서버 로그|서버 모니터링| 50 | |5. db 모니터링|6. 테스트를 통해 나온 지표 확인 및 분석| 51 | |db 모니터링|테스트 결과 확인| 52 | 53 | 54 | --- 55 | ## 서비스 아키텍처 ⚙️ 56 | ![서비스 아키텍처](https://github.com/god-kao-talk/.github/assets/54833128/930aa88d-07ea-47e7-9ec3-9602f52ae4fc) 57 | ### 활용 기술 / 기술적 의사 결정 ⚒️ 58 | 59 | |요구사항|선택지|기술 선택 이유| 60 | |---|---|---| 61 | |🛢️ 데이터 베이스|ver1. MySQL,
ver2. MongoDB,
ver3. Cassandra|버전 별 성능테스트 결과와 IOPS와 Billing 측면에서 우위를 가진 MongoDB 최종 선택| 62 | |📈 부하 테스트|Jmeter, Ngrinder|소켓 통신 테스트를 위한 시나리오 작성 가능| 63 | |📊 모니터링|Grafana, Prometheus, kibana|- Grafana : 시스템 관점에서 CPU 메모리, 디스크 IO 사용율과 같은 지표를 시각화 하는데 특화
- Kibana : 엘라스틱 위에서 쿼리 로그 분석에 특화
→ 채팅 시스템에서 트래픽 지표를 분석하기 위해 Grafana 선택| 64 | |🛠️ 데이터 파이프라인|Kafka, Redis|- Redis : 휘발성
- kafka : 트랜잭션을 줄이고 비동기적으로 데이터베이스에 저장할 수 있고 정합성을 보장
→ 휘발성이 있는 Redis는 신뢰도가 중요한 채팅 서비스와 적합하지 않다고 판단, kafka 선택| 65 | |🗂️ 클러스터링|Docker Swarm, Kubernetes|컨테이너 클러스터링, 로드밸런싱 기능에 집중
- 중소 규모의 클러스터에서 컨테이너 기반 애플리케이션 구동을 제어하기에 충분한 기능을 제공
- 도커 엔진이 설치된 환경이라면 별도의 구축 비용 없이 컨테이너 오케스트레이션 환경 구축 가능
- Kubernetes의 경우 master node의 최소 요구 사양이 CPU 2, RAM 2GB, 현 프로젝트에 오버 스펙이라고 판단
→ Docker Swarm 선택| 66 | |🔍 검색 성능 개선|Elasticsearch,
MongoDB Index,
QueryDSL|대용량의 데이터 속에서 채팅 메시지를 찾아야 함에 집중
- 역 인덱스를 이용해 데이터를 관리하기 때문에 모든 데이터를 탐색하지 않고도 결과를 찾을 수 있음
- 데이터의 규모가 커질수록 찾고자 하는 메시지의 데이터 위치를 알고 있는 것은 성능 최적화를 가능케 함| 67 | |⚙️ CI/CD|Github Action, Jenkins|Jenkins: 별도의 서버를 구축해야하며, 계정과 트리거에 기반하고 있으며 GitHub 이벤트를 처리할 수없다.
Git Action: 클라우드에서 동작하므로 어떤 설치도 필요 없다. 모든 GitHub 이벤트에 대해 GitHub Actions를 제공하고 있다. GitHub에 push, PR 이벤트가 발생할 때 자동 테스트, 배포가 쉽게 이루어지기 때문에 개발에 몰두할 수 있음
-> Github Action 선택| 68 | |🚀 소켓 통신|Web socket|- 서버가 클라이언트에게 비동기 메시지를 보낼 때 가장 널리 사용하는 기술
- 양방향 메시지 전송까지 가능| 69 | 70 | 71 | --- 72 | ## ERD, 유저 플로우 🏄 73 |
74 | ERD 펼쳐보기 75 | erd 76 |
77 | 78 |
79 | 유저 플로우 펼쳐보기 80 | user flow 81 |
82 | 83 | --- 84 | ## 부하 테스트 및 성능 개선 🔥 85 | - [🐬version 0.1](https://www.notion.so/version-0-1-a5d33fa6a17247498c25f3d79f8d02f2) 86 | - [🐒version 0.2](https://www.notion.so/version-0-2-b8a2c77900f54824a71378bc704e6445) 87 | - [🐅version 0.3](https://www.notion.so/version-0-3-afadc459105944a9b1a2b13c61cf621a) 88 | - [❌version 0.x](https://www.notion.so/version-0-x-c9983b7397724ff9bba241088714d53d) 89 | - [최종 성능 개선 결과](https://www.notion.so/dca6e10439e84264b390f12abbda9d93) 90 | - [부하 테스트 기록](https://docs.google.com/spreadsheets/d/1K3fgQ_T9y2-cGr0WNEFuMYYJ845qjKn5BfrGWD9_tHo/edit#gid=1540611111) 91 | 92 | --- 93 | ## 팀원 👨‍👩‍👦‍👦 94 | |역할|이름|담당|github| 95 | |---|---|---|---| 96 | |공통| |- BE 채팅 서비스 구현
- 부하 테스트 결과 분석
- 아키텍처 및 데이터 플로우 개선
- 서비스 문제점 파악| | 97 | |팀장|김건|- FE 채팅 서비스 구현 및 개선 방향 제시
- 코드 리팩토링
- Docker 분석 및 환경 테스트
- kafka를 통한 채팅 데이터 플로우 방향 제시
- elasticsearch 기능 구현, 한글 형태소 분석기 추가
- ES sink connector 구현|
프로필 사진
98 | |팀원|박권재|- JUnit 테스트 코드 구현
- Jmeter 시나리오 구현 및 테스트
- kafka 연결 구현
- kafka connet 구현, mongoDB와 연결
- cassandra 구현|
프로필 사진1
| 99 | |팀원|이상언|- 코드 리팩토링
- Jmeter 시나리오 구현 및 테스트
- Grafana 구현
- Prometheus, Spring actuator 구현
- QueryDSL 구현|
프로필 사진2
| 100 | |팀원|이태경|- kafka 구현
- NoSQL분석, MongoDB 연결
- Docker Swarm 구현
- GitAction CI/CD 구현
- Grafana, Prometheus 구현|
프로필 사진3
| 101 | 102 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/jwt/service/JwtService.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.jwt.service; 2 | 3 | import java.util.Date; 4 | import java.util.Optional; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.stereotype.Service; 11 | 12 | import com.auth0.jwt.JWT; 13 | import com.auth0.jwt.algorithms.Algorithm; 14 | import com.challenge.chat.domain.member.entity.Member; 15 | import com.challenge.chat.domain.member.repository.MemberRepository; 16 | import com.challenge.chat.exception.RestApiException; 17 | import com.challenge.chat.exception.dto.MemberErrorCode; 18 | 19 | import lombok.Getter; 20 | import lombok.RequiredArgsConstructor; 21 | import lombok.extern.slf4j.Slf4j; 22 | 23 | @Service 24 | @RequiredArgsConstructor 25 | @Getter 26 | @Slf4j 27 | public class JwtService { 28 | 29 | @Value("${jwt.secretKey}") 30 | private String secretKey; 31 | 32 | @Value("${jwt.access.expiration}") 33 | private Long accessTokenExpirationPeriod; 34 | 35 | @Value("${jwt.refresh.expiration}") 36 | private Long refreshTokenExpirationPeriod; 37 | 38 | @Value("${jwt.access.header}") 39 | private String accessHeader; 40 | 41 | @Value("${jwt.refresh.header}") 42 | private String refreshHeader; 43 | 44 | /** 45 | * JWT의 Subject와 Claim으로 email 사용 -> 클레임의 name을 "email"으로 설정 46 | * JWT의 헤더에 들어오는 값 : 'Authorization(Key) = Bearer {토큰} (Value)' 형식 47 | */ 48 | private static final String ACCESS_TOKEN_SUBJECT = "AccessToken"; 49 | private static final String REFRESH_TOKEN_SUBJECT = "RefreshToken"; 50 | private static final String EMAIL_CLAIM = "email"; 51 | private static final String NICKNAME_CLAIM = "nickname"; 52 | private static final String IMAGE_URL_CLAIM = "imageUrl"; 53 | private static final String BEARER = "Bearer "; 54 | 55 | private final MemberRepository memberRepository; 56 | 57 | /** 58 | * AccessToken 생성 메소드 59 | */ 60 | public String createAccessToken(String email) { 61 | Date now = new Date(); 62 | Member member = memberRepository.findByEmail(email).get(); 63 | 64 | return JWT.create() // JWT 토큰을 생성하는 빌더 반환 65 | .withSubject(ACCESS_TOKEN_SUBJECT) // JWT의 Subject 지정 -> AccessToken이므로 AccessToken 66 | .withExpiresAt(new Date(now.getTime() + accessTokenExpirationPeriod)) // 토큰 만료 시간 설정 67 | 68 | //클레임으로는 저희는 email 하나만 사용합니다. 69 | //추가적으로 식별자나, 이름 등의 정보를 더 추가하셔도 됩니다. 70 | //추가하실 경우 .withClaim(클래임 이름, 클래임 값) 으로 설정해주시면 됩니다 71 | .withClaim(EMAIL_CLAIM, email) 72 | .withClaim(NICKNAME_CLAIM, member.getNickname()) 73 | .withClaim(IMAGE_URL_CLAIM, member.getImageUrl()) 74 | .sign(Algorithm.HMAC512(secretKey)); // HMAC512 알고리즘 사용, application-jwt.yml에서 지정한 secret 키로 암호화 75 | } 76 | 77 | /** 78 | * RefreshToken 생성 79 | * RefreshToken은 Claim에 email도 넣지 않으므로 withClaim() X 80 | */ 81 | public String createRefreshToken() { 82 | Date now = new Date(); 83 | String refreshToken = JWT.create() 84 | .withSubject(REFRESH_TOKEN_SUBJECT) 85 | .withExpiresAt(new Date(now.getTime() + refreshTokenExpirationPeriod)) 86 | .sign(Algorithm.HMAC512(secretKey)); 87 | log.info("리프레시 토큰 발급 완료"); 88 | return refreshToken; 89 | } 90 | 91 | /** 92 | * AccessToken 헤더에 실어서 보내기 93 | */ 94 | public void sendAccessToken(HttpServletResponse response, String accessToken) { 95 | response.setStatus(HttpServletResponse.SC_OK); 96 | 97 | response.setHeader(accessHeader, accessToken); 98 | log.info("재발급된 Access Token : {}", accessToken); 99 | } 100 | 101 | /** 102 | * AccessToken + RefreshToken 헤더에 실어서 보내기 103 | */ 104 | public void sendAccessAndRefreshToken(HttpServletResponse response, String accessToken, String refreshToken) { 105 | response.setStatus(HttpServletResponse.SC_OK); 106 | 107 | setAccessTokenHeader(response, accessToken); 108 | setRefreshTokenHeader(response, refreshToken); 109 | log.info("Access Token, Refresh Token 헤더 설정 완료"); 110 | } 111 | 112 | /** 113 | * 헤더에서 RefreshToken 추출 114 | * 토큰 형식 : Bearer XXX에서 Bearer를 제외하고 순수 토큰만 가져오기 위해서 115 | * 헤더를 가져온 후 "Bearer"를 삭제(""로 replace) 116 | */ 117 | public Optional extractRefreshToken(HttpServletRequest request) { 118 | return Optional.ofNullable(request.getHeader(refreshHeader)) 119 | .filter(refreshToken -> refreshToken.startsWith(BEARER)) 120 | .map(refreshToken -> refreshToken.replace(BEARER, "")); 121 | } 122 | 123 | /** 124 | * 헤더에서 AccessToken 추출 125 | * 토큰 형식 : Bearer XXX에서 Bearer를 제외하고 순수 토큰만 가져오기 위해서 126 | * 헤더를 가져온 후 "Bearer"를 삭제(""로 replace) 127 | */ 128 | public Optional extractAccessToken(HttpServletRequest request) { 129 | return Optional.ofNullable(request.getHeader(accessHeader)) 130 | .filter(refreshToken -> refreshToken.startsWith(BEARER)) 131 | .map(refreshToken -> refreshToken.replace(BEARER, "")); 132 | } 133 | 134 | /** 135 | * AccessToken에서 Email 추출 136 | * 추출 전에 JWT.require()로 검증기 생성 137 | * verify로 AceessToken 검증 후 138 | * 유효하다면 getClaim()으로 이메일 추출 139 | * 유효하지 않다면 빈 Optional 객체 반환 140 | */ 141 | public Optional extractEmail(String accessToken) { 142 | try { 143 | // 토큰 유효성 검사하는 데에 사용할 알고리즘이 있는 JWT verifier builder 반환 144 | return Optional.ofNullable(JWT.require(Algorithm.HMAC512(secretKey)) 145 | .build() // 반환된 빌더로 JWT verifier 생성 146 | .verify(accessToken) // accessToken을 검증하고 유효하지 않다면 예외 발생 147 | .getClaim(EMAIL_CLAIM) // claim(Emial) 가져오기 148 | .asString()); 149 | } catch (Exception e) { 150 | log.error("액세스 토큰이 유효하지 않습니다."); 151 | // throw new RestApiException(TokenErrorCode.INVALID_TOKEN); 152 | return Optional.empty(); 153 | } 154 | } 155 | 156 | /** 157 | * AccessToken 헤더 설정 158 | */ 159 | public void setAccessTokenHeader(HttpServletResponse response, String accessToken) { 160 | String bearerAccessToken = "Bearer " + accessToken; 161 | response.setHeader(accessHeader, bearerAccessToken); 162 | } 163 | 164 | /** 165 | * RefreshToken 헤더 설정 166 | */ 167 | public void setRefreshTokenHeader(HttpServletResponse response, String refreshToken) { 168 | String bearerRefreshToken = "Bearer " + refreshToken; 169 | response.setHeader(refreshHeader, bearerRefreshToken); 170 | } 171 | 172 | /** 173 | * RefreshToken DB 저장(업데이트) 174 | */ 175 | public void updateRefreshToken(String email, String refreshToken) { 176 | try { 177 | memberRepository.findByEmail(email) 178 | .ifPresentOrElse( 179 | user -> user.updateRefreshToken(refreshToken), 180 | () -> new RestApiException(MemberErrorCode.MEMBER_NOT_FOUND) 181 | ); 182 | } catch (Exception e) { 183 | log.error("해당 멤버를 찾을 수 없어 리프레시 토큰을 업데이트 할 수 없습니다. {}", e.getMessage()); 184 | } 185 | } 186 | 187 | public boolean isTokenValid(String token) { 188 | try { 189 | log.info("토큰의 value 입니다. {}", token); 190 | JWT.require(Algorithm.HMAC512(secretKey)).build().verify(token); 191 | return true; 192 | } catch (Exception e) { 193 | log.info("유효하지 않은 토큰입니다. {}", e.getMessage()); 194 | return false; 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/test/java/com/challenge/chat/domain/member/controller/MemberControllerTest.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat.domain.member.controller; 2 | // 3 | // import static org.assertj.core.api.Assertions.*; 4 | // import static org.mockito.BDDMockito.*; 5 | // import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 6 | // import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 7 | // 8 | // import java.util.ArrayList; 9 | // import java.util.List; 10 | // import java.util.Map; 11 | // 12 | // import org.junit.jupiter.api.DisplayName; 13 | // import org.junit.jupiter.api.Test; 14 | // import org.springframework.beans.factory.annotation.Autowired; 15 | // import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 16 | // import org.springframework.boot.test.mock.mockito.MockBean; 17 | // import org.springframework.data.jpa.mapping.JpaMetamodelMappingContext; 18 | // import org.springframework.security.test.context.support.WithMockUser; 19 | // import org.springframework.test.web.servlet.MockMvc; 20 | // import org.springframework.test.web.servlet.MvcResult; 21 | // 22 | // import com.challenge.chat.domain.chat.entity.MemberChatRoom; 23 | // import com.challenge.chat.domain.member.constant.MemberRole; 24 | // import com.challenge.chat.domain.member.constant.SocialType; 25 | // import com.challenge.chat.domain.member.dto.MemberDto; 26 | // import com.challenge.chat.domain.member.entity.Member; 27 | // import com.challenge.chat.domain.member.service.MemberService; 28 | // import com.fasterxml.jackson.core.JsonProcessingException; 29 | // import com.fasterxml.jackson.core.type.TypeReference; 30 | // import com.fasterxml.jackson.databind.ObjectMapper; 31 | // import com.jayway.jsonpath.JsonPath; 32 | // 33 | // @WithMockUser(username = "email") 34 | // @WebMvcTest(MemberController.class) 35 | // @MockBean(JpaMetamodelMappingContext.class) 36 | // class MemberControllerTest { 37 | // 38 | // @Autowired 39 | // MockMvc mockMvc; 40 | // 41 | // @Autowired 42 | // ObjectMapper objectMapper; 43 | // 44 | // @MockBean 45 | // MemberService memberService; 46 | // 47 | // @Test 48 | // @DisplayName("멤버 리스트 조회 서비스 호출 확인") 49 | // void getMemberList() throws Exception { 50 | // //given 51 | // 52 | // //when 53 | // mockMvc.perform(get("/users")) 54 | // .andExpect(status().isOk()) 55 | // .andReturn(); 56 | // 57 | // //then 58 | // verify(memberService, times(1)).getMemberList(); 59 | // } 60 | // @Test 61 | // @DisplayName("멤버 리스트 조회 서비스 호출 성공: JSON 확인") 62 | // void getMemberListJSON() throws Exception { 63 | // //given 64 | // List memberDtoList = new ArrayList<>(); 65 | // MemberDto memberDto1 = MemberDto.from(setMember(1L, "email1")); 66 | // MemberDto memberDto2 = MemberDto.from(setMember(2L, "email2")); 67 | // MemberDto memberDto3 = MemberDto.from(setMember(3L, "email3")); 68 | // memberDtoList.add(memberDto1); 69 | // memberDtoList.add(memberDto2); 70 | // memberDtoList.add(memberDto3); 71 | // 72 | // given(memberService.getMemberList()).willReturn(memberDtoList); 73 | // 74 | // //when, then 75 | // MvcResult result =mockMvc.perform(get("/users")) 76 | // .andExpect(status().isOk()) 77 | // .andExpect(jsonPath("$.length()").value(3)) 78 | // .andReturn(); 79 | // 80 | // String response = result.getResponse().getContentAsString(); 81 | // List resultHashMap = JsonPath.read(response, "$.[*]"); 82 | // List resultList = toMemberDto(resultHashMap); 83 | // 84 | // for (int i = 0; i < resultList.size(); i++) { 85 | // assertThat(resultList.get(i).getId()).isEqualTo(memberDtoList.get(i).getId()); 86 | // assertThat(resultList.get(i).getNickname()).isEqualTo(memberDtoList.get(i).getNickname()); 87 | // assertThat(resultList.get(i).getEmail()).isEqualTo(memberDtoList.get(i).getEmail()); 88 | // assertThat(resultList.get(i).getImageUrl()).isEqualTo(memberDtoList.get(i).getImageUrl()); 89 | // } 90 | // } 91 | // 92 | // @Test 93 | // @DisplayName("멤버 email 조회 서비스 호출 확인") 94 | // void getMemberByEmail() throws Exception { 95 | // //given 96 | // String email = "email"; 97 | // 98 | // //when 99 | // mockMvc.perform(get("/users/myinfo")) 100 | // .andExpect(status().isOk()) 101 | // .andReturn(); 102 | // 103 | // //then 104 | // verify(memberService, times(1)).getMemberByEmail(email); 105 | // } 106 | // 107 | // @Test 108 | // @DisplayName("멤버 email 조회 서비스 호출 성공: JSON 확인") 109 | // void getMemberByEmailJSON() throws Exception { 110 | // //given 111 | // String user = "email"; 112 | // MemberDto memberDto = MemberDto.from(setMember(1L, user)); 113 | // given(memberService.getMemberByEmail(user)).willReturn(memberDto); 114 | // 115 | // //when, then 116 | // MvcResult result =mockMvc.perform(get("/users/myinfo")) 117 | // .andExpect(status().isOk()) 118 | // .andReturn(); 119 | // 120 | // String response = result.getResponse().getContentAsString(); 121 | // Map dataString = JsonPath.parse(response).read("$"); 122 | // String body = toJson(dataString); 123 | // MemberDto resultMemberDto = toMemberDto(body); 124 | // 125 | // assertThat(resultMemberDto.getId()).isEqualTo(memberDto.getId()); 126 | // assertThat(resultMemberDto.getNickname()).isEqualTo(memberDto.getNickname()); 127 | // assertThat(resultMemberDto.getEmail()).isEqualTo(memberDto.getEmail()); 128 | // assertThat(resultMemberDto.getImageUrl()).isEqualTo(memberDto.getImageUrl()); 129 | // } 130 | // 131 | // @Test 132 | // @DisplayName("멤버 id 조회 서비스 호출 확인") 133 | // void getMemberByUserId() throws Exception { 134 | // //given 135 | // long userId = 1L; 136 | // //when 137 | // mockMvc.perform(get("/users/" + userId)) 138 | // .andExpect(status().isOk()) 139 | // .andReturn(); 140 | // 141 | // //then 142 | // verify(memberService, times(1)).getMemberByUserId(userId); 143 | // } 144 | // 145 | // @Test 146 | // @DisplayName("멤버 id 조회 서비스 호출 성공: JSON 확인") 147 | // void getMemberByUserIdJSON() throws Exception { 148 | // //given 149 | // long userId = 1L; 150 | // MemberDto memberDto = MemberDto.from(setMember(1L, "email")); 151 | // given(memberService.getMemberByUserId(userId)).willReturn(memberDto); 152 | // 153 | // //when, then 154 | // MvcResult result =mockMvc.perform(get("/users/"+userId)) 155 | // .andExpect(status().isOk()) 156 | // .andReturn(); 157 | // 158 | // String response = result.getResponse().getContentAsString(); 159 | // Map dataString = JsonPath.parse(response).read("$"); 160 | // String body = toJson(dataString); 161 | // MemberDto resultMemberDto = toMemberDto(body); 162 | // 163 | // assertThat(resultMemberDto.getId()).isEqualTo(memberDto.getId()); 164 | // assertThat(resultMemberDto.getNickname()).isEqualTo(memberDto.getNickname()); 165 | // assertThat(resultMemberDto.getEmail()).isEqualTo(memberDto.getEmail()); 166 | // assertThat(resultMemberDto.getImageUrl()).isEqualTo(memberDto.getImageUrl()); 167 | // } 168 | // 169 | // private Member setMember(Long id, String email) { 170 | // List roomList = new ArrayList<>(); 171 | // return new Member(id, email, "password", "nickname", 172 | // "imagerUrl", MemberRole.USER, SocialType.GOOGLE, 173 | // "socialId", "refreshToken", roomList); 174 | // } 175 | // 176 | // private String toJson(T data) throws JsonProcessingException { 177 | // return objectMapper.writeValueAsString(data); 178 | // } 179 | // 180 | // private MemberDto toMemberDto(String json) throws JsonProcessingException { 181 | // return objectMapper.readValue(json , new TypeReference(){}); 182 | // } 183 | // 184 | // private List toMemberDto(List resultHashMap) throws JsonProcessingException { 185 | // return objectMapper.convertValue(resultHashMap , new TypeReference>(){}); 186 | // } 187 | // } -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.authentication.AuthenticationManager; 6 | import org.springframework.security.authentication.ProviderManager; 7 | import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 10 | import org.springframework.security.config.http.SessionCreationPolicy; 11 | import org.springframework.security.crypto.factory.PasswordEncoderFactories; 12 | import org.springframework.security.crypto.password.PasswordEncoder; 13 | import org.springframework.security.web.SecurityFilterChain; 14 | import org.springframework.security.web.authentication.logout.LogoutFilter; 15 | import org.springframework.web.cors.CorsConfiguration; 16 | import org.springframework.web.cors.CorsConfigurationSource; 17 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 18 | 19 | import com.challenge.chat.domain.member.repository.MemberRepository; 20 | import com.challenge.chat.security.jwt.filter.JwtAuthenticationProcessingFilter; 21 | import com.challenge.chat.security.jwt.service.JwtService; 22 | import com.challenge.chat.security.login.filter.CustomJsonUsernamePasswordAuthenticationFilter; 23 | import com.challenge.chat.security.login.handler.LoginFailureHandler; 24 | import com.challenge.chat.security.login.handler.LoginSuccessHandler; 25 | import com.challenge.chat.security.login.service.LoginService; 26 | import com.challenge.chat.security.oauth.handler.OAuth2LoginFailureHandler; 27 | import com.challenge.chat.security.oauth.handler.OAuth2LoginSuccessHandler; 28 | import com.challenge.chat.security.oauth.service.CustomOAuth2UserService; 29 | import com.fasterxml.jackson.databind.ObjectMapper; 30 | 31 | import lombok.RequiredArgsConstructor; 32 | 33 | /** 34 | * 인증은 CustomJsonUsernamePasswordAuthenticationFilter에서 authenticate()로 인증된 사용자로 처리 35 | * JwtAuthenticationProcessingFilter는 AccessToken, RefreshToken 재발급 36 | */ 37 | @Configuration 38 | @EnableWebSecurity 39 | @RequiredArgsConstructor 40 | public class SecurityConfig { 41 | 42 | // private final LoginService loginService; 43 | private final JwtService jwtService; 44 | private final MemberRepository memberRepository; 45 | private final ObjectMapper objectMapper; 46 | private final OAuth2LoginSuccessHandler oAuth2LoginSuccessHandler; 47 | private final OAuth2LoginFailureHandler oAuth2LoginFailureHandler; 48 | private final CustomOAuth2UserService customOAuth2UserService; 49 | private final LoginService loginService; 50 | 51 | @Bean 52 | public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 53 | http 54 | .formLogin().disable() // FormLogin 사용 X 55 | .httpBasic().disable() // httpBasic 사용 X 56 | .csrf().disable() // csrf 보안 사용 X 57 | .headers().frameOptions().disable() 58 | .and() 59 | 60 | .cors() 61 | .and() 62 | 63 | // 세션 사용하지 않으므로 STATELESS로 설정 64 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 65 | 66 | .and() 67 | 68 | //== URL별 권한 관리 옵션 ==// 69 | .authorizeRequests() 70 | 71 | // 아이콘, css, js 관련 72 | // 기본 페이지, css, image, js 하위 폴더에 있는 자료들은 모두 접근 가능, h2-console에 접근 가능 73 | .antMatchers("/", "/css/**", "/images/**", "/js/**", "/favicon.ico", "/h2-console/**","/users/signup").permitAll() 74 | .antMatchers("/ws-chat/**", "/actuator/**").permitAll() //웹소캣 통신? 75 | .anyRequest().authenticated() // 위의 경로 이외에는 모두 인증된 사용자만 접근 가능 76 | .and() 77 | //== 소셜 로그인 설정 ==// 78 | .oauth2Login() 79 | .successHandler(oAuth2LoginSuccessHandler) // 동의하고 계속하기를 눌렀을 때 Handler 설정 80 | .failureHandler(oAuth2LoginFailureHandler) // 소셜 로그인 실패 시 핸들러 설정 81 | .userInfoEndpoint().userService(customOAuth2UserService); // customUserService 설정 82 | 83 | // 원래 스프링 시큐리티 필터 순서가 LogoutFilter 이후에 로그인 필터 동작 84 | // 따라서, LogoutFilter 이후에 우리가 만든 필터 동작하도록 설정 85 | // 순서 : LogoutFilter -> JwtAuthenticationProcessingFilter -> CustomJsonUsernamePasswordAuthenticationFilter 86 | http.addFilterAfter(customJsonUsernamePasswordAuthenticationFilter(), LogoutFilter.class); 87 | http.addFilterBefore(jwtAuthenticationProcessingFilter(), CustomJsonUsernamePasswordAuthenticationFilter.class); 88 | // http.addFilterAfter(jwtAuthenticationProcessingFilter(), LogoutFilter.class); 89 | 90 | return http.build(); 91 | } 92 | 93 | @Bean 94 | public PasswordEncoder passwordEncoder() { 95 | return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 96 | } 97 | 98 | /** 99 | * AuthenticationManager 설정 후 등록 100 | * PasswordEncoder를 사용하는 AuthenticationProvider 지정 (PasswordEncoder는 위에서 등록한 PasswordEncoder 사용) 101 | * FormLogin(기존 스프링 시큐리티 로그인)과 동일하게 DaoAuthenticationProvider 사용 102 | * UserDetailsService는 커스텀 LoginService로 등록 103 | * 또한, FormLogin과 동일하게 AuthenticationManager로는 구현체인 ProviderManager 사용(return ProviderManager) 104 | * 105 | */ 106 | @Bean 107 | public AuthenticationManager authenticationManager() { 108 | DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); 109 | provider.setPasswordEncoder(passwordEncoder()); 110 | provider.setUserDetailsService(loginService); 111 | return new ProviderManager(provider); 112 | } 113 | 114 | /** 115 | * 로그인 성공 시 호출되는 LoginSuccessJWTProviderHandler 빈 등록 116 | */ 117 | @Bean 118 | public LoginSuccessHandler loginSuccessHandler() { 119 | return new LoginSuccessHandler(jwtService, memberRepository); 120 | } 121 | 122 | /** 123 | * 로그인 실패 시 호출되는 LoginFailureHandler 빈 등록 124 | */ 125 | @Bean 126 | public LoginFailureHandler loginFailureHandler() { 127 | return new LoginFailureHandler(); 128 | } 129 | 130 | /** 131 | * CustomJsonUsernamePasswordAuthenticationFilter 빈 등록 132 | * 커스텀 필터를 사용하기 위해 만든 커스텀 필터를 Bean으로 등록 133 | * setAuthenticationManager(authenticationManager())로 위에서 등록한 AuthenticationManager(ProviderManager) 설정 134 | * 로그인 성공 시 호출할 handler, 실패 시 호출할 handler로 위에서 등록한 handler 설정 135 | */ 136 | @Bean 137 | public CustomJsonUsernamePasswordAuthenticationFilter customJsonUsernamePasswordAuthenticationFilter() { 138 | CustomJsonUsernamePasswordAuthenticationFilter customJsonUsernamePasswordLoginFilter 139 | = new CustomJsonUsernamePasswordAuthenticationFilter(objectMapper); 140 | customJsonUsernamePasswordLoginFilter.setAuthenticationManager(authenticationManager()); 141 | customJsonUsernamePasswordLoginFilter.setAuthenticationSuccessHandler(loginSuccessHandler()); 142 | customJsonUsernamePasswordLoginFilter.setAuthenticationFailureHandler(loginFailureHandler()); 143 | return customJsonUsernamePasswordLoginFilter; 144 | } 145 | @Bean 146 | public JwtAuthenticationProcessingFilter jwtAuthenticationProcessingFilter() { 147 | JwtAuthenticationProcessingFilter jwtAuthenticationFilter = new JwtAuthenticationProcessingFilter(jwtService, 148 | memberRepository); 149 | return jwtAuthenticationFilter; 150 | } 151 | 152 | @Bean 153 | public CorsConfigurationSource corsConfigurationSource() { 154 | 155 | CorsConfiguration config = new CorsConfiguration(); 156 | config.addAllowedOrigin("http://localhost:3000"); 157 | config.addAllowedOrigin("http://this.code.s3-website-us-east-1.amazonaws.com"); 158 | config.addExposedHeader("Authorization"); 159 | config.addExposedHeader("Authorization-refresh"); 160 | 161 | config.addAllowedMethod("*"); 162 | config.addAllowedHeader("*"); 163 | config.setAllowCredentials(true); 164 | config.validateAllowCredentials(); 165 | 166 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 167 | source.registerCorsConfiguration("/**", config); 168 | 169 | return source; 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/main/java/com/challenge/chat/security/jwt/filter/JwtAuthenticationProcessingFilter.java: -------------------------------------------------------------------------------- 1 | package com.challenge.chat.security.jwt.filter; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.FilterChain; 6 | import javax.servlet.ServletException; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; 13 | import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper; 14 | import org.springframework.security.core.context.SecurityContextHolder; 15 | import org.springframework.security.core.userdetails.UserDetails; 16 | import org.springframework.web.filter.OncePerRequestFilter; 17 | 18 | import com.challenge.chat.domain.member.entity.Member; 19 | import com.challenge.chat.domain.member.repository.MemberRepository; 20 | import com.challenge.chat.security.jwt.service.JwtService; 21 | import com.challenge.chat.security.jwt.util.PasswordUtil; 22 | 23 | import lombok.RequiredArgsConstructor; 24 | import lombok.extern.slf4j.Slf4j; 25 | 26 | /** 27 | * Jwt 인증 필터 28 | * "/login" 이외의 URI 요청이 왔을 때 처리하는 필터 29 | * 30 | * 기본적으로 사용자는 요청 헤더에 AccessToken만 담아서 요청 31 | * AccessToken 만료 시에만 RefreshToken을 요청 헤더에 AccessToken과 함께 요청 32 | * 33 | * 1. RefreshToken이 없고, AccessToken이 유효한 경우 -> 인증 성공 처리, RefreshToken을 재발급하지는 않는다. 34 | * 2. RefreshToken이 없고, AccessToken이 없거나 유효하지 않은 경우 -> 인증 실패 처리, 403 ERROR 35 | * 3. RefreshToken이 있는 경우 -> DB의 RefreshToken과 비교하여 일치하면 AccessToken 재발급, RefreshToken 재발급(RTR 방식) 36 | * 인증 성공 처리는 하지 않고 실패 처리 37 | * 38 | */ 39 | @RequiredArgsConstructor 40 | @Slf4j 41 | public class JwtAuthenticationProcessingFilter extends OncePerRequestFilter { 42 | 43 | private static final String NO_CHECK_URL_LOGIN = "/login"; // "/login"으로 들어오는 요청은 Filter 작동 X 44 | private static final String NO_CHECK_URL_SIGNUP = "/users/signup"; // "/login"으로 들어오는 요청은 Filter 작동 X 45 | 46 | private final JwtService jwtService; 47 | private final MemberRepository memberRepository; 48 | 49 | private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper(); 50 | 51 | @Override 52 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws 53 | ServletException, 54 | IOException, 55 | ServletException { 56 | 57 | if (request.getRequestURI().equals(NO_CHECK_URL_LOGIN) || request.getRequestURI().equals(NO_CHECK_URL_SIGNUP)) { 58 | filterChain.doFilter(request, response); // "/login" 요청이 들어오면, 다음 필터 호출 59 | return; // return으로 이후 현재 필터 진행 막기 (안해주면 아래로 내려가서 계속 필터 진행시킴) 60 | } 61 | 62 | // 사용자 요청 헤더에서 RefreshToken 추출 63 | // -> RefreshToken이 없거나 유효하지 않다면(DB에 저장된 RefreshToken과 다르다면) null을 반환 64 | // 사용자의 요청 헤더에 RefreshToken이 있는 경우는, AccessToken이 만료되어 요청한 경우밖에 없다. 65 | // 따라서, 위의 경우를 제외하면 추출한 refreshToken은 모두 null 66 | // 내 한 줄 정리: 유효한 refresh token이 아니라면 null로 만들기 67 | log.info("리프레시 토큰 유효성 검사"); 68 | String refreshToken = jwtService.extractRefreshToken(request) 69 | .filter(jwtService::isTokenValid) 70 | .orElse(null); 71 | 72 | // 리프레시 토큰이 요청 헤더에 존재했다면, 사용자가 AccessToken이 만료되어서 73 | // RefreshToken까지 보낸 것이므로 리프레시 토큰이 DB의 리프레시 토큰과 일치하는지 판단 후, 74 | // 일치한다면 AccessToken을 재발급해준다. 75 | if (refreshToken != null) { 76 | checkRefreshTokenAndReIssueAccessToken(response, refreshToken); 77 | // jwtResponseHandler(response, TokenErrorCode.ISSUED_ACCESS_TOKEN); 78 | return; // RefreshToken을 보낸 경우에는 AccessToken을 재발급 하고 인증 처리는 하지 않게 하기위해 바로 return으로 필터 진행 막기 79 | } 80 | 81 | // RefreshToken이 없거나 유효하지 않다면, AccessToken을 검사하고 인증을 처리하는 로직 수행 82 | // AccessToken이 없거나 유효하지 않다면, 인증 객체가 담기지 않은 상태로 다음 필터로 넘어가기 때문에 403 에러 발생 83 | // AccessToken이 유효하다면, 인증 객체가 담긴 상태로 다음 필터로 넘어가기 때문에 인증 성공 84 | log.info("액세스 토큰 유효성 검사"); 85 | if (refreshToken == null) { 86 | checkAccessTokenAndAuthentication(request, response, filterChain); 87 | } 88 | } 89 | 90 | /** 91 | * [리프레시 토큰으로 유저 정보 찾기 & 액세스 토큰/리프레시 토큰 재발급 메소드] 92 | * 파라미터로 들어온 헤더에서 추출한 리프레시 토큰으로 DB에서 유저를 찾고, 해당 유저가 있다면 93 | * JwtService.createAccessToken()으로 AccessToken 생성, 94 | * reIssueRefreshToken()로 리프레시 토큰 재발급 & DB에 리프레시 토큰 업데이트 메소드 호출 95 | * 그 후 JwtService.sendAccessTokenAndRefreshToken()으로 응답 헤더에 보내기 96 | */ 97 | public void checkRefreshTokenAndReIssueAccessToken(HttpServletResponse response, String refreshToken) { 98 | memberRepository.findByRefreshToken(refreshToken) 99 | .ifPresent(member -> { 100 | String reIssuedRefreshToken = reIssueRefreshToken(member); 101 | jwtService.sendAccessAndRefreshToken(response, jwtService.createAccessToken(member.getEmail()), 102 | reIssuedRefreshToken); 103 | }); 104 | } 105 | 106 | /** 107 | * [리프레시 토큰 재발급 & DB에 리프레시 토큰 업데이트 메소드] 108 | * jwtService.createRefreshToken()으로 리프레시 토큰 재발급 후 109 | * DB에 재발급한 리프레시 토큰 업데이트 후 Flush 110 | */ 111 | private String reIssueRefreshToken(Member member) { 112 | String reIssuedRefreshToken = jwtService.createRefreshToken(); 113 | member.updateRefreshToken(reIssuedRefreshToken); 114 | memberRepository.save(member); 115 | return reIssuedRefreshToken; 116 | } 117 | 118 | /** 119 | * [액세스 토큰 체크 & 인증 처리 메소드] 120 | * request에서 extractAccessToken()으로 액세스 토큰 추출 후, isTokenValid()로 유효한 토큰인지 검증 121 | * 유효한 토큰이면, 액세스 토큰에서 extractEmail로 Email을 추출한 후 findByEmail()로 해당 이메일을 사용하는 유저 객체 반환 122 | * 그 유저 객체를 saveAuthentication()으로 인증 처리하여 123 | * 인증 허가 처리된 객체를 SecurityContextHolder에 담기 124 | * 그 후 다음 인증 필터로 진행 125 | */ 126 | public void checkAccessTokenAndAuthentication(HttpServletRequest request, HttpServletResponse response, 127 | FilterChain filterChain) throws ServletException, IOException { 128 | log.info("checkAccessTokenAndAuthentication() 호출"); 129 | log.info("request getHeader 값 입니다. {}", request.getHeader("Authorization")); 130 | 131 | jwtService.extractAccessToken(request) 132 | .filter(jwtService::isTokenValid) 133 | .ifPresent(accessToken -> jwtService.extractEmail(accessToken) 134 | .ifPresent(email -> memberRepository.findByEmail(email) 135 | .ifPresent(this::saveAuthentication))); 136 | 137 | filterChain.doFilter(request, response); 138 | // jwtResponseHandler(response, TokenErrorCode.INVALID_TOKEN); 139 | } 140 | 141 | /** 142 | * [인증 허가 메소드] 143 | * 파라미터의 유저 : 우리가 만든 회원 객체 / 빌더의 유저 : UserDetails의 User 객체 144 | * 145 | * new UsernamePasswordAuthenticationToken()로 인증 객체인 Authentication 객체 생성 146 | * UsernamePasswordAuthenticationToken의 파라미터 147 | * 1. 위에서 만든 UserDetailsUser 객체 (유저 정보) 148 | * 2. credential(보통 비밀번호로, 인증 시에는 보통 null로 제거) 149 | * 3. Collection < ? extends GrantedAuthority>로, 150 | * UserDetails의 User 객체 안에 Set authorities이 있어서 getter로 호출한 후에, 151 | * new NullAuthoritiesMapper()로 GrantedAuthoritiesMapper 객체를 생성하고 mapAuthorities()에 담기 152 | * 153 | * SecurityContextHolder.getContext()로 SecurityContext를 꺼낸 후, 154 | * setAuthentication()을 이용하여 위에서 만든 Authentication 객체에 대한 인증 허가 처리 155 | */ 156 | public void saveAuthentication(Member myUser) { 157 | String password = myUser.getPassword(); 158 | if (password == null) { // 소셜 로그인 유저의 비밀번호 임의로 설정 하여 소셜 로그인 유저도 인증 되도록 설정 159 | password = PasswordUtil.generateRandomPassword(); 160 | } 161 | 162 | UserDetails userDetailsUser = org.springframework.security.core.userdetails.User.builder() 163 | .username(myUser.getEmail()) 164 | .password(password) 165 | .roles(myUser.getRole().name()) 166 | .build(); 167 | 168 | Authentication authentication = 169 | new UsernamePasswordAuthenticationToken(userDetailsUser, null, 170 | authoritiesMapper.mapAuthorities(userDetailsUser.getAuthorities())); 171 | 172 | SecurityContextHolder.getContext().setAuthentication(authentication); 173 | } 174 | 175 | // public void jwtResponseHandler(HttpServletResponse response, ErrorCode errorCode) { 176 | // log.error("jwtResponseHandler 에러/응답을 처리."); 177 | // 178 | // response.setStatus(errorCode.getHttpStatus().value()); 179 | // response.setContentType("application/json"); 180 | // try { 181 | // String json = new ObjectMapper() 182 | // .writeValueAsString(new ErrorResponse( 183 | // errorCode.name(), 184 | // errorCode.getHttpStatus().toString(), 185 | // errorCode.getMessage())); 186 | // response.getWriter().write(json); 187 | // } catch (Exception e) { 188 | // log.error(e.getMessage()); 189 | // } 190 | // } 191 | } 192 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /src/test/java/com/challenge/chat/domain/chat/service/ChatServiceTest.java: -------------------------------------------------------------------------------- 1 | // package com.challenge.chat.domain.chat.service; 2 | // 3 | // import com.challenge.chat.domain.chat.dto.ChatDto; 4 | // import com.challenge.chat.domain.chat.dto.ChatRoomDto; 5 | // import com.challenge.chat.domain.chat.dto.EnterUserDto; 6 | // import com.challenge.chat.domain.chat.entity.Chat; 7 | // import com.challenge.chat.domain.chat.entity.ChatRoom; 8 | // import com.challenge.chat.domain.chat.entity.MemberChatRoom; 9 | // import com.challenge.chat.domain.chat.entity.MessageType; 10 | // import com.challenge.chat.domain.chat.repository.ChatRepository; 11 | // import com.challenge.chat.domain.chat.repository.ChatRoomRepository; 12 | // import com.challenge.chat.domain.chat.repository.MemberChatRoomRepository; 13 | // import com.challenge.chat.domain.member.constant.MemberRole; 14 | // import com.challenge.chat.domain.member.constant.SocialType; 15 | // import com.challenge.chat.domain.member.entity.Member; 16 | // import com.challenge.chat.domain.member.service.MemberService; 17 | // import com.challenge.chat.exception.RestApiException; 18 | // import com.challenge.chat.exception.dto.ChatErrorCode; 19 | // import org.junit.jupiter.api.DisplayName; 20 | // import org.junit.jupiter.api.Test; 21 | // import org.junit.jupiter.api.extension.ExtendWith; 22 | // import org.mockito.ArgumentCaptor; 23 | // import org.mockito.InjectMocks; 24 | // import org.mockito.Mock; 25 | // import org.mockito.junit.jupiter.MockitoExtension; 26 | // import org.mockito.junit.jupiter.MockitoSettings; 27 | // import org.mockito.quality.Strictness; 28 | // import org.springframework.messaging.simp.SimpMessageHeaderAccessor; 29 | // 30 | // import java.util.*; 31 | // 32 | // import static org.assertj.core.api.Assertions.assertThat; 33 | // import static org.assertj.core.api.Assertions.assertThatThrownBy; 34 | // import static org.mockito.BDDMockito.*; 35 | // 36 | // @ExtendWith(MockitoExtension.class) 37 | // @MockitoSettings(strictness = Strictness.LENIENT) 38 | // class ChatServiceTest { 39 | // @Mock 40 | // private ChatRepository chatRepository; 41 | // @Mock 42 | // private ChatRoomRepository chatRoomRepository; 43 | // @Mock 44 | // private MemberChatRoomRepository memberChatRoomRepository; 45 | // 46 | // @InjectMocks 47 | // private ChatService chatService; 48 | // @Mock 49 | // private MemberService memberService; 50 | // 51 | // @Test 52 | // @DisplayName("채팅방 조회 성공") 53 | // void showRoomList() { 54 | // //given 55 | // List chatRooms = new ArrayList<>(); 56 | // ChatRoom room1 = ChatRoom.of("room UUID1", "room name1"); 57 | // ChatRoom room2 = ChatRoom.of("room UUID2", "room name2"); 58 | // ChatRoom room3 = ChatRoom.of("room UUID3", "room name3"); 59 | // chatRooms.add(room1); 60 | // chatRooms.add(room2); 61 | // chatRooms.add(room3); 62 | // given(chatRoomRepository.findAll()).willReturn(chatRooms); 63 | // 64 | // //when 65 | // List chatRoomDtoList = chatService.showRoomList(); 66 | // 67 | // //then 68 | // for (int i = 0; i < chatRoomDtoList.size(); i++) { 69 | // assertThat(chatRoomDtoList.get(i).getId()).isEqualTo(chatRooms.get(i).getId()); 70 | // assertThat(chatRoomDtoList.get(i).getRoomId()).isEqualTo(chatRooms.get(i).getRoomId()); 71 | // assertThat(chatRoomDtoList.get(i).getRoomName()).isEqualTo(chatRooms.get(i).getRoomName()); 72 | // } 73 | // } 74 | // 75 | // @Test 76 | // @DisplayName("채팅방 생성 및 저장 성공") 77 | // void createChatRoom() { 78 | // //given 79 | // ChatRoomDto chatRoomDto = new ChatRoomDto(1L, "room UUID1", "room name1"); 80 | // 81 | // //when 82 | // String result = chatService.createChatRoom(chatRoomDto); 83 | // 84 | // //then 85 | // assertThat(result).isEqualTo("Successfully created chat room"); 86 | // // assertThat(result.getData()).isNotBlank(); 87 | // } 88 | // 89 | // @Test 90 | // @DisplayName("채팅방 입장 성공: 이미 채팅방이 존재") 91 | // void enterChatRoom() { 92 | // //given 93 | // Long memberId = 1L; 94 | // ChatDto chatDto = setChatDto(); 95 | // Member member = setMember(memberId); 96 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 97 | // 98 | // //given Accessor 만들기 99 | // Map attributes = new HashMap<>(); 100 | // SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); 101 | // accessor.setSessionAttributes(attributes); 102 | // 103 | // //given @Mock Stubbing 104 | // given(chatRoomRepository.findByRoomId(chatDto.getRoomId())).willReturn(Optional.of(chatRoom)); 105 | // given(memberService.findMemberByEmail(chatDto.getUserId())).willReturn(member); 106 | // given(memberChatRoomRepository.findByMemberAndRoom(member, chatRoom)).willReturn(Optional.of(new MemberChatRoom(chatRoom, member))); 107 | // 108 | // //when 109 | // ChatDto resultChatDto = chatService.enterChatRoom(chatDto, accessor); 110 | // 111 | // //then 112 | // assertThat(chatDto).isEqualTo(resultChatDto); 113 | // assertThat(chatDto.getMessage()).isEqualTo(chatDto.getSender() + "님 입장!! ο(=•ω<=)ρ⌒☆"); 114 | // } 115 | // 116 | // @Test 117 | // @DisplayName("채팅방 입장 성공: 채팅방 새로 생성") 118 | // void enterChatRoom2() { 119 | // //given 120 | // ChatDto chatDto = setChatDto(); 121 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 122 | // Member member = setMember(); 123 | // 124 | // //given Accessor 만들기 125 | // Map attributes = new HashMap<>(); 126 | // SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); 127 | // accessor.setSessionAttributes(attributes); 128 | // 129 | // //given @Mock Stubbing 130 | // given(chatRoomRepository.findByRoomId(chatDto.getRoomId())).willReturn(Optional.of(chatRoom)); 131 | // given(memberService.findMemberByEmail(chatDto.getUserId())).willReturn(member); 132 | // given(memberChatRoomRepository.findByMemberAndRoom(member, chatRoom)).willReturn(Optional.empty()); 133 | // 134 | // //when 135 | // ChatDto resultChatDto = chatService.enterChatRoom(chatDto, accessor); 136 | // 137 | // //then 138 | // assertThat(chatDto).isEqualTo(resultChatDto); 139 | // assertThat(chatDto.getMessage()).isEqualTo(chatDto.getSender() + "님 입장!! ο(=•ω<=)ρ⌒☆"); 140 | // } 141 | // 142 | // @Test 143 | // @DisplayName("채팅방 입장 실패: chatService 호출 실패") 144 | // void enterChatRoomFail1() { 145 | // //given 146 | // ChatDto chatDto = setChatDto(); 147 | // 148 | // //given Accessor 만들기 149 | // Map attributes = new HashMap<>(); 150 | // SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); 151 | // accessor.setSessionAttributes(attributes); 152 | // 153 | // //given @Mock Stubbing 154 | // given(chatRoomRepository.findByRoomId(chatDto.getRoomId())).willReturn(Optional.empty()); 155 | // 156 | // //when, then 157 | // assertThatThrownBy(() -> chatService.enterChatRoom(chatDto, accessor)) 158 | // .isInstanceOf(RestApiException.class); 159 | // } 160 | // 161 | // @Test 162 | // @DisplayName("채팅방 입장 실패: memberService 호출 실패") 163 | // void enterChatRoomFail2() { 164 | // //given 165 | // ChatDto chatDto = setChatDto(); 166 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 167 | // 168 | // //given Accessor 만들기 169 | // Map attributes = new HashMap<>(); 170 | // SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); 171 | // accessor.setSessionAttributes(attributes); 172 | // 173 | // //given @Mock Stubbing 174 | // given(chatRoomRepository.findByRoomId(chatDto.getRoomId())).willReturn(Optional.of(chatRoom)); 175 | // given(memberService.findMemberByEmail(chatDto.getUserId())).willThrow(NoSuchElementException.class); 176 | // 177 | // //when, then 178 | // assertThatThrownBy(() -> chatService.enterChatRoom(chatDto, accessor)) 179 | // .isInstanceOf(NoSuchElementException.class); 180 | // } 181 | // 182 | // @Test 183 | // @DisplayName("채팅방 나가기 성공") 184 | // void disconnectChatRoom() { 185 | // //given 186 | // String roomId = "roomId"; 187 | // String nickName = "nickName"; 188 | // String userId = "userId"; 189 | // 190 | // //given Accessor 만들기 191 | // Map attributes = new HashMap<>(); 192 | // SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(); 193 | // accessor.setSessionAttributes(attributes); 194 | // Objects.requireNonNull( 195 | // accessor.getSessionAttributes()).put("roomId", roomId); 196 | // accessor.getSessionAttributes().put("nickName", nickName); 197 | // accessor.getSessionAttributes().put("userId", userId); 198 | // 199 | // //when 200 | // ChatDto resultChatDto = chatService.leaveChatRoom(accessor); 201 | // 202 | // //then 203 | // assertThat(resultChatDto.getRoomId()).isEqualTo(roomId); 204 | // assertThat(resultChatDto.getSender()).isEqualTo(nickName); 205 | // assertThat(resultChatDto.getUserId()).isEqualTo(userId); 206 | // assertThat(resultChatDto.getMessage()).isEqualTo(nickName + "님 퇴장!! ヽ(*。>Д<)o゜"); 207 | // } 208 | // 209 | // @Test 210 | // @DisplayName("채팅방 메세지 조회 성공") 211 | // void viewChat() { 212 | // //given 213 | // Member member = setMember(); 214 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 215 | // List chatList = new ArrayList<>(); 216 | // List chatDtoList = new ArrayList<>(); 217 | // 218 | // //given @Mock Stubbing 219 | // given(chatRoomRepository.findByRoomId(chatRoom.getRoomId())).willReturn(Optional.of(chatRoom)); 220 | // given(memberService.findMemberByEmail(member.getEmail())).willReturn(member); 221 | // given(chatRepository.findByRoomId(chatRoom.getRoomId())).willReturn(chatList); 222 | // 223 | // 224 | // //when 225 | // EnterUserDto resultUserDto = chatService.viewChat(chatRoom.getRoomId(), member.getEmail()); 226 | // 227 | // //then 228 | // assertThat(resultUserDto.getSender()).isEqualTo(member.getNickname()); 229 | // assertThat(resultUserDto.getUserId()).isEqualTo(member.getEmail()); 230 | // assertThat(resultUserDto.getRoomId()).isEqualTo(chatRoom.getRoomId()); 231 | // assertThat(resultUserDto.getChatList()).isEqualTo(chatDtoList); 232 | // } 233 | // 234 | // @Test 235 | // @DisplayName("채팅방 메세지 조회 실패: 채팅방 조회 실패") 236 | // void viewChatFail1() { 237 | // //given 238 | // Member member = setMember(); 239 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 240 | // 241 | // //given @Mock Stubbing 242 | // given(chatRoomRepository.findByRoomId(chatRoom.getRoomId())).willReturn(Optional.empty()); 243 | // 244 | // //when, then 245 | // assertThatThrownBy(() -> chatService.viewChat(chatRoom.getRoomId(), member.getEmail())) 246 | // .isInstanceOf(RestApiException.class); 247 | // } 248 | // 249 | // @Test 250 | // @DisplayName("채팅방 메세지 조회 실패: memberService 호출 실패") 251 | // void viewChatFail2() { 252 | // //given 253 | // Member member = setMember(); 254 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 255 | // 256 | // //given @Mock Stubbing 257 | // given(chatRoomRepository.findByRoomId(chatRoom.getRoomId())).willReturn(Optional.of(chatRoom)); 258 | // given(memberService.findMemberByEmail(member.getEmail())).willThrow(NoSuchElementException.class); 259 | // 260 | // //when, then 261 | // assertThatThrownBy(() -> chatService.viewChat(chatRoom.getRoomId(), member.getEmail())) 262 | // .isInstanceOf(NoSuchElementException.class); 263 | // } 264 | // 265 | // @Test 266 | // @DisplayName("채팅 저장하기 성공") 267 | // void sendChatRoom() { 268 | // //given 269 | // Member member = setMember(); 270 | // ChatDto chatDto = setChatDto(); 271 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 272 | // 273 | // //given @Mock Stubbing 274 | // given(chatRoomRepository.findByRoomId(chatDto.getRoomId())).willReturn(Optional.of(chatRoom)); 275 | // given(memberService.findMemberByEmail(chatDto.getUserId())).willReturn(member); 276 | // given(chatRepository.save(any())).willReturn(null); 277 | // 278 | // //when 279 | // chatService.sendChatRoom(chatDto); 280 | // 281 | // //then 282 | // // chatRepository.save() 메서드가 호출될 때 전달된 Chat 객체를 캡쳐 283 | // ArgumentCaptor chatCaptor = ArgumentCaptor.forClass(Chat.class); 284 | // // chatRepository.save() 메서드가 주어진 인자로 한번 호출 되었는지 확인 285 | // verify(chatRepository, times(1)).save(chatCaptor.capture()); 286 | // } 287 | // 288 | // @Test 289 | // @DisplayName("채팅 저장하기 실패: 채팅방 조회 실패") 290 | // void sendChatRoomFail1() { 291 | // //given 292 | // ChatDto chatDto = setChatDto(); 293 | // 294 | // //given @Mock Stubbing 295 | // given(chatRoomRepository.findByRoomId(chatDto.getRoomId())).willReturn(Optional.empty()); 296 | // 297 | // //when, then 298 | // assertThatThrownBy(() -> chatService.sendChatRoom(chatDto)) 299 | // .isInstanceOf(RestApiException.class); 300 | // } 301 | // 302 | // @Test 303 | // @DisplayName("채팅 저장하기 실패: memberService 호출 실패") 304 | // void sendChatRoomFail2() { 305 | // //given 306 | // ChatDto chatDto = setChatDto(); 307 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 308 | // 309 | // //given @Mock Stubbing 310 | // given(chatRoomRepository.findByRoomId(chatDto.getRoomId())).willThrow(new RestApiException(ChatErrorCode.CHATROOM_NOT_FOUND)); 311 | // 312 | // //when, then 313 | // assertThatThrownBy(() -> chatService.sendChatRoom(chatDto)) 314 | // .isInstanceOf(RestApiException.class); 315 | // } 316 | // 317 | // @Test 318 | // @DisplayName("roomId로 채팅방 가져오기 성공") 319 | // void getRoomByRoomId() { 320 | // //given 321 | // ChatRoom chatRoom = ChatRoom.of("room UUID1", "room name1"); 322 | // 323 | // //given @Mock Stubbing 324 | // given(chatRoomRepository.findByRoomId(any())).willReturn(Optional.of(chatRoom)); 325 | // 326 | // //when 327 | // chatService.getRoomByRoomId(chatRoom.getRoomId()); 328 | // 329 | // //then 330 | // verify(chatRoomRepository).findByRoomId(chatRoom.getRoomId()); 331 | // 332 | // } 333 | // 334 | // @Test 335 | // @DisplayName("roomId로 채팅방 가져오기 실패: chatService 호출 실패") 336 | // void getRoomByRoomIdFail() { 337 | // //given 338 | // String roomId = "userId"; 339 | // 340 | // //given @Mock Stubbing 341 | // given(chatRoomRepository.findByRoomId(roomId)).willReturn(Optional.empty()); 342 | // 343 | // //then, when 344 | // assertThatThrownBy(() -> chatService.getRoomByRoomId(roomId)) 345 | // .isInstanceOf(RestApiException.class); 346 | // } 347 | // 348 | // private Member setMember() { 349 | // List roomList = new ArrayList<>(); 350 | // return new Member( 351 | // 1L, "email", "password", "nickname", 352 | // null, MemberRole.USER, SocialType.GOOGLE, 353 | // "socialId", "refreshToken", roomList); 354 | // } 355 | // 356 | // private Member setMember(Long id) { 357 | // List roomList = new ArrayList<>(); 358 | // return new Member(id, "email", "password", "nickname", 359 | // null, MemberRole.USER, SocialType.GOOGLE, 360 | // "socialId", "refreshToken", roomList); 361 | // } 362 | // 363 | // private ChatDto setChatDto() { 364 | // return new ChatDto(MessageType.ENTER, "sender", "userId", "roomId", "message", "date"); 365 | // } 366 | // } --------------------------------------------------------------------------------