commit 7a4f60c842c2aff6f7a73460250ca8f4e1093ff7 Author: ondal Date: Wed Feb 12 21:24:01 2025 +0900 release diff --git a/.gradle/8.4/checksums/checksums.lock b/.gradle/8.4/checksums/checksums.lock new file mode 100644 index 0000000..1948304 Binary files /dev/null and b/.gradle/8.4/checksums/checksums.lock differ diff --git a/.gradle/8.4/checksums/md5-checksums.bin b/.gradle/8.4/checksums/md5-checksums.bin new file mode 100644 index 0000000..3b13af4 Binary files /dev/null and b/.gradle/8.4/checksums/md5-checksums.bin differ diff --git a/.gradle/8.4/checksums/sha1-checksums.bin b/.gradle/8.4/checksums/sha1-checksums.bin new file mode 100644 index 0000000..d01caaa Binary files /dev/null and b/.gradle/8.4/checksums/sha1-checksums.bin differ diff --git a/.gradle/8.4/dependencies-accessors/dependencies-accessors.lock b/.gradle/8.4/dependencies-accessors/dependencies-accessors.lock new file mode 100644 index 0000000..c15a074 Binary files /dev/null and b/.gradle/8.4/dependencies-accessors/dependencies-accessors.lock differ diff --git a/.gradle/8.4/dependencies-accessors/gc.properties b/.gradle/8.4/dependencies-accessors/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/8.4/executionHistory/executionHistory.bin b/.gradle/8.4/executionHistory/executionHistory.bin new file mode 100644 index 0000000..14084aa Binary files /dev/null and b/.gradle/8.4/executionHistory/executionHistory.bin differ diff --git a/.gradle/8.4/executionHistory/executionHistory.lock b/.gradle/8.4/executionHistory/executionHistory.lock new file mode 100644 index 0000000..97d4af2 Binary files /dev/null and b/.gradle/8.4/executionHistory/executionHistory.lock differ diff --git a/.gradle/8.4/fileChanges/last-build.bin b/.gradle/8.4/fileChanges/last-build.bin new file mode 100644 index 0000000..f76dd23 Binary files /dev/null and b/.gradle/8.4/fileChanges/last-build.bin differ diff --git a/.gradle/8.4/fileHashes/fileHashes.bin b/.gradle/8.4/fileHashes/fileHashes.bin new file mode 100644 index 0000000..642cb82 Binary files /dev/null and b/.gradle/8.4/fileHashes/fileHashes.bin differ diff --git a/.gradle/8.4/fileHashes/fileHashes.lock b/.gradle/8.4/fileHashes/fileHashes.lock new file mode 100644 index 0000000..5e52a62 Binary files /dev/null and b/.gradle/8.4/fileHashes/fileHashes.lock differ diff --git a/.gradle/8.4/fileHashes/resourceHashesCache.bin b/.gradle/8.4/fileHashes/resourceHashesCache.bin new file mode 100644 index 0000000..5f118ec Binary files /dev/null and b/.gradle/8.4/fileHashes/resourceHashesCache.bin differ diff --git a/.gradle/8.4/gc.properties b/.gradle/8.4/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 0000000..cc42f52 Binary files /dev/null and b/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/.gradle/buildOutputCleanup/cache.properties b/.gradle/buildOutputCleanup/cache.properties new file mode 100644 index 0000000..99fad32 --- /dev/null +++ b/.gradle/buildOutputCleanup/cache.properties @@ -0,0 +1,2 @@ +#Wed Feb 12 15:21:47 KST 2025 +gradle.version=8.4 diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin new file mode 100644 index 0000000..a0e6f18 Binary files /dev/null and b/.gradle/buildOutputCleanup/outputFiles.bin differ diff --git a/.gradle/file-system.probe b/.gradle/file-system.probe new file mode 100644 index 0000000..c5e6994 Binary files /dev/null and b/.gradle/file-system.probe differ diff --git a/.gradle/vcs-1/gc.properties b/.gradle/vcs-1/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..507bcb4 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..97657e0 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,21 @@ + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..fdc392f --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..49504ef --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..264f470 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules/common/lifesub.common.main.iml b/.idea/modules/common/lifesub.common.main.iml new file mode 100644 index 0000000..0d2c1d2 --- /dev/null +++ b/.idea/modules/common/lifesub.common.main.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules/member/lifesub.member.main.iml b/.idea/modules/member/lifesub.member.main.iml new file mode 100644 index 0000000..e208837 --- /dev/null +++ b/.idea/modules/member/lifesub.member.main.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules/mysub-biz/lifesub.mysub-biz.main.iml b/.idea/modules/mysub-biz/lifesub.mysub-biz.main.iml new file mode 100644 index 0000000..0c5afac --- /dev/null +++ b/.idea/modules/mysub-biz/lifesub.mysub-biz.main.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules/mysub-infra/lifesub.mysub-infra.main.iml b/.idea/modules/mysub-infra/lifesub.mysub-infra.main.iml new file mode 100644 index 0000000..bac25ea --- /dev/null +++ b/.idea/modules/mysub-infra/lifesub.mysub-infra.main.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules/recommend/lifesub.recommend.main.iml b/.idea/modules/recommend/lifesub.recommend.main.iml new file mode 100644 index 0000000..eb1b213 --- /dev/null +++ b/.idea/modules/recommend/lifesub.recommend.main.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..2b63946 --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..d112b81 --- /dev/null +++ b/build.gradle @@ -0,0 +1,62 @@ +plugins { + id 'org.springframework.boot' version '3.4.0' apply false + id 'io.spring.dependency-management' version '1.1.6' apply false + id 'java' +} + +allprojects { + group = 'com.unicorn' + version = '1.0.0' + sourceCompatibility = '21' +} + +subprojects { + apply plugin: 'java' + apply plugin: 'org.springframework.boot' + apply plugin: 'io.spring.dependency-management' + + repositories { + mavenCentral() + } + + dependencies { + + implementation 'org.springframework.boot:spring-boot-starter' + + // Lombok + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + // Test + testImplementation 'org.springframework.boot:spring-boot-starter-test' + } + + test { + useJUnitPlatform() + } +} + +//-- Biz와 common 모듈이 아닌 경우 인프라 관련 라이브러리 추가 +configure(subprojects.findAll { !it.name.endsWith('-biz') && it.name != 'common' }) { + dependencies { + // Spring Boot + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + // data + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + // JWT + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'com.auth0:java-jwt:4.4.0' //JWT unitlity + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + // Swagger + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' + } +} + +//-- Biz와 common 모듈은 일반Jar만 생성하고 실행Jar는 생성되지 않게 함 +configure(subprojects.findAll { it.name.endsWith('-biz') || it.name == 'common' }) { + bootJar.enabled = false + jar.enabled = true +} diff --git a/common/build.gradle b/common/build.gradle new file mode 100644 index 0000000..05eac0d --- /dev/null +++ b/common/build.gradle @@ -0,0 +1,6 @@ +dependencies { + implementation 'com.fasterxml.jackson.core:jackson-databind' + implementation 'jakarta.persistence:jakarta.persistence-api' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'com.google.code.gson:gson' +} diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/aop/LoggingAspect.class b/common/build/classes/java/main/com/unicorn/lifesub/common/aop/LoggingAspect.class new file mode 100644 index 0000000..fdcf1bc Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/aop/LoggingAspect.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/dto/ApiResponse.class b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/ApiResponse.class new file mode 100644 index 0000000..5af5cdd Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/ApiResponse.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenDTO$JwtTokenDTOBuilder.class b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenDTO$JwtTokenDTOBuilder.class new file mode 100644 index 0000000..28578d7 Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenDTO$JwtTokenDTOBuilder.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenDTO.class b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenDTO.class new file mode 100644 index 0000000..6f6dac1 Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenDTO.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenRefreshDTO.class b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenRefreshDTO.class new file mode 100644 index 0000000..54e2d72 Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenRefreshDTO.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenVerifyDTO.class b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenVerifyDTO.class new file mode 100644 index 0000000..62830d4 Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/dto/JwtTokenVerifyDTO.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/entity/BaseTimeEntity.class b/common/build/classes/java/main/com/unicorn/lifesub/common/entity/BaseTimeEntity.class new file mode 100644 index 0000000..7cd57d7 Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/entity/BaseTimeEntity.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/exception/BusinessException.class b/common/build/classes/java/main/com/unicorn/lifesub/common/exception/BusinessException.class new file mode 100644 index 0000000..a27661c Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/exception/BusinessException.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/exception/ErrorCode.class b/common/build/classes/java/main/com/unicorn/lifesub/common/exception/ErrorCode.class new file mode 100644 index 0000000..e9c4184 Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/exception/ErrorCode.class differ diff --git a/common/build/classes/java/main/com/unicorn/lifesub/common/exception/InfraException.class b/common/build/classes/java/main/com/unicorn/lifesub/common/exception/InfraException.class new file mode 100644 index 0000000..c7bc0d1 Binary files /dev/null and b/common/build/classes/java/main/com/unicorn/lifesub/common/exception/InfraException.class differ diff --git a/common/build/libs/common-1.0.0-plain.jar b/common/build/libs/common-1.0.0-plain.jar new file mode 100644 index 0000000..4e1fb1f Binary files /dev/null and b/common/build/libs/common-1.0.0-plain.jar differ diff --git a/common/build/tmp/compileJava/previous-compilation-data.bin b/common/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 0000000..e17ebe0 Binary files /dev/null and b/common/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/common/build/tmp/jar/MANIFEST.MF b/common/build/tmp/jar/MANIFEST.MF new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/common/build/tmp/jar/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/common/src/main/java/com/unicorn/lifesub/common/aop/LoggingAspect.java b/common/src/main/java/com/unicorn/lifesub/common/aop/LoggingAspect.java new file mode 100644 index 0000000..77098fa --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/aop/LoggingAspect.java @@ -0,0 +1,110 @@ +package com.unicorn.lifesub.common.aop; + +import com.google.gson.Gson; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.*; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.Map; + +@Aspect //Disable하려면 리마크 함 +@Component +@Slf4j +@SuppressWarnings("unused") +public class LoggingAspect { + private final Gson gson = new Gson(); + + @Pointcut("execution(* com.unicorn..*.*(..))") + private void loggingPointcut() {} + + @Before("loggingPointcut()") + public void logMethodStart(JoinPoint joinPoint) { + String className = joinPoint.getTarget().getClass().getSimpleName(); + String methodName = joinPoint.getSignature().getName(); + Object[] args = joinPoint.getArgs(); + + String argString = getArgumentString(args); + + log.info("[START] {}.{} - Args: [{}]", className, methodName, argString); + } + + @AfterReturning(pointcut = "loggingPointcut()", returning = "result") + public void logMethodEnd(JoinPoint joinPoint, Object result) { + String className = joinPoint.getTarget().getClass().getSimpleName(); + String methodName = joinPoint.getSignature().getName(); + + String resultString = getResultString(result); + + log.info("[END] {}.{} - Result: {}", className, methodName, resultString); + } + + @AfterThrowing(pointcut = "loggingPointcut()", throwing = "exception") + public void logMethodException(JoinPoint joinPoint, Exception exception) { + String className = joinPoint.getTarget().getClass().getSimpleName(); + String methodName = joinPoint.getSignature().getName(); + log.error("[EXCEPTION] {}.{} - Exception: {}", className, methodName, exception.getMessage()); + } + + private String getArgumentString(Object[] args) { + StringBuilder argString = new StringBuilder(); + + for (Object arg : args) { + if (arg != null) { + if (arg instanceof String || arg instanceof Number || arg instanceof Boolean) { + argString.append(arg).append(", "); + } else if (arg instanceof Collection) { + argString.append(((Collection) arg).size()).append(" elements, "); + } else if (arg instanceof Map) { + argString.append(((Map) arg).size()).append(" entries, "); + } else { + argString.append(arg); + /* + try { + String jsonString = gson.toJson(arg); + argString.append(jsonString).append(", "); + } catch (Exception e) { + log.warn("JSON serialization failed for argument: {}", arg); + argString.append("JSON serialization failed, "); + } + */ + + } + } else { + argString.append("null, "); + } + } + + if (!argString.isEmpty()) { + argString.setLength(argString.length() - 2); + } + + return argString.toString(); + } + + private String getResultString(Object result) { + if (result != null) { + if (result instanceof String || result instanceof Number || result instanceof Boolean) { + return result.toString(); + } else if (result instanceof Collection) { + return ((Collection) result).size() + " elements"; + } else if (result instanceof Map) { + return ((Map) result).size() + " entries"; + } else { + return result.toString(); + /* + try { + return gson.toJson(result); + } catch (Exception e) { + log.warn("JSON serialization failed for result: {}", result); + return "JSON serialization failed"; + } + + */ + } + } else { + return "null"; + } + } +} \ No newline at end of file diff --git a/common/src/main/java/com/unicorn/lifesub/common/dto/ApiResponse.java b/common/src/main/java/com/unicorn/lifesub/common/dto/ApiResponse.java new file mode 100644 index 0000000..0745ca5 --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/dto/ApiResponse.java @@ -0,0 +1,29 @@ +package com.unicorn.lifesub.common.dto; + +import com.unicorn.lifesub.common.exception.ErrorCode; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +public class ApiResponse { + private final int status; + private final String message; + private final T data; + private final LocalDateTime timestamp; + + private ApiResponse(int status, String message, T data) { + this.status = status; + this.message = message; + this.data = data; + this.timestamp = LocalDateTime.now(); + } + + public static ApiResponse success(T data) { + return new ApiResponse<>(200, "Success", data); + } + + public static ApiResponse error(ErrorCode errorCode) { + return new ApiResponse<>(errorCode.getStatus(), errorCode.getMessage(), null); + } +} diff --git a/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenDTO.java b/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenDTO.java new file mode 100644 index 0000000..ddffb26 --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenDTO.java @@ -0,0 +1,14 @@ +package com.unicorn.lifesub.common.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.Getter; + +@Builder +@Getter +@AllArgsConstructor +public class JwtTokenDTO { + private String accessToken; + private String refreshToken; +} \ No newline at end of file diff --git a/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenRefreshDTO.java b/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenRefreshDTO.java new file mode 100644 index 0000000..18f5806 --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenRefreshDTO.java @@ -0,0 +1,10 @@ +package com.unicorn.lifesub.common.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class JwtTokenRefreshDTO { + private String refreshToken; +} diff --git a/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenVerifyDTO.java b/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenVerifyDTO.java new file mode 100644 index 0000000..4a062b2 --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/dto/JwtTokenVerifyDTO.java @@ -0,0 +1,10 @@ +package com.unicorn.lifesub.common.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class JwtTokenVerifyDTO { + private String token; +} diff --git a/common/src/main/java/com/unicorn/lifesub/common/entity/BaseTimeEntity.java b/common/src/main/java/com/unicorn/lifesub/common/entity/BaseTimeEntity.java new file mode 100644 index 0000000..3534395 --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/entity/BaseTimeEntity.java @@ -0,0 +1,21 @@ +package com.unicorn.lifesub.common.entity; + +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@EntityListeners(AuditingEntityListener.class) +@MappedSuperclass +@Getter +public class BaseTimeEntity { + @CreatedDate + private LocalDateTime createdAt; + + @LastModifiedDate + private LocalDateTime updatedAt; +} diff --git a/common/src/main/java/com/unicorn/lifesub/common/exception/BusinessException.java b/common/src/main/java/com/unicorn/lifesub/common/exception/BusinessException.java new file mode 100644 index 0000000..5dbac18 --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/exception/BusinessException.java @@ -0,0 +1,13 @@ +package com.unicorn.lifesub.common.exception; + +import lombok.Getter; + +@Getter +public class BusinessException extends RuntimeException { + private final ErrorCode errorCode; + + public BusinessException(ErrorCode errorCode) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + } +} diff --git a/common/src/main/java/com/unicorn/lifesub/common/exception/ErrorCode.java b/common/src/main/java/com/unicorn/lifesub/common/exception/ErrorCode.java new file mode 100644 index 0000000..2893107 --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/exception/ErrorCode.java @@ -0,0 +1,33 @@ +package com.unicorn.lifesub.common.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public enum ErrorCode { + // Common + INVALID_INPUT_VALUE(400, "Invalid input value"), + INTERNAL_SERVER_ERROR(500, "Internal server error"), + + // Member + MEMBER_NOT_FOUND(404, "Member not found"), + INVALID_CREDENTIALS(401, "Invalid credentials"), + TOKEN_EXPIRED(401, "Token expired"), + SIGNATURE_VERIFICATION_EXCEPTION(20, "서명 검증 실패"), + ALGORITHM_MISMATCH_EXCEPTION(30, "알고리즘 불일치"), + INVALID_CLAIM_EXCEPTION(40, "유효하지 않은 클레임"), + + // Subscription + SUBSCRIPTION_NOT_FOUND(404, "Subscription not found"), + ALREADY_SUBSCRIBED(400, "Already subscribed to this service"), + + // Recommend + NO_SPENDING_DATA(404, "No spending data found"), + + // UnDefined + UNDIFINED_ERROR(0, "정의되지 않은 에러"); + + private final int status; + private final String message; +} diff --git a/common/src/main/java/com/unicorn/lifesub/common/exception/InfraException.java b/common/src/main/java/com/unicorn/lifesub/common/exception/InfraException.java new file mode 100644 index 0000000..1bee416 --- /dev/null +++ b/common/src/main/java/com/unicorn/lifesub/common/exception/InfraException.java @@ -0,0 +1,13 @@ +package com.unicorn.lifesub.common.exception; + +import lombok.Getter; + +@Getter +public class InfraException extends RuntimeException { + private final ErrorCode errorCode; + + public InfraException(ErrorCode errorCode) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..3fa8f86 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/member/build.gradle b/member/build.gradle new file mode 100644 index 0000000..5057beb --- /dev/null +++ b/member/build.gradle @@ -0,0 +1,7 @@ +dependencies { + implementation project(':common') + runtimeOnly 'org.postgresql:postgresql' +} +bootJar { + archiveFileName = "member.jar" +} diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/MemberApplication.class b/member/build/classes/java/main/com/unicorn/lifesub/member/MemberApplication.class new file mode 100644 index 0000000..075032a Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/MemberApplication.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/config/SecurityConfig.class b/member/build/classes/java/main/com/unicorn/lifesub/member/config/SecurityConfig.class new file mode 100644 index 0000000..a77f430 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/config/SecurityConfig.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/config/SwaggerConfig.class b/member/build/classes/java/main/com/unicorn/lifesub/member/config/SwaggerConfig.class new file mode 100644 index 0000000..7360ce7 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/config/SwaggerConfig.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/CustomUserDetailsService.class b/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/CustomUserDetailsService.class new file mode 100644 index 0000000..12a3864 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/CustomUserDetailsService.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/JwtAuthenticationFilter.class b/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/JwtAuthenticationFilter.class new file mode 100644 index 0000000..325b385 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/JwtAuthenticationFilter.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/JwtTokenProvider.class b/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/JwtTokenProvider.class new file mode 100644 index 0000000..351f028 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/config/jwt/JwtTokenProvider.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/controller/MemberController.class b/member/build/classes/java/main/com/unicorn/lifesub/member/controller/MemberController.class new file mode 100644 index 0000000..71bced7 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/controller/MemberController.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/domain/Member$MemberBuilder.class b/member/build/classes/java/main/com/unicorn/lifesub/member/domain/Member$MemberBuilder.class new file mode 100644 index 0000000..5b355d3 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/domain/Member$MemberBuilder.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/domain/Member.class b/member/build/classes/java/main/com/unicorn/lifesub/member/domain/Member.class new file mode 100644 index 0000000..7ce52fa Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/domain/Member.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LoginRequest.class b/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LoginRequest.class new file mode 100644 index 0000000..e9f308a Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LoginRequest.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutRequest.class b/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutRequest.class new file mode 100644 index 0000000..25ea6ff Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutRequest.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutResponse$LogoutResponseBuilder.class b/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutResponse$LogoutResponseBuilder.class new file mode 100644 index 0000000..386a637 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutResponse$LogoutResponseBuilder.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutResponse.class b/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutResponse.class new file mode 100644 index 0000000..4500a45 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/dto/LogoutResponse.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/repository/entity/MemberEntity$MemberEntityBuilder.class b/member/build/classes/java/main/com/unicorn/lifesub/member/repository/entity/MemberEntity$MemberEntityBuilder.class new file mode 100644 index 0000000..1915313 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/repository/entity/MemberEntity$MemberEntityBuilder.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/repository/entity/MemberEntity.class b/member/build/classes/java/main/com/unicorn/lifesub/member/repository/entity/MemberEntity.class new file mode 100644 index 0000000..16f8a6d Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/repository/entity/MemberEntity.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/repository/jpa/MemberRepository.class b/member/build/classes/java/main/com/unicorn/lifesub/member/repository/jpa/MemberRepository.class new file mode 100644 index 0000000..afcb8c0 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/repository/jpa/MemberRepository.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/service/MemberService.class b/member/build/classes/java/main/com/unicorn/lifesub/member/service/MemberService.class new file mode 100644 index 0000000..4c70138 Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/service/MemberService.class differ diff --git a/member/build/classes/java/main/com/unicorn/lifesub/member/service/MemberServiceImpl.class b/member/build/classes/java/main/com/unicorn/lifesub/member/service/MemberServiceImpl.class new file mode 100644 index 0000000..3a9a16d Binary files /dev/null and b/member/build/classes/java/main/com/unicorn/lifesub/member/service/MemberServiceImpl.class differ diff --git a/member/build/resources/main/application.yml b/member/build/resources/main/application.yml new file mode 100644 index 0000000..23202be --- /dev/null +++ b/member/build/resources/main/application.yml @@ -0,0 +1,31 @@ +server: + port: ${SERVER_PORT:8081} + +spring: + application: + name: member-service + datasource: + url: ${POSTGRES_URL} + username: ${POSTGRES_USER} + password: ${POSTGRES_PASSWORD} + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: ${JPA_DDL_AUTO:validate} + show-sql: ${JPA_SHOW_SQL:false} + properties: + hibernate: + format_sql: true + +jwt: + secret-key: ${JWT_SECRET_KEY} + access-token-validity: ${JWT_ACCESS_TOKEN_VALIDITY:3600000} + refresh-token-validity: ${JWT_REFRESH_TOKEN_VALIDITY:86400000} + +allowedorigins: ${ALLOWED_ORIGINS:*} + +springdoc: + swagger-ui: + path: /swagger-ui.html + api-docs: + path: /api-docs \ No newline at end of file diff --git a/member/build/tmp/compileJava/previous-compilation-data.bin b/member/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 0000000..7fb6b94 Binary files /dev/null and b/member/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/member/src/main/java/com/unicorn/lifesub/member/MemberApplication.java b/member/src/main/java/com/unicorn/lifesub/member/MemberApplication.java new file mode 100644 index 0000000..636f06b --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/MemberApplication.java @@ -0,0 +1,11 @@ +package com.unicorn.lifesub.member; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MemberApplication { + public static void main(String[] args) { + SpringApplication.run(MemberApplication.class, args); + } +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/config/InitialDataLoader.java b/member/src/main/java/com/unicorn/lifesub/member/config/InitialDataLoader.java new file mode 100644 index 0000000..70319a0 --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/config/InitialDataLoader.java @@ -0,0 +1,44 @@ +// File: lifesub/member/src/main/java/com/unicorn/lifesub/member/config/InitialDataLoader.java +package com.unicorn.lifesub.member.config; + +import com.unicorn.lifesub.member.repository.entity.MemberEntity; +import com.unicorn.lifesub.member.repository.jpa.MemberRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.CommandLineRunner; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.util.HashSet; +import java.util.Set; +import java.util.stream.IntStream; + +@Component +@RequiredArgsConstructor +public class InitialDataLoader implements CommandLineRunner { + private final MemberRepository memberRepository; + private final PasswordEncoder passwordEncoder; + + @Override + @Transactional + public void run(String... args) { + // 기존 사용자 데이터가 없을 경우에만 초기 데이터 생성 + if (memberRepository.count() == 0) { + Set userRoles = new HashSet<>(); + userRoles.add("USER"); + String encodedPassword = passwordEncoder.encode("P@ssw0rd$"); + + IntStream.rangeClosed(1, 10).forEach(i -> { + String userId = String.format("user%02d", i); + MemberEntity member = MemberEntity.builder() + .userId(userId) + .userName("사용자" + i) + .password(encodedPassword) + .roles(userRoles) + .build(); + + memberRepository.save(member); + }); + } + } +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/config/SecurityConfig.java b/member/src/main/java/com/unicorn/lifesub/member/config/SecurityConfig.java new file mode 100644 index 0000000..849673c --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/config/SecurityConfig.java @@ -0,0 +1,86 @@ +package com.unicorn.lifesub.member.config; + +import com.unicorn.lifesub.member.config.jwt.CustomUserDetailsService; +import com.unicorn.lifesub.member.config.jwt.JwtTokenProvider; +import com.unicorn.lifesub.member.config.jwt.JwtAuthenticationFilter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.Arrays; +import java.util.List; + +@Configuration +@EnableWebSecurity +@SuppressWarnings("unused") +public class SecurityConfig { + private final JwtTokenProvider jwtTokenProvider; + private final CustomUserDetailsService customUserDetailsService; + + @Value("${allowedorigins}") + private String allowedOrigins; + + public SecurityConfig(JwtTokenProvider jwtTokenProvider, CustomUserDetailsService customUserDetailsService) { + this.jwtTokenProvider = jwtTokenProvider; + this.customUserDetailsService = customUserDetailsService; + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception { + return authConfig.getAuthenticationManager(); + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .cors(cors -> cors + .configurationSource(corsConfigurationSource()) + ) + .csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(auth -> auth + .requestMatchers(HttpMethod.GET, "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**").permitAll() + .requestMatchers(HttpMethod.POST, "/api/auth/**").permitAll() + .anyRequest().authenticated() + ) + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + ) + .userDetailsService(customUserDetailsService) + .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Arrays.asList(allowedOrigins.split(","))); + configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(List.of("*")); + configuration.setAllowCredentials(true); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} + diff --git a/member/src/main/java/com/unicorn/lifesub/member/config/SwaggerConfig.java b/member/src/main/java/com/unicorn/lifesub/member/config/SwaggerConfig.java new file mode 100644 index 0000000..87b7b8a --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/config/SwaggerConfig.java @@ -0,0 +1,28 @@ +package com.unicorn.lifesub.member.config; + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SuppressWarnings("unused") +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + bearerFormat = "JWT", + scheme = "bearer" +) +public class SwaggerConfig { + + @Bean + public OpenAPI openAPI() { + return new OpenAPI() + .info(new Info() + .title("회원 서비스 API") + .version("v1.0.0") + .description("회원 서비스 API 명세서입니다.")); + } +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/config/jwt/CustomUserDetailsService.java b/member/src/main/java/com/unicorn/lifesub/member/config/jwt/CustomUserDetailsService.java new file mode 100644 index 0000000..50d6c88 --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/config/jwt/CustomUserDetailsService.java @@ -0,0 +1,41 @@ +package com.unicorn.lifesub.member.config.jwt; + +import com.unicorn.lifesub.member.repository.entity.MemberEntity; +import com.unicorn.lifesub.member.repository.jpa.MemberRepository; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.Set; +import java.util.stream.Collectors; + +@Service +public class CustomUserDetailsService implements UserDetailsService { + + private final MemberRepository memberRepository; + + public CustomUserDetailsService(MemberRepository memberRepository) { + this.memberRepository = memberRepository; + } + + @Override + public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException { + MemberEntity member = memberRepository.findByUserId(userId) + .orElseThrow(() -> new UsernameNotFoundException("User not found with userId: " + userId)); + + Set authorities = member.getRoles().stream() + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toSet()); + + return User.builder() + .username(member.getUserId()) + .password(member.getPassword()) + .authorities(authorities) + .build(); + } +} + diff --git a/member/src/main/java/com/unicorn/lifesub/member/config/jwt/JwtAuthenticationFilter.java b/member/src/main/java/com/unicorn/lifesub/member/config/jwt/JwtAuthenticationFilter.java new file mode 100644 index 0000000..79df3bf --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/config/jwt/JwtAuthenticationFilter.java @@ -0,0 +1,36 @@ +package com.unicorn.lifesub.member.config.jwt; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.NonNull; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final JwtTokenProvider jwtTokenProvider; + + public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) { + this.jwtTokenProvider = jwtTokenProvider; + } + + @Override + protected void doFilterInternal(@NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + @NonNull FilterChain filterChain) + throws ServletException, IOException { + String token = jwtTokenProvider.resolveToken(request); + + if (token != null && jwtTokenProvider.validateToken(token) == 1) { + Authentication authentication = jwtTokenProvider.getAuthentication(token); + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + filterChain.doFilter(request, response); + } +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/config/jwt/JwtTokenProvider.java b/member/src/main/java/com/unicorn/lifesub/member/config/jwt/JwtTokenProvider.java new file mode 100644 index 0000000..5ae66b0 --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/config/jwt/JwtTokenProvider.java @@ -0,0 +1,148 @@ +package com.unicorn.lifesub.member.config.jwt; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.AlgorithmMismatchException; +import com.auth0.jwt.exceptions.InvalidClaimException; +import com.auth0.jwt.exceptions.SignatureVerificationException; +import com.auth0.jwt.exceptions.TokenExpiredException; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.unicorn.lifesub.common.exception.ErrorCode; +import com.unicorn.lifesub.common.dto.JwtTokenDTO; +import com.unicorn.lifesub.common.exception.InfraException; +import com.unicorn.lifesub.member.repository.entity.MemberEntity; +import jakarta.servlet.http.HttpServletRequest; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.stream.Collectors; + +@Slf4j +@Component +public class JwtTokenProvider { + private final Algorithm algorithm; + private final long accessTokenValidityInMilliseconds; + private final long refreshTokenValidityInMilliseconds; + + public JwtTokenProvider( + @Value("${jwt.secret-key}") String secretKey, + @Value("${jwt.access-token-validity}") long accessTokenValidityInMilliseconds, + @Value("${jwt.refresh-token-validity}") long refreshTokenValidityInMilliseconds) { + this.algorithm = Algorithm.HMAC512(secretKey); + this.accessTokenValidityInMilliseconds = accessTokenValidityInMilliseconds * 1000; + this.refreshTokenValidityInMilliseconds = refreshTokenValidityInMilliseconds * 1000; + } + + public JwtTokenDTO createToken(MemberEntity memberEntity, Collection authorities) { + try { + Date now = new Date(); + Date accessTokenValidity = new Date(now.getTime() + accessTokenValidityInMilliseconds); + Date refreshTokenValidity = new Date(now.getTime() + refreshTokenValidityInMilliseconds); + + String accessToken = JWT.create() + .withSubject(memberEntity.getUserId()) + .withClaim("userId", memberEntity.getUserId()) + .withClaim("userName", memberEntity.getUserName()) + .withClaim("auth", authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())) + .withIssuedAt(now) + .withExpiresAt(accessTokenValidity) + .sign(algorithm); + + String refreshToken = JWT.create() + .withSubject(memberEntity.getUserId()) + .withIssuedAt(now) + .withExpiresAt(refreshTokenValidity) + .sign(algorithm); + + return JwtTokenDTO.builder() + .accessToken(accessToken) + .refreshToken(refreshToken) + .build(); + } catch(Exception e) { + throw new InfraException(ErrorCode.INVALID_CREDENTIALS); + } + } + + public boolean validateRefreshToken(String refreshToken) { + try { + JWTVerifier verifier = JWT.require(algorithm).build(); + verifier.verify(refreshToken); + return true; + } catch (Exception e) { + throw new InfraException(ErrorCode.INVALID_CREDENTIALS); + } + } + + public String getUserIdFromToken(String refreshToken) { + try { + DecodedJWT decodedJWT = JWT.decode(refreshToken); + return decodedJWT.getSubject(); + } catch (Exception e) { + throw new InfraException(ErrorCode.INVALID_CREDENTIALS); + } + } + + public String resolveToken(HttpServletRequest request) { + try { + String bearerToken = request.getHeader("Authorization"); + if (bearerToken != null && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); + } + return null; + } catch (Exception e) { + throw new InfraException(ErrorCode.INVALID_CREDENTIALS); + } + } + + public int validateToken(String token) { + log.info("******** validateToken: {}", token); + try { + JWTVerifier verifier = JWT.require(algorithm).build(); + verifier.verify(token); + return 1; // 검사 성공 시 1 반환 + } catch (TokenExpiredException e) { + log.error("Token validation failed: {}", e.getMessage(), e); + throw new InfraException(ErrorCode.TOKEN_EXPIRED); + } catch (SignatureVerificationException e) { + log.error("Token validation failed: {}", e.getMessage(), e); + throw new InfraException(ErrorCode.SIGNATURE_VERIFICATION_EXCEPTION); + } catch (AlgorithmMismatchException e) { + log.error("AlgorithmMismatchException: {}", e.getMessage(), e); + throw new InfraException(ErrorCode.ALGORITHM_MISMATCH_EXCEPTION); + } catch (InvalidClaimException e) { + log.error("InvalidClaimException: {}", e.getMessage(), e); + throw new InfraException(ErrorCode.INVALID_CREDENTIALS); + } catch (Exception e) { + log.error("Undefined Error: {}", e.getMessage(), e); + throw new InfraException(ErrorCode.UNDIFINED_ERROR); + } + } + + public Authentication getAuthentication(String token) { + try { + DecodedJWT decodedJWT = JWT.decode(token); + String username = decodedJWT.getSubject(); + String[] authStrings = decodedJWT.getClaim("auth").asArray(String.class); + Collection authorities = Arrays.stream(authStrings) + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + UserDetails userDetails = new User(username, "", authorities); + + return new UsernamePasswordAuthenticationToken(userDetails, "", authorities); + } catch (Exception e) { + throw new InfraException(ErrorCode.INVALID_CREDENTIALS); + } + } +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/controller/MemberController.java b/member/src/main/java/com/unicorn/lifesub/member/controller/MemberController.java new file mode 100644 index 0000000..47884cc --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/controller/MemberController.java @@ -0,0 +1,37 @@ +package com.unicorn.lifesub.member.controller; + +import com.unicorn.lifesub.common.dto.ApiResponse; +import com.unicorn.lifesub.common.dto.JwtTokenDTO; +import com.unicorn.lifesub.member.dto.*; +import com.unicorn.lifesub.member.service.MemberService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Tag(name = "회원 API", description = "회원 인증 관련 API") +@RestController +@RequestMapping("/api/auth") +@RequiredArgsConstructor +public class MemberController { + private final MemberService memberService; + + @Operation(summary = "로그인", description = "사용자 ID와 비밀번호로 로그인합니다.") + @PostMapping("/login") + public ResponseEntity> login(@Valid @RequestBody LoginRequest request) { + JwtTokenDTO response = memberService.login(request); + return ResponseEntity.ok(ApiResponse.success(response)); + } + + @Operation(summary = "로그아웃", description = "현재 로그인된 사용자를 로그아웃합니다.") + @PostMapping("/logout") + public ResponseEntity> logout(@Valid @RequestBody LogoutRequest request) { + LogoutResponse response = memberService.logout(request); + return ResponseEntity.ok(ApiResponse.success(response)); + } +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/domain/Member.java b/member/src/main/java/com/unicorn/lifesub/member/domain/Member.java new file mode 100644 index 0000000..2cf778a --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/domain/Member.java @@ -0,0 +1,21 @@ +package com.unicorn.lifesub.member.domain; + +import lombok.Builder; +import lombok.Getter; +import java.util.Set; + +@Getter +public class Member { + private final String userId; + private final String userName; + private final String password; + private final Set roles; + + @Builder + public Member(String userId, String userName, String password, Set roles) { + this.userId = userId; + this.userName = userName; + this.password = password; + this.roles = roles; + } +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/dto/LoginRequest.java b/member/src/main/java/com/unicorn/lifesub/member/dto/LoginRequest.java new file mode 100644 index 0000000..8bbbfbe --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/dto/LoginRequest.java @@ -0,0 +1,13 @@ +package com.unicorn.lifesub.member.dto; + +import jakarta.validation.constraints.NotBlank; +import lombok.Getter; + +@Getter +public class LoginRequest { + @NotBlank(message = "사용자 ID는 필수입니다.") + private String userId; + + @NotBlank(message = "비밀번호는 필수입니다.") + private String password; +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/dto/LogoutRequest.java b/member/src/main/java/com/unicorn/lifesub/member/dto/LogoutRequest.java new file mode 100644 index 0000000..4e0809a --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/dto/LogoutRequest.java @@ -0,0 +1,10 @@ +package com.unicorn.lifesub.member.dto; + +import jakarta.validation.constraints.NotBlank; +import lombok.Getter; + +@Getter +public class LogoutRequest { + @NotBlank(message = "사용자 ID는 필수입니다.") + private String userId; +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/dto/LogoutResponse.java b/member/src/main/java/com/unicorn/lifesub/member/dto/LogoutResponse.java new file mode 100644 index 0000000..e6276f8 --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/dto/LogoutResponse.java @@ -0,0 +1,10 @@ +package com.unicorn.lifesub.member.dto; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class LogoutResponse { + private String message; +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/repository/entity/MemberEntity.java b/member/src/main/java/com/unicorn/lifesub/member/repository/entity/MemberEntity.java new file mode 100644 index 0000000..1d1c251 --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/repository/entity/MemberEntity.java @@ -0,0 +1,54 @@ +package com.unicorn.lifesub.member.repository.entity; + +import com.unicorn.lifesub.common.entity.BaseTimeEntity; +import com.unicorn.lifesub.member.domain.Member; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.HashSet; +import java.util.Set; + +@Entity +@Table(name = "members") +@Getter +@NoArgsConstructor +public class MemberEntity extends BaseTimeEntity { + @Id + private String userId; + + private String userName; + private String password; + + @ElementCollection(fetch = FetchType.EAGER) + @CollectionTable(name = "member_roles", joinColumns = @JoinColumn(name = "user_id")) + @Column(name = "role") + private Set roles = new HashSet<>(); + + @Builder + public MemberEntity(String userId, String userName, String password, Set roles) { + this.userId = userId; + this.userName = userName; + this.password = password; + this.roles = roles; + } + + public Member toDomain() { + return Member.builder() + .userId(userId) + .userName(userName) + .password(password) + .roles(roles) + .build(); + } + + public static MemberEntity fromDomain(Member member) { + return MemberEntity.builder() + .userId(member.getUserId()) + .userName(member.getUserName()) + .password(member.getPassword()) + .roles(member.getRoles()) + .build(); + } +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/repository/jpa/MemberRepository.java b/member/src/main/java/com/unicorn/lifesub/member/repository/jpa/MemberRepository.java new file mode 100644 index 0000000..1466c0f --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/repository/jpa/MemberRepository.java @@ -0,0 +1,9 @@ +package com.unicorn.lifesub.member.repository.jpa; + +import com.unicorn.lifesub.member.repository.entity.MemberEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.Optional; + +public interface MemberRepository extends JpaRepository { + Optional findByUserId(String userId); +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/service/MemberService.java b/member/src/main/java/com/unicorn/lifesub/member/service/MemberService.java new file mode 100644 index 0000000..6dbca48 --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/service/MemberService.java @@ -0,0 +1,9 @@ +package com.unicorn.lifesub.member.service; + +import com.unicorn.lifesub.common.dto.JwtTokenDTO; +import com.unicorn.lifesub.member.dto.*; + +public interface MemberService { + JwtTokenDTO login(LoginRequest request); + LogoutResponse logout(LogoutRequest request); +} diff --git a/member/src/main/java/com/unicorn/lifesub/member/service/MemberServiceImpl.java b/member/src/main/java/com/unicorn/lifesub/member/service/MemberServiceImpl.java new file mode 100644 index 0000000..a5bae5d --- /dev/null +++ b/member/src/main/java/com/unicorn/lifesub/member/service/MemberServiceImpl.java @@ -0,0 +1,56 @@ +package com.unicorn.lifesub.member.service; + +import com.unicorn.lifesub.common.exception.BusinessException; +import com.unicorn.lifesub.common.exception.ErrorCode; +import com.unicorn.lifesub.member.config.jwt.JwtTokenProvider; +import com.unicorn.lifesub.common.dto.JwtTokenDTO; +import com.unicorn.lifesub.member.dto.LoginRequest; +import com.unicorn.lifesub.member.dto.LogoutRequest; +import com.unicorn.lifesub.member.dto.LogoutResponse; +import com.unicorn.lifesub.common.exception.InfraException; +import com.unicorn.lifesub.member.repository.entity.MemberEntity; +import com.unicorn.lifesub.member.repository.jpa.MemberRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collection; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class MemberServiceImpl implements MemberService { + private final MemberRepository memberRepository; + private final PasswordEncoder passwordEncoder; + private final JwtTokenProvider jwtTokenProvider; + + @Override + @Transactional(readOnly = true) + public JwtTokenDTO login(LoginRequest request) { + MemberEntity member = memberRepository.findByUserId(request.getUserId()) + .orElseThrow(() -> new InfraException(ErrorCode.MEMBER_NOT_FOUND)); + + // 사용자의 권한 정보 생성 + Collection authorities = member.getRoles().stream() + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + if (!passwordEncoder.matches(request.getPassword(), member.getPassword())) { + throw new BusinessException(ErrorCode.INVALID_CREDENTIALS); + } + + return jwtTokenProvider.createToken(member, authorities); + } + + @Override + @Transactional + public LogoutResponse logout(LogoutRequest request) { + // 실제 구현에서는 Redis 등을 사용하여 토큰 블랙리스트 관리 + return LogoutResponse.builder() + .message("로그아웃이 완료되었습니다.") + .build(); + } +} diff --git a/member/src/main/resources/application.yml b/member/src/main/resources/application.yml new file mode 100644 index 0000000..7759a05 --- /dev/null +++ b/member/src/main/resources/application.yml @@ -0,0 +1,32 @@ +server: + port: ${SERVER_PORT:8081} + +spring: + application: + name: member-service + datasource: + url: jdbc:postgresql://${POSTGRES_HOST:localhost}:${POSTGRES_PORT:5432}/${POSTGRES_DB:member} + username: ${POSTGRES_USER:postgres} + password: ${POSTGRES_PASSWORD:postgres} + driver-class-name: org.postgresql.Driver + + jpa: + hibernate: + ddl-auto: ${JPA_DDL_AUTO:validate} + show-sql: ${JPA_SHOW_SQL:false} + properties: + hibernate: + format_sql: true + +jwt: + secret-key: ${JWT_SECRET_KEY} + access-token-validity: ${JWT_ACCESS_TOKEN_VALIDITY:3600000} + refresh-token-validity: ${JWT_REFRESH_TOKEN_VALIDITY:86400000} + +allowedorigins: ${ALLOWED_ORIGINS:*} + +springdoc: + swagger-ui: + path: /swagger-ui.html + api-docs: + path: /api-docs \ No newline at end of file diff --git a/mysub-biz/build.gradle b/mysub-biz/build.gradle new file mode 100644 index 0000000..4c66527 --- /dev/null +++ b/mysub-biz/build.gradle @@ -0,0 +1,4 @@ +dependencies { + implementation project(':common') + implementation 'org.springframework:spring-tx' +} diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Category$CategoryBuilder.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Category$CategoryBuilder.class new file mode 100644 index 0000000..f5b5890 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Category$CategoryBuilder.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Category.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Category.class new file mode 100644 index 0000000..e94a25f Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Category.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/MySubscription$MySubscriptionBuilder.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/MySubscription$MySubscriptionBuilder.class new file mode 100644 index 0000000..7a2ca4c Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/MySubscription$MySubscriptionBuilder.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/MySubscription.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/MySubscription.class new file mode 100644 index 0000000..250d377 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/MySubscription.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Subscription$SubscriptionBuilder.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Subscription$SubscriptionBuilder.class new file mode 100644 index 0000000..ee1b0ad Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Subscription$SubscriptionBuilder.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Subscription.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Subscription.class new file mode 100644 index 0000000..4b2c37c Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/domain/Subscription.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse$CategoryResponseBuilder.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse$CategoryResponseBuilder.class new file mode 100644 index 0000000..ce1d8d6 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse$CategoryResponseBuilder.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse.class new file mode 100644 index 0000000..9cf02ca Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/MySubResponse$MySubResponseBuilder.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/MySubResponse$MySubResponseBuilder.class new file mode 100644 index 0000000..e0d70b9 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/MySubResponse$MySubResponseBuilder.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/MySubResponse.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/MySubResponse.class new file mode 100644 index 0000000..e511c24 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/MySubResponse.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse$ServiceListResponseBuilder.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse$ServiceListResponseBuilder.class new file mode 100644 index 0000000..6ccd969 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse$ServiceListResponseBuilder.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse.class new file mode 100644 index 0000000..7132930 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse$SubDetailResponseBuilder.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse$SubDetailResponseBuilder.class new file mode 100644 index 0000000..5627ca9 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse$SubDetailResponseBuilder.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse.class new file mode 100644 index 0000000..79c5516 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse$TotalFeeResponseBuilder.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse$TotalFeeResponseBuilder.class new file mode 100644 index 0000000..7aa5130 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse$TotalFeeResponseBuilder.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse.class new file mode 100644 index 0000000..2aa4cb3 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/service/MySubscriptionService.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/service/MySubscriptionService.class new file mode 100644 index 0000000..a6e7e19 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/service/MySubscriptionService.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/CancelSubscriptionUseCase.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/CancelSubscriptionUseCase.class new file mode 100644 index 0000000..2ff1394 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/CancelSubscriptionUseCase.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/CategoryUseCase.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/CategoryUseCase.class new file mode 100644 index 0000000..208dbf1 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/CategoryUseCase.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/MySubscriptionsUseCase.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/MySubscriptionsUseCase.class new file mode 100644 index 0000000..c4d42c7 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/MySubscriptionsUseCase.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/SubscribeUseCase.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/SubscribeUseCase.class new file mode 100644 index 0000000..058a8de Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/SubscribeUseCase.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/SubscriptionDetailUseCase.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/SubscriptionDetailUseCase.class new file mode 100644 index 0000000..164f169 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/SubscriptionDetailUseCase.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/TotalFeeUseCase.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/TotalFeeUseCase.class new file mode 100644 index 0000000..5e02bbc Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/in/TotalFeeUseCase.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionReader.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionReader.class new file mode 100644 index 0000000..70abe6e Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionReader.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionWriter.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionWriter.class new file mode 100644 index 0000000..a610f11 Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionWriter.class differ diff --git a/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/SubscriptionReader.class b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/SubscriptionReader.class new file mode 100644 index 0000000..151165c Binary files /dev/null and b/mysub-biz/build/classes/java/main/com/unicorn/lifesub/mysub/biz/usecase/out/SubscriptionReader.class differ diff --git a/mysub-biz/build/libs/mysub-biz-1.0.0-plain.jar b/mysub-biz/build/libs/mysub-biz-1.0.0-plain.jar new file mode 100644 index 0000000..50f38fd Binary files /dev/null and b/mysub-biz/build/libs/mysub-biz-1.0.0-plain.jar differ diff --git a/mysub-biz/build/tmp/compileJava/previous-compilation-data.bin b/mysub-biz/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 0000000..d6768e3 Binary files /dev/null and b/mysub-biz/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/mysub-biz/build/tmp/jar/MANIFEST.MF b/mysub-biz/build/tmp/jar/MANIFEST.MF new file mode 100644 index 0000000..59499bc --- /dev/null +++ b/mysub-biz/build/tmp/jar/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/Category.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/Category.java new file mode 100644 index 0000000..a4f8308 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/Category.java @@ -0,0 +1,17 @@ +// Category.java +package com.unicorn.lifesub.mysub.biz.domain; + +import lombok.Builder; +import lombok.Getter; + +@Getter +public class Category { + private final String categoryId; + private final String name; + + @Builder + public Category(String categoryId, String name) { + this.categoryId = categoryId; + this.name = name; + } +} \ No newline at end of file diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/MySubscription.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/MySubscription.java new file mode 100644 index 0000000..9e5e784 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/MySubscription.java @@ -0,0 +1,22 @@ +package com.unicorn.lifesub.mysub.biz.domain; + +import lombok.Builder; +import lombok.Getter; + +@Getter +public class MySubscription { + private final Long id; + private final String userId; + private final Subscription subscription; + + @Builder + public MySubscription(Long id, String userId, Subscription subscription) { + this.id = id; + this.userId = userId; + this.subscription = subscription; + } + + public int getPrice() { + return subscription.getPrice(); + } +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/Subscription.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/Subscription.java new file mode 100644 index 0000000..dcca927 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/domain/Subscription.java @@ -0,0 +1,27 @@ +package com.unicorn.lifesub.mysub.biz.domain; + +import lombok.Builder; +import lombok.Getter; + +@Getter +public class Subscription { + private final Long id; + private final String name; + private final String description; + private final String category; + private final int price; + private final int maxSharedUsers; + private final String logoUrl; + + @Builder + public Subscription(Long id, String name, String description, String category, + int price, int maxSharedUsers, String logoUrl) { + this.id = id; + this.name = name; + this.description = description; + this.category = category; + this.price = price; + this.maxSharedUsers = maxSharedUsers; + this.logoUrl = logoUrl; + } +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse.java new file mode 100644 index 0000000..591531f --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/CategoryResponse.java @@ -0,0 +1,12 @@ +// CategoryResponse.java +package com.unicorn.lifesub.mysub.biz.dto; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class CategoryResponse { + private final String categoryId; + private final String categoryName; +} \ No newline at end of file diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/MySubResponse.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/MySubResponse.java new file mode 100644 index 0000000..45cce88 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/MySubResponse.java @@ -0,0 +1,11 @@ +package com.unicorn.lifesub.mysub.biz.dto; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class MySubResponse { + private final String serviceName; + private final String logoUrl; +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse.java new file mode 100644 index 0000000..550bedb --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/ServiceListResponse.java @@ -0,0 +1,15 @@ +package com.unicorn.lifesub.mysub.biz.dto; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder + +public class ServiceListResponse { + private String serviceId; + private String serviceName; + private String description; + private int price; + private String logoUrl; +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse.java new file mode 100644 index 0000000..642d314 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/SubDetailResponse.java @@ -0,0 +1,16 @@ +package com.unicorn.lifesub.mysub.biz.dto; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder + +public class SubDetailResponse { + private final String serviceName; + private final String logoUrl; + private final String category; + private final String description; + private final int price; + private final int maxSharedUsers; +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse.java new file mode 100644 index 0000000..5b412b4 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/dto/TotalFeeResponse.java @@ -0,0 +1,11 @@ +package com.unicorn.lifesub.mysub.biz.dto; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class TotalFeeResponse { + private final Long totalFee; + private final String feeLevel; +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/service/MySubscriptionService.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/service/MySubscriptionService.java new file mode 100644 index 0000000..329a384 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/service/MySubscriptionService.java @@ -0,0 +1,51 @@ +package com.unicorn.lifesub.mysub.biz.service; + +import com.unicorn.lifesub.mysub.biz.domain.MySubscription; +import com.unicorn.lifesub.mysub.biz.dto.MySubResponse; +import com.unicorn.lifesub.mysub.biz.dto.TotalFeeResponse; +import com.unicorn.lifesub.mysub.biz.usecase.in.MySubscriptionsUseCase; +import com.unicorn.lifesub.mysub.biz.usecase.in.TotalFeeUseCase; +import com.unicorn.lifesub.mysub.biz.usecase.out.MySubscriptionReader; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class MySubscriptionService implements TotalFeeUseCase, MySubscriptionsUseCase { + private final MySubscriptionReader mySubscriptionReader; + + @Override + @Transactional(readOnly = true) + public TotalFeeResponse getTotalFee(String userId) { + List subscriptions = mySubscriptionReader.findByUserId(userId); + long totalFee = subscriptions.stream() + .mapToLong(MySubscription::getPrice) + .sum(); + + return TotalFeeResponse.builder() + .totalFee(totalFee) + .feeLevel(calculateFeeLevel(totalFee)) + .build(); + } + + @Override + @Transactional(readOnly = true) + public List getMySubscriptions(String userId) { + return mySubscriptionReader.findByUserId(userId).stream() + .map(subscription -> MySubResponse.builder() + .serviceName(subscription.getSubscription().getName()) + .logoUrl(subscription.getSubscription().getLogoUrl()) + .build()) + .collect(Collectors.toList()); + } + + private String calculateFeeLevel(long totalFee) { + if (totalFee < 100000) return "구독을 좋아하는 사람"; + if (totalFee < 200000) return "구독 수집자"; + return "구독 사치왕"; + } +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/CancelSubscriptionUseCase.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/CancelSubscriptionUseCase.java new file mode 100644 index 0000000..f9fb010 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/CancelSubscriptionUseCase.java @@ -0,0 +1,5 @@ +package com.unicorn.lifesub.mysub.biz.usecase.in; + +public interface CancelSubscriptionUseCase { + void cancel(Long subscriptionId); +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/CategoryUseCase.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/CategoryUseCase.java new file mode 100644 index 0000000..d537b2f --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/CategoryUseCase.java @@ -0,0 +1,10 @@ +package com.unicorn.lifesub.mysub.biz.usecase.in; + +import com.unicorn.lifesub.mysub.biz.dto.CategoryResponse; +import com.unicorn.lifesub.mysub.biz.dto.ServiceListResponse; +import java.util.List; + +public interface CategoryUseCase { + List getAllCategories(); + List getServicesByCategory(String categoryId); +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/MySubscriptionsUseCase.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/MySubscriptionsUseCase.java new file mode 100644 index 0000000..8500e52 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/MySubscriptionsUseCase.java @@ -0,0 +1,8 @@ +package com.unicorn.lifesub.mysub.biz.usecase.in; + +import com.unicorn.lifesub.mysub.biz.dto.MySubResponse; +import java.util.List; + +public interface MySubscriptionsUseCase { + List getMySubscriptions(String userId); +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/SubscribeUseCase.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/SubscribeUseCase.java new file mode 100644 index 0000000..ae04aa4 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/SubscribeUseCase.java @@ -0,0 +1,5 @@ +package com.unicorn.lifesub.mysub.biz.usecase.in; + +public interface SubscribeUseCase { + void subscribe(Long subscriptionId, String userId); +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/SubscriptionDetailUseCase.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/SubscriptionDetailUseCase.java new file mode 100644 index 0000000..d7e417e --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/SubscriptionDetailUseCase.java @@ -0,0 +1,7 @@ +package com.unicorn.lifesub.mysub.biz.usecase.in; + +import com.unicorn.lifesub.mysub.biz.dto.SubDetailResponse; + +public interface SubscriptionDetailUseCase { + SubDetailResponse getSubscriptionDetail(Long subscriptionId); +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/TotalFeeUseCase.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/TotalFeeUseCase.java new file mode 100644 index 0000000..01a8ed5 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/in/TotalFeeUseCase.java @@ -0,0 +1,7 @@ +package com.unicorn.lifesub.mysub.biz.usecase.in; + +import com.unicorn.lifesub.mysub.biz.dto.TotalFeeResponse; + +public interface TotalFeeUseCase { + TotalFeeResponse getTotalFee(String userId); +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionReader.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionReader.java new file mode 100644 index 0000000..6890145 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionReader.java @@ -0,0 +1,10 @@ +package com.unicorn.lifesub.mysub.biz.usecase.out; + +import com.unicorn.lifesub.mysub.biz.domain.MySubscription; +import java.util.List; +import java.util.Optional; + +public interface MySubscriptionReader { + List findByUserId(String userId); + Optional findById(Long id); +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionWriter.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionWriter.java new file mode 100644 index 0000000..19d04c3 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/MySubscriptionWriter.java @@ -0,0 +1,8 @@ +package com.unicorn.lifesub.mysub.biz.usecase.out; + +import com.unicorn.lifesub.mysub.biz.domain.MySubscription; + +public interface MySubscriptionWriter { + MySubscription save(String userId, Long subscriptionId); + void delete(Long id); +} diff --git a/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/SubscriptionReader.java b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/SubscriptionReader.java new file mode 100644 index 0000000..8a92233 --- /dev/null +++ b/mysub-biz/src/main/java/com/unicorn/lifesub/mysub/biz/usecase/out/SubscriptionReader.java @@ -0,0 +1,13 @@ +package com.unicorn.lifesub.mysub.biz.usecase.out; + +import com.unicorn.lifesub.mysub.biz.domain.Category; +import com.unicorn.lifesub.mysub.biz.domain.Subscription; + +import java.util.List; +import java.util.Optional; + +public interface SubscriptionReader { + Optional findById(Long id); + List findByCategory(String categoryId); + List findAllCategories(); +} diff --git a/mysub-infra/build.gradle b/mysub-infra/build.gradle new file mode 100644 index 0000000..78e7954 --- /dev/null +++ b/mysub-infra/build.gradle @@ -0,0 +1,8 @@ +dependencies { + implementation project(':common') + implementation project(':mysub-biz') + runtimeOnly 'org.postgresql:postgresql' +} +bootJar { + archiveFileName = "mysub.jar" +} diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/MySubApplication.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/MySubApplication.class new file mode 100644 index 0000000..81e01ee Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/MySubApplication.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/adapter/MySubscriptionAdapter.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/adapter/MySubscriptionAdapter.class new file mode 100644 index 0000000..11327b0 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/adapter/MySubscriptionAdapter.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/adapter/SubscriptionAdapter.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/adapter/SubscriptionAdapter.class new file mode 100644 index 0000000..8bbff21 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/adapter/SubscriptionAdapter.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/SecurityConfig.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/SecurityConfig.class new file mode 100644 index 0000000..c0f2dc5 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/SecurityConfig.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/SwaggerConfig.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/SwaggerConfig.class new file mode 100644 index 0000000..a82565a Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/SwaggerConfig.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/jwt/JwtAuthenticationFilter.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/jwt/JwtAuthenticationFilter.class new file mode 100644 index 0000000..4bca27d Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/jwt/JwtAuthenticationFilter.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/jwt/JwtTokenProvider.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/jwt/JwtTokenProvider.class new file mode 100644 index 0000000..4870a8e Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/config/jwt/JwtTokenProvider.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/CategoryController.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/CategoryController.class new file mode 100644 index 0000000..d8e4cad Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/CategoryController.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/MySubController.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/MySubController.class new file mode 100644 index 0000000..65787b1 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/MySubController.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/ServiceController.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/ServiceController.class new file mode 100644 index 0000000..a4beaeb Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/controller/ServiceController.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity$CategoryEntityBuilder.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity$CategoryEntityBuilder.class new file mode 100644 index 0000000..1edfad0 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity$CategoryEntityBuilder.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity.class new file mode 100644 index 0000000..eff0e93 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity$MySubscriptionEntityBuilder.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity$MySubscriptionEntityBuilder.class new file mode 100644 index 0000000..5ba180d Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity$MySubscriptionEntityBuilder.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity.class new file mode 100644 index 0000000..f0b20d7 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity$SubscriptionEntityBuilder.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity$SubscriptionEntityBuilder.class new file mode 100644 index 0000000..9ef9bdd Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity$SubscriptionEntityBuilder.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity.class new file mode 100644 index 0000000..daa7aae Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/CategoryJpaRepository.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/CategoryJpaRepository.class new file mode 100644 index 0000000..6861a66 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/CategoryJpaRepository.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/MySubscriptionJpaRepository.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/MySubscriptionJpaRepository.class new file mode 100644 index 0000000..23fb3fc Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/MySubscriptionJpaRepository.class differ diff --git a/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/SubscriptionJpaRepository.class b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/SubscriptionJpaRepository.class new file mode 100644 index 0000000..7df8b15 Binary files /dev/null and b/mysub-infra/build/classes/java/main/com/unicorn/lifesub/mysub/infra/repository/SubscriptionJpaRepository.class differ diff --git a/mysub-infra/build/resources/main/application.yml b/mysub-infra/build/resources/main/application.yml new file mode 100644 index 0000000..53222c8 --- /dev/null +++ b/mysub-infra/build/resources/main/application.yml @@ -0,0 +1,26 @@ +server: + port: ${SERVER_PORT:8082} + +spring: + application: + name: mysub-service + datasource: + url: ${POSTGRES_URL} + username: ${POSTGRES_USER} + password: ${POSTGRES_PASSWORD} + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: ${JPA_DDL_AUTO:validate} + show-sql: ${JPA_SHOW_SQL:false} + properties: + hibernate: + format_sql: true + +allowedorigins: ${ALLOWED_ORIGINS:*} + +springdoc: + swagger-ui: + path: /swagger-ui.html + api-docs: + path: /api-docs \ No newline at end of file diff --git a/mysub-infra/build/tmp/compileJava/previous-compilation-data.bin b/mysub-infra/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 0000000..fba669d Binary files /dev/null and b/mysub-infra/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/MySubApplication.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/MySubApplication.java new file mode 100644 index 0000000..f2e6486 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/MySubApplication.java @@ -0,0 +1,11 @@ +package com.unicorn.lifesub.mysub.infra; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MySubApplication { + public static void main(String[] args) { + SpringApplication.run(MySubApplication.class, args); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/adapter/MySubscriptionAdapter.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/adapter/MySubscriptionAdapter.java new file mode 100644 index 0000000..9e010e3 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/adapter/MySubscriptionAdapter.java @@ -0,0 +1,55 @@ +package com.unicorn.lifesub.mysub.infra.adapter; + +import com.unicorn.lifesub.common.exception.BusinessException; +import com.unicorn.lifesub.common.exception.ErrorCode; +import com.unicorn.lifesub.mysub.biz.domain.MySubscription; +import com.unicorn.lifesub.mysub.biz.usecase.out.MySubscriptionReader; +import com.unicorn.lifesub.mysub.biz.usecase.out.MySubscriptionWriter; +import com.unicorn.lifesub.mysub.infra.entity.MySubscriptionEntity; +import com.unicorn.lifesub.mysub.infra.entity.SubscriptionEntity; +import com.unicorn.lifesub.mysub.infra.repository.MySubscriptionJpaRepository; +import com.unicorn.lifesub.mysub.infra.repository.SubscriptionJpaRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +@Component +@RequiredArgsConstructor +public class MySubscriptionAdapter implements MySubscriptionReader, MySubscriptionWriter { + private final MySubscriptionJpaRepository mySubscriptionRepository; + private final SubscriptionJpaRepository subscriptionRepository; + + @Override + public List findByUserId(String userId) { + return mySubscriptionRepository.findByUserId(userId).stream() + .map(MySubscriptionEntity::toDomain) + .collect(Collectors.toList()); + } + + @Override + public Optional findById(Long id) { + return mySubscriptionRepository.findById(id) + .map(MySubscriptionEntity::toDomain); + } + + @Override + public MySubscription save(String userId, Long subscriptionId) { + SubscriptionEntity subscription = subscriptionRepository.findById(subscriptionId) + .orElseThrow(() -> new BusinessException(ErrorCode.SUBSCRIPTION_NOT_FOUND)); + + MySubscriptionEntity entity = MySubscriptionEntity.builder() + .userId(userId) + .subscription(subscription) + .build(); + + return mySubscriptionRepository.save(entity).toDomain(); + } + + @Override + public void delete(Long id) { + mySubscriptionRepository.deleteById(id); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/adapter/SubscriptionAdapter.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/adapter/SubscriptionAdapter.java new file mode 100644 index 0000000..e2b2f3e --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/adapter/SubscriptionAdapter.java @@ -0,0 +1,44 @@ +package com.unicorn.lifesub.mysub.infra.adapter; + +import com.unicorn.lifesub.common.exception.BusinessException; +import com.unicorn.lifesub.common.exception.ErrorCode; +import com.unicorn.lifesub.mysub.biz.domain.Subscription; +import com.unicorn.lifesub.mysub.biz.domain.Category; +import com.unicorn.lifesub.mysub.biz.usecase.out.SubscriptionReader; +import com.unicorn.lifesub.mysub.infra.entity.SubscriptionEntity; +import com.unicorn.lifesub.mysub.infra.entity.CategoryEntity; +import com.unicorn.lifesub.mysub.infra.repository.SubscriptionJpaRepository; +import com.unicorn.lifesub.mysub.infra.repository.CategoryJpaRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +@Component +@RequiredArgsConstructor +public class SubscriptionAdapter implements SubscriptionReader { + private final SubscriptionJpaRepository subscriptionRepository; + private final CategoryJpaRepository categoryRepository; + + @Override + public Optional findById(Long id) { + return subscriptionRepository.findById(id) + .map(SubscriptionEntity::toDomain); + } + + @Override + public List findByCategory(String categoryId) { + return subscriptionRepository.findByCategory(categoryId).stream() + .map(SubscriptionEntity::toDomain) + .collect(Collectors.toList()); + } + + @Override + public List findAllCategories() { + return categoryRepository.findAll().stream() + .map(CategoryEntity::toDomain) + .collect(Collectors.toList()); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/SecurityConfig.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/SecurityConfig.java new file mode 100644 index 0000000..13e3286 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/SecurityConfig.java @@ -0,0 +1,65 @@ +package com.unicorn.lifesub.mysub.infra.config; + +import com.unicorn.lifesub.mysub.infra.config.jwt.JwtAuthenticationFilter; +import com.unicorn.lifesub.mysub.infra.config.jwt.JwtTokenProvider; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.Arrays; +import java.util.List; + +@Configuration +@EnableWebSecurity +@SuppressWarnings("unused") +public class SecurityConfig { + protected final JwtTokenProvider jwtTokenProvider; + + @Value("${allowedorigins}") + private String allowedOrigins; + + public SecurityConfig(JwtTokenProvider jwtTokenProvider) { + this.jwtTokenProvider = jwtTokenProvider; + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .cors(cors -> cors + .configurationSource(corsConfigurationSource()) + ) + .csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs.yaml", "/v3/api-docs/**").permitAll() + .anyRequest().authenticated() + ) + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + ) + .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + protected CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Arrays.asList(allowedOrigins.split(","))); + configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(List.of("*")); + configuration.setAllowCredentials(true); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/SwaggerConfig.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/SwaggerConfig.java new file mode 100644 index 0000000..f268128 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/SwaggerConfig.java @@ -0,0 +1,28 @@ +package com.unicorn.lifesub.mysub.infra.config; + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SuppressWarnings("unused") +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + bearerFormat = "JWT", + scheme = "bearer" +) +public class SwaggerConfig { + + @Bean + public OpenAPI openAPI() { + return new OpenAPI() + .info(new Info() + .title("마이구독 서비스 API") + .version("v1.0.0") + .description("마이구독 서비스 API 명세서입니다.")); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/jwt/JwtAuthenticationFilter.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/jwt/JwtAuthenticationFilter.java new file mode 100644 index 0000000..de3ce16 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/jwt/JwtAuthenticationFilter.java @@ -0,0 +1,42 @@ +// CommonJwtAuthenticationFilter.java +package com.unicorn.lifesub.mysub.infra.config.jwt; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.NonNull; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class JwtAuthenticationFilter extends OncePerRequestFilter { + private final JwtTokenProvider jwtTokenProvider; + + public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) { + this.jwtTokenProvider = jwtTokenProvider; + } + + @Override + protected void doFilterInternal(@NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + @NonNull FilterChain filterChain) + throws ServletException, IOException { + String token = resolveToken(request); + + if (token != null && jwtTokenProvider.validateToken(token)) { + SecurityContextHolder.getContext().setAuthentication(jwtTokenProvider.getAuthentication(token)); + } + + filterChain.doFilter(request, response); + } + + private String resolveToken(HttpServletRequest request) { + String bearerToken = request.getHeader("Authorization"); + if (bearerToken != null && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); + } + return null; + } +} \ No newline at end of file diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/jwt/JwtTokenProvider.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/jwt/JwtTokenProvider.java new file mode 100644 index 0000000..b9b917f --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/config/jwt/JwtTokenProvider.java @@ -0,0 +1,58 @@ +// CommonJwtTokenProvider.java +package com.unicorn.lifesub.mysub.infra.config.jwt; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTVerificationException; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.unicorn.lifesub.common.exception.ErrorCode; +import com.unicorn.lifesub.common.exception.InfraException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; + +@Component +public class JwtTokenProvider { + private final Algorithm algorithm; + + public JwtTokenProvider(@Value("${jwt.secret}") String secretKey) { + this.algorithm = Algorithm.HMAC512(secretKey); + } + + public Authentication getAuthentication(String token) { + try { + DecodedJWT decodedJWT = JWT.decode(token); + String username = decodedJWT.getSubject(); + String[] authStrings = decodedJWT.getClaim("auth").asArray(String.class); + Collection authorities = Arrays.stream(authStrings) + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + UserDetails userDetails = new User(username, "", authorities); + + return new UsernamePasswordAuthenticationToken(userDetails, "", authorities); + } catch (Exception e) { + throw new InfraException(ErrorCode.INVALID_CREDENTIALS); + } + } + + public boolean validateToken(String token) { + try { + JWTVerifier verifier = JWT.require(algorithm).build(); + verifier.verify(token); + return true; + } catch (JWTVerificationException e) { + return false; + } + } +} \ No newline at end of file diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/CategoryController.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/CategoryController.java new file mode 100644 index 0000000..e035701 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/CategoryController.java @@ -0,0 +1,37 @@ +package com.unicorn.lifesub.mysub.infra.controller; + +import com.unicorn.lifesub.common.dto.ApiResponse; +import com.unicorn.lifesub.mysub.biz.dto.CategoryResponse; +import com.unicorn.lifesub.mysub.biz.dto.ServiceListResponse; +import com.unicorn.lifesub.mysub.biz.usecase.in.CategoryUseCase; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@Tag(name = "구독 카테고리 API", description = "구독 카테고리 관련 API") +@RestController +@RequestMapping("/api/mysub") +@RequiredArgsConstructor +public class CategoryController { + private final CategoryUseCase categoryUseCase; + + @Operation(summary = "전체 카테고리 목록 조회") + @GetMapping("/categories") + public ResponseEntity>> getAllCategories() { + return ResponseEntity.ok(ApiResponse.success(categoryUseCase.getAllCategories())); + } + + @Operation(summary = "카테고리별 서비스 목록 조회") + @GetMapping("/services") + public ResponseEntity>> getServicesByCategory( + @RequestParam String categoryId) { + return ResponseEntity.ok(ApiResponse.success(categoryUseCase.getServicesByCategory(categoryId))); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/MySubController.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/MySubController.java new file mode 100644 index 0000000..e626925 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/MySubController.java @@ -0,0 +1,37 @@ +package com.unicorn.lifesub.mysub.infra.controller; + +import com.unicorn.lifesub.common.dto.ApiResponse; +import com.unicorn.lifesub.mysub.biz.dto.MySubResponse; +import com.unicorn.lifesub.mysub.biz.dto.TotalFeeResponse; +import com.unicorn.lifesub.mysub.biz.usecase.in.MySubscriptionsUseCase; +import com.unicorn.lifesub.mysub.biz.usecase.in.TotalFeeUseCase; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@Tag(name = "마이구독 API", description = "마이구독 관련 API") +@RestController +@RequestMapping("/api/mysub") +@RequiredArgsConstructor +public class MySubController { + private final TotalFeeUseCase totalFeeUseCase; + private final MySubscriptionsUseCase mySubscriptionsUseCase; + + @Operation(summary = "총 구독료 조회", description = "사용자의 총 구독료를 조회합니다.") + @GetMapping("/total-fee") + public ResponseEntity> getTotalFee(@RequestParam String userId) { + TotalFeeResponse response = totalFeeUseCase.getTotalFee(userId); + return ResponseEntity.ok(ApiResponse.success(response)); + } + + @Operation(summary = "구독 목록 조회", description = "사용자의 구독 서비스 목록을 조회합니다.") + @GetMapping("/list") + public ResponseEntity>> getMySubscriptions(@RequestParam String userId) { + List response = mySubscriptionsUseCase.getMySubscriptions(userId); + return ResponseEntity.ok(ApiResponse.success(response)); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/ServiceController.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/ServiceController.java new file mode 100644 index 0000000..61108f7 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/controller/ServiceController.java @@ -0,0 +1,47 @@ +package com.unicorn.lifesub.mysub.infra.controller; + +import com.unicorn.lifesub.common.dto.ApiResponse; +import com.unicorn.lifesub.mysub.biz.dto.SubDetailResponse; +import com.unicorn.lifesub.mysub.biz.usecase.in.CancelSubscriptionUseCase; +import com.unicorn.lifesub.mysub.biz.usecase.in.SubscribeUseCase; +import com.unicorn.lifesub.mysub.biz.usecase.in.SubscriptionDetailUseCase; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@Tag(name = "구독 서비스 API", description = "구독 서비스 관련 API") +@RestController +@RequestMapping("/api/mysub/services") +@RequiredArgsConstructor +public class ServiceController { + private final SubscriptionDetailUseCase subscriptionDetailUseCase; + private final SubscribeUseCase subscribeUseCase; + private final CancelSubscriptionUseCase cancelSubscriptionUseCase; + + @Operation(summary = "구독 서비스 상세 조회") + @GetMapping("/{subscriptionId}") + public ResponseEntity> getSubscriptionDetail( + @PathVariable Long subscriptionId) { + return ResponseEntity.ok(ApiResponse.success( + subscriptionDetailUseCase.getSubscriptionDetail(subscriptionId))); + } + + @Operation(summary = "구독 신청") + @PostMapping("/{subscriptionId}/subscribe") + public ResponseEntity> subscribe( + @PathVariable Long subscriptionId, + @RequestParam String userId) { + subscribeUseCase.subscribe(subscriptionId, userId); + return ResponseEntity.ok(ApiResponse.success(null)); + } + + @Operation(summary = "구독 취소") + @DeleteMapping("/{subscriptionId}") + public ResponseEntity> cancel( + @PathVariable Long subscriptionId) { + cancelSubscriptionUseCase.cancel(subscriptionId); + return ResponseEntity.ok(ApiResponse.success(null)); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity.java new file mode 100644 index 0000000..59de44e --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/CategoryEntity.java @@ -0,0 +1,33 @@ +package com.unicorn.lifesub.mysub.infra.entity; + +import com.unicorn.lifesub.common.entity.BaseTimeEntity; +import com.unicorn.lifesub.mysub.biz.domain.Category; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; + +@Entity +@Table(name = "categories") +@Getter +@NoArgsConstructor +public class CategoryEntity extends BaseTimeEntity { + @Id + private String categoryId; + private String name; + + @Builder + public CategoryEntity(String categoryId, String name) { + this.categoryId = categoryId; + this.name = name; + } + + public Category toDomain() { + return Category.builder() + .categoryId(categoryId) + .name(name) + .build(); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity.java new file mode 100644 index 0000000..a5b227b --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/MySubscriptionEntity.java @@ -0,0 +1,38 @@ +package com.unicorn.lifesub.mysub.infra.entity; + +import com.unicorn.lifesub.mysub.biz.domain.MySubscription; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "my_subscriptions") +@Getter +@NoArgsConstructor +public class MySubscriptionEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String userId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "subscription_id") + private SubscriptionEntity subscription; + + @Builder + public MySubscriptionEntity(Long id, String userId, SubscriptionEntity subscription) { + this.id = id; + this.userId = userId; + this.subscription = subscription; + } + + public MySubscription toDomain() { + return MySubscription.builder() + .id(id) + .userId(userId) + .subscription(subscription.toDomain()) + .build(); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity.java new file mode 100644 index 0000000..dd21b3a --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/entity/SubscriptionEntity.java @@ -0,0 +1,49 @@ +package com.unicorn.lifesub.mysub.infra.entity; + +import com.unicorn.lifesub.common.entity.BaseTimeEntity; +import com.unicorn.lifesub.mysub.biz.domain.Subscription; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "subscriptions") +@Getter +@NoArgsConstructor +public class SubscriptionEntity extends BaseTimeEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + private String description; + private String category; + private int price; + private int maxSharedUsers; + private String logoUrl; + + @Builder + public SubscriptionEntity(Long id, String name, String description, String category, + int price, int maxSharedUsers, String logoUrl) { + this.id = id; + this.name = name; + this.description = description; + this.category = category; + this.price = price; + this.maxSharedUsers = maxSharedUsers; + this.logoUrl = logoUrl; + } + + public Subscription toDomain() { + return Subscription.builder() + .id(id) + .name(name) + .description(description) + .category(category) + .price(price) + .maxSharedUsers(maxSharedUsers) + .logoUrl(logoUrl) + .build(); + } +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/CategoryJpaRepository.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/CategoryJpaRepository.java new file mode 100644 index 0000000..655570f --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/CategoryJpaRepository.java @@ -0,0 +1,7 @@ +package com.unicorn.lifesub.mysub.infra.repository; + +import com.unicorn.lifesub.mysub.infra.entity.CategoryEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CategoryJpaRepository extends JpaRepository { +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/MySubscriptionJpaRepository.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/MySubscriptionJpaRepository.java new file mode 100644 index 0000000..bb8c9d8 --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/MySubscriptionJpaRepository.java @@ -0,0 +1,9 @@ +package com.unicorn.lifesub.mysub.infra.repository; + +import com.unicorn.lifesub.mysub.infra.entity.MySubscriptionEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + +public interface MySubscriptionJpaRepository extends JpaRepository { + List findByUserId(String userId); +} diff --git a/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/SubscriptionJpaRepository.java b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/SubscriptionJpaRepository.java new file mode 100644 index 0000000..fd0de3c --- /dev/null +++ b/mysub-infra/src/main/java/com/unicorn/lifesub/mysub/infra/repository/SubscriptionJpaRepository.java @@ -0,0 +1,11 @@ +package com.unicorn.lifesub.mysub.infra.repository; + +import com.unicorn.lifesub.mysub.infra.entity.SubscriptionEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +// SubscriptionJpaRepository.java에 메서드 추가 +public interface SubscriptionJpaRepository extends JpaRepository { + List findByCategory(String category); +} \ No newline at end of file diff --git a/mysub-infra/src/main/resources/application.yml b/mysub-infra/src/main/resources/application.yml new file mode 100644 index 0000000..b748511 --- /dev/null +++ b/mysub-infra/src/main/resources/application.yml @@ -0,0 +1,26 @@ +server: + port: ${SERVER_PORT:8082} + +spring: + application: + name: mysub-service + datasource: + url: jdbc:postgresql://${POSTGRES_HOST:localhost}:${POSTGRES_PORT:5432}/${POSTGRES_DB:mysub} + username: ${POSTGRES_USER:postgres} + password: ${POSTGRES_PASSWORD:postgres} + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: ${JPA_DDL_AUTO:validate} + show-sql: ${JPA_SHOW_SQL:false} + properties: + hibernate: + format_sql: true + +allowedorigins: ${ALLOWED_ORIGINS:*} + +springdoc: + swagger-ui: + path: /swagger-ui.html + api-docs: + path: /api-docs \ No newline at end of file diff --git a/recommend/build.gradle b/recommend/build.gradle new file mode 100644 index 0000000..83f5a32 --- /dev/null +++ b/recommend/build.gradle @@ -0,0 +1,7 @@ +dependencies { + implementation project(':common') + runtimeOnly 'org.postgresql:postgresql' +} +bootJar { + archiveFileName = "recommend.jar" +} diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/RecommendApplication.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/RecommendApplication.class new file mode 100644 index 0000000..9e6f07c Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/RecommendApplication.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/SecurityConfig.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/SecurityConfig.class new file mode 100644 index 0000000..1f07e16 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/SecurityConfig.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/SwaggerConfig.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/SwaggerConfig.class new file mode 100644 index 0000000..260d083 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/SwaggerConfig.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/jwt/JwtAuthenticationFilter.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/jwt/JwtAuthenticationFilter.class new file mode 100644 index 0000000..a84b4c9 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/jwt/JwtAuthenticationFilter.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/jwt/JwtTokenProvider.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/jwt/JwtTokenProvider.class new file mode 100644 index 0000000..a47c085 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/config/jwt/JwtTokenProvider.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/controller/RecommendController.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/controller/RecommendController.class new file mode 100644 index 0000000..cd9c225 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/controller/RecommendController.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/RecommendedCategory$RecommendedCategoryBuilder.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/RecommendedCategory$RecommendedCategoryBuilder.class new file mode 100644 index 0000000..976669c Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/RecommendedCategory$RecommendedCategoryBuilder.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/RecommendedCategory.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/RecommendedCategory.class new file mode 100644 index 0000000..3540c95 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/RecommendedCategory.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/SpendingCategory$SpendingCategoryBuilder.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/SpendingCategory$SpendingCategoryBuilder.class new file mode 100644 index 0000000..01b74b5 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/SpendingCategory$SpendingCategoryBuilder.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/SpendingCategory.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/SpendingCategory.class new file mode 100644 index 0000000..6112fa4 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/domain/SpendingCategory.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO$RecommendCategoryDTOBuilder.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO$RecommendCategoryDTOBuilder.class new file mode 100644 index 0000000..83d75f1 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO$RecommendCategoryDTOBuilder.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO.class new file mode 100644 index 0000000..7e6fbc1 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity$RecommendedCategoryEntityBuilder.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity$RecommendedCategoryEntityBuilder.class new file mode 100644 index 0000000..db95b2b Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity$RecommendedCategoryEntityBuilder.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity.class new file mode 100644 index 0000000..67f6c31 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity$SpendingEntityBuilder.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity$SpendingEntityBuilder.class new file mode 100644 index 0000000..9727f6a Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity$SpendingEntityBuilder.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity.class new file mode 100644 index 0000000..0a3aec3 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/jpa/RecommendRepository.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/jpa/RecommendRepository.class new file mode 100644 index 0000000..2c7316a Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/repository/jpa/RecommendRepository.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/RecommendService.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/RecommendService.class new file mode 100644 index 0000000..7d31527 Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/RecommendService.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/RecommendServiceImpl.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/RecommendServiceImpl.class new file mode 100644 index 0000000..b97e9ed Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/RecommendServiceImpl.class differ diff --git a/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/SpendingAnalyzer.class b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/SpendingAnalyzer.class new file mode 100644 index 0000000..1f5cdde Binary files /dev/null and b/recommend/build/classes/java/main/com/unicorn/lifesub/recommend/service/SpendingAnalyzer.class differ diff --git a/recommend/build/resources/main/application.yml b/recommend/build/resources/main/application.yml new file mode 100644 index 0000000..9083f84 --- /dev/null +++ b/recommend/build/resources/main/application.yml @@ -0,0 +1,26 @@ +server: + port: ${SERVER_PORT:8083} + +spring: + application: + name: recommend-service + datasource: + url: ${POSTGRES_URL} + username: ${POSTGRES_USER} + password: ${POSTGRES_PASSWORD} + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: ${JPA_DDL_AUTO:validate} + show-sql: ${JPA_SHOW_SQL:false} + properties: + hibernate: + format_sql: true + +allowedorigins: ${ALLOWED_ORIGINS:*} + +springdoc: + swagger-ui: + path: /swagger-ui.html + api-docs: + path: /api-docs diff --git a/recommend/build/tmp/compileJava/previous-compilation-data.bin b/recommend/build/tmp/compileJava/previous-compilation-data.bin new file mode 100644 index 0000000..b601dee Binary files /dev/null and b/recommend/build/tmp/compileJava/previous-compilation-data.bin differ diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/RecommendApplication.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/RecommendApplication.java new file mode 100644 index 0000000..58aec01 --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/RecommendApplication.java @@ -0,0 +1,12 @@ +package com.unicorn.lifesub.recommend; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication + +public class RecommendApplication { + public static void main(String[] args) { + SpringApplication.run(RecommendApplication.class, args); + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/config/SecurityConfig.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/config/SecurityConfig.java new file mode 100644 index 0000000..4e6975c --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/config/SecurityConfig.java @@ -0,0 +1,65 @@ +package com.unicorn.lifesub.recommend.config; + +import com.unicorn.lifesub.recommend.config.jwt.JwtAuthenticationFilter; +import com.unicorn.lifesub.recommend.config.jwt.JwtTokenProvider; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.Arrays; +import java.util.List; + +@Configuration +@EnableWebSecurity +@SuppressWarnings("unused") +public class SecurityConfig { + protected final JwtTokenProvider jwtTokenProvider; + + @Value("${allowedorigins}") + private String allowedOrigins; + + public SecurityConfig(JwtTokenProvider jwtTokenProvider) { + this.jwtTokenProvider = jwtTokenProvider; + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .cors(cors -> cors + .configurationSource(corsConfigurationSource()) + ) + .csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs.yaml", "/v3/api-docs/**").permitAll() + .anyRequest().authenticated() + ) + .sessionManagement(session -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + ) + .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } + + @Bean + protected CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Arrays.asList(allowedOrigins.split(","))); + configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(List.of("*")); + configuration.setAllowCredentials(true); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/config/SwaggerConfig.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/config/SwaggerConfig.java new file mode 100644 index 0000000..458213d --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/config/SwaggerConfig.java @@ -0,0 +1,28 @@ +package com.unicorn.lifesub.recommend.config; + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SuppressWarnings("unused") +@SecurityScheme( + name = "bearerAuth", + type = SecuritySchemeType.HTTP, + bearerFormat = "JWT", + scheme = "bearer" +) +public class SwaggerConfig { + + @Bean + public OpenAPI openAPI() { + return new OpenAPI() + .info(new Info() + .title("구독추천 서비스 API") + .version("v1.0.0") + .description("구독추천 서비스 API 명세서입니다.")); + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/config/jwt/JwtAuthenticationFilter.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/config/jwt/JwtAuthenticationFilter.java new file mode 100644 index 0000000..d6a8709 --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/config/jwt/JwtAuthenticationFilter.java @@ -0,0 +1,42 @@ +// CommonJwtAuthenticationFilter.java +package com.unicorn.lifesub.recommend.config.jwt; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.NonNull; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class JwtAuthenticationFilter extends OncePerRequestFilter { + private final JwtTokenProvider jwtTokenProvider; + + public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) { + this.jwtTokenProvider = jwtTokenProvider; + } + + @Override + protected void doFilterInternal(@NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + @NonNull FilterChain filterChain) + throws ServletException, IOException { + String token = resolveToken(request); + + if (token != null && jwtTokenProvider.validateToken(token)) { + SecurityContextHolder.getContext().setAuthentication(jwtTokenProvider.getAuthentication(token)); + } + + filterChain.doFilter(request, response); + } + + private String resolveToken(HttpServletRequest request) { + String bearerToken = request.getHeader("Authorization"); + if (bearerToken != null && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); + } + return null; + } +} \ No newline at end of file diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/config/jwt/JwtTokenProvider.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/config/jwt/JwtTokenProvider.java new file mode 100644 index 0000000..36ba8f8 --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/config/jwt/JwtTokenProvider.java @@ -0,0 +1,58 @@ +// CommonJwtTokenProvider.java +package com.unicorn.lifesub.recommend.config.jwt; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTVerificationException; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.unicorn.lifesub.common.exception.ErrorCode; +import com.unicorn.lifesub.common.exception.InfraException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; + +@Component +public class JwtTokenProvider { + private final Algorithm algorithm; + + public JwtTokenProvider(@Value("${jwt.secret}") String secretKey) { + this.algorithm = Algorithm.HMAC512(secretKey); + } + + public Authentication getAuthentication(String token) { + try { + DecodedJWT decodedJWT = JWT.decode(token); + String username = decodedJWT.getSubject(); + String[] authStrings = decodedJWT.getClaim("auth").asArray(String.class); + Collection authorities = Arrays.stream(authStrings) + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + UserDetails userDetails = new User(username, "", authorities); + + return new UsernamePasswordAuthenticationToken(userDetails, "", authorities); + } catch (Exception e) { + throw new InfraException(ErrorCode.INVALID_CREDENTIALS); + } + } + + public boolean validateToken(String token) { + try { + JWTVerifier verifier = JWT.require(algorithm).build(); + verifier.verify(token); + return true; + } catch (JWTVerificationException e) { + return false; + } + } +} \ No newline at end of file diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/controller/RecommendController.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/controller/RecommendController.java new file mode 100644 index 0000000..4a1e39d --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/controller/RecommendController.java @@ -0,0 +1,30 @@ +package com.unicorn.lifesub.recommend.controller; + +import com.unicorn.lifesub.common.dto.ApiResponse; +import com.unicorn.lifesub.recommend.dto.RecommendCategoryDTO; +import com.unicorn.lifesub.recommend.service.RecommendService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@Tag(name = "구독추천 API", description = "구독추천 관련 API") +@RestController +@RequestMapping("/api/recommend") +@RequiredArgsConstructor +public class RecommendController { + private final RecommendService recommendService; + + @Operation(summary = "추천 카테고리 조회", + description = "사용자의 지출 패턴을 분석하여 추천 구독 카테고리를 제공합니다.") + @GetMapping("/categories") + public ResponseEntity> getRecommendedCategory( + @RequestParam String userId) { + RecommendCategoryDTO response = recommendService.getRecommendedCategory(userId); + return ResponseEntity.ok(ApiResponse.success(response)); + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/domain/RecommendedCategory.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/domain/RecommendedCategory.java new file mode 100644 index 0000000..da300e1 --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/domain/RecommendedCategory.java @@ -0,0 +1,19 @@ +package com.unicorn.lifesub.recommend.domain; + +import lombok.Builder; +import lombok.Getter; +import java.time.LocalDate; + +@Getter +public class RecommendedCategory { + private final String spendingCategory; + private final String recommendCategory; + private final LocalDate baseDate; + + @Builder + public RecommendedCategory(String spendingCategory, String recommendCategory, LocalDate baseDate) { + this.spendingCategory = spendingCategory; + this.recommendCategory = recommendCategory; + this.baseDate = baseDate; + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/domain/SpendingCategory.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/domain/SpendingCategory.java new file mode 100644 index 0000000..d55fac2 --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/domain/SpendingCategory.java @@ -0,0 +1,16 @@ +package com.unicorn.lifesub.recommend.domain; + +import lombok.Builder; +import lombok.Getter; + +@Getter +public class SpendingCategory { + private final String category; + private final Long totalAmount; + + @Builder + public SpendingCategory(String category, Long totalAmount) { + this.category = category; + this.totalAmount = totalAmount; + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO.java new file mode 100644 index 0000000..820afdf --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/dto/RecommendCategoryDTO.java @@ -0,0 +1,13 @@ +package com.unicorn.lifesub.recommend.dto; + +import lombok.Builder; +import lombok.Getter; +import java.time.LocalDate; + +@Getter +@Builder +public class RecommendCategoryDTO { + private String categoryName; + private String imagePath; + private LocalDate baseDate; +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity.java new file mode 100644 index 0000000..85f5414 --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/entity/RecommendedCategoryEntity.java @@ -0,0 +1,35 @@ +package com.unicorn.lifesub.recommend.repository.entity; + +import com.unicorn.lifesub.recommend.domain.RecommendedCategory; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "recommended_categories") +@Getter +@NoArgsConstructor +public class RecommendedCategoryEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String spendingCategory; + private String recommendCategory; + + @Builder + public RecommendedCategoryEntity(Long id, String spendingCategory, String recommendCategory) { + this.id = id; + this.spendingCategory = spendingCategory; + this.recommendCategory = recommendCategory; + } + + public RecommendedCategory toDomain() { + return RecommendedCategory.builder() + .spendingCategory(spendingCategory) + .recommendCategory(recommendCategory) + .baseDate(java.time.LocalDate.now()) + .build(); + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity.java new file mode 100644 index 0000000..0ce18fc --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/entity/SpendingEntity.java @@ -0,0 +1,32 @@ +package com.unicorn.lifesub.recommend.repository.entity; + +import com.unicorn.lifesub.common.entity.BaseTimeEntity; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import java.time.LocalDate; + +@Entity +@Table(name = "spending_history") +@Getter +@NoArgsConstructor +public class SpendingEntity extends BaseTimeEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String userId; + private String category; + private Long amount; + private LocalDate spendingDate; + + @Builder + public SpendingEntity(Long id, String userId, String category, Long amount, LocalDate spendingDate) { + this.id = id; + this.userId = userId; + this.category = category; + this.amount = amount; + this.spendingDate = spendingDate; + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/jpa/RecommendRepository.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/jpa/RecommendRepository.java new file mode 100644 index 0000000..cc6f31a --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/repository/jpa/RecommendRepository.java @@ -0,0 +1,19 @@ +package com.unicorn.lifesub.recommend.repository.jpa; + +import com.unicorn.lifesub.recommend.repository.entity.RecommendedCategoryEntity; +import com.unicorn.lifesub.recommend.repository.entity.SpendingEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +public interface RecommendRepository extends JpaRepository { + Optional findBySpendingCategory(String category); + + @Query("SELECT s FROM SpendingEntity s WHERE s.userId = :userId AND s.spendingDate >= :startDate") + List findSpendingsByUserIdAndDateAfter(@Param("userId") String userId, + @Param("startDate") LocalDate startDate); +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/service/RecommendService.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/service/RecommendService.java new file mode 100644 index 0000000..49661e8 --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/service/RecommendService.java @@ -0,0 +1,7 @@ +package com.unicorn.lifesub.recommend.service; + +import com.unicorn.lifesub.recommend.dto.RecommendCategoryDTO; + +public interface RecommendService { + RecommendCategoryDTO getRecommendedCategory(String userId); +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/service/RecommendServiceImpl.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/service/RecommendServiceImpl.java new file mode 100644 index 0000000..656eb9c --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/service/RecommendServiceImpl.java @@ -0,0 +1,49 @@ +package com.unicorn.lifesub.recommend.service; + +import com.unicorn.lifesub.common.exception.BusinessException; +import com.unicorn.lifesub.common.exception.ErrorCode; +import com.unicorn.lifesub.recommend.domain.RecommendedCategory; +import com.unicorn.lifesub.recommend.domain.SpendingCategory; +import com.unicorn.lifesub.recommend.dto.RecommendCategoryDTO; +import com.unicorn.lifesub.recommend.repository.jpa.RecommendRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; + +@Service +@RequiredArgsConstructor +public class RecommendServiceImpl implements RecommendService { + private final RecommendRepository recommendRepository; + private final SpendingAnalyzer spendingAnalyzer; + + @Override + @Transactional(readOnly = true) + public RecommendCategoryDTO getRecommendedCategory(String userId) { + LocalDate startDate = LocalDate.now().minusMonths(1); + + SpendingCategory topSpending = spendingAnalyzer.analyzeSpending( + recommendRepository.findSpendingsByUserIdAndDateAfter(userId, startDate) + ); + + if (topSpending == null) { + throw new BusinessException(ErrorCode.NO_SPENDING_DATA); + } + + RecommendedCategory recommendedCategory = recommendRepository + .findBySpendingCategory(topSpending.getCategory()) + .orElseThrow(() -> new BusinessException(ErrorCode.NO_SPENDING_DATA)) + .toDomain(); + + return RecommendCategoryDTO.builder() + .categoryName(recommendedCategory.getRecommendCategory()) + .imagePath(getCategoryImagePath(recommendedCategory.getRecommendCategory())) + .baseDate(recommendedCategory.getBaseDate()) + .build(); + } + + private String getCategoryImagePath(String category) { + return "/images/categories/" + category.toLowerCase() + ".png"; + } +} diff --git a/recommend/src/main/java/com/unicorn/lifesub/recommend/service/SpendingAnalyzer.java b/recommend/src/main/java/com/unicorn/lifesub/recommend/service/SpendingAnalyzer.java new file mode 100644 index 0000000..e2a9adc --- /dev/null +++ b/recommend/src/main/java/com/unicorn/lifesub/recommend/service/SpendingAnalyzer.java @@ -0,0 +1,35 @@ +package com.unicorn.lifesub.recommend.service; + +import com.unicorn.lifesub.recommend.domain.SpendingCategory; +import com.unicorn.lifesub.recommend.repository.entity.SpendingEntity; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +public class SpendingAnalyzer { + public SpendingCategory analyzeSpending(List spendings) { + Map totalsByCategory = calculateTotalByCategory(spendings); + return findTopCategory(totalsByCategory); + } + + private Map calculateTotalByCategory(List spendings) { + return spendings.stream() + .collect(Collectors.groupingBy( + SpendingEntity::getCategory, + Collectors.summingLong(SpendingEntity::getAmount) + )); + } + + private SpendingCategory findTopCategory(Map totals) { + return totals.entrySet().stream() + .max(Map.Entry.comparingByValue()) + .map(entry -> SpendingCategory.builder() + .category(entry.getKey()) + .totalAmount(entry.getValue()) + .build()) + .orElse(null); + } +} diff --git a/recommend/src/main/resources/application.yml b/recommend/src/main/resources/application.yml new file mode 100644 index 0000000..ce29afd --- /dev/null +++ b/recommend/src/main/resources/application.yml @@ -0,0 +1,26 @@ +server: + port: ${SERVER_PORT:8083} + +spring: + application: + name: recommend-service + datasource: + url: jdbc:postgresql://${POSTGRES_HOST:localhost}:${POSTGRES_PORT:5432}/${POSTGRES_DB:recommend} + username: ${POSTGRES_USER:postgres} + password: ${POSTGRES_PASSWORD:postgres} + driver-class-name: org.postgresql.Driver + jpa: + hibernate: + ddl-auto: ${JPA_DDL_AUTO:validate} + show-sql: ${JPA_SHOW_SQL:false} + properties: + hibernate: + format_sql: true + +allowedorigins: ${ALLOWED_ORIGINS:*} + +springdoc: + swagger-ui: + path: /swagger-ui.html + api-docs: + path: /api-docs diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..1703db5 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,7 @@ +rootProject.name = 'lifesub' + +include 'common' +include 'member' +include 'mysub-biz' +include 'mysub-infra' +include 'recommend'