diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..675f927 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### 민감정보!! ### +.env +application.yml + + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/10th_UMC_Spring_Boot b/10th_UMC_Spring_Boot new file mode 160000 index 0000000..b0c00f4 --- /dev/null +++ b/10th_UMC_Spring_Boot @@ -0,0 +1 @@ +Subproject commit b0c00f4bcbf2cc898e153ad6bac7a75725801215 diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..5705f15 --- /dev/null +++ b/build.gradle @@ -0,0 +1,46 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.0.6' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' +description = 'umc10th' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-webmvc' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-security' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testCompileOnly 'org.projectlombok:lombok' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testAnnotationProcessor 'org.projectlombok:lombok' + + // Swagger + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.0.1' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.1' + + // Security + implementation 'org.springframework.boot:spring-boot-starter-security' + testImplementation 'org.springframework.security:spring-security-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc 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..c61a118 --- /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-9.4.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..739907d --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/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 -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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 + + + +# 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" ) + + 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, 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +: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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..67a1b8e --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'umc10th' diff --git a/src/main/java/com/example/umc10th/Umc10thApplication.java b/src/main/java/com/example/umc10th/Umc10thApplication.java new file mode 100644 index 0000000..9202ae8 --- /dev/null +++ b/src/main/java/com/example/umc10th/Umc10thApplication.java @@ -0,0 +1,15 @@ +package com.example.umc10th; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +@EnableJpaAuditing +public class Umc10thApplication { + + public static void main(String[] args) { + SpringApplication.run(Umc10thApplication.class, args); + } + +} diff --git a/src/main/java/com/example/umc10th/domain/member/controller/MemberController.java b/src/main/java/com/example/umc10th/domain/member/controller/MemberController.java new file mode 100644 index 0000000..9a886d4 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/controller/MemberController.java @@ -0,0 +1,44 @@ +package com.example.umc10th.domain.member.controller; + +import com.example.umc10th.domain.member.dto.MemberReqDTO; +import com.example.umc10th.domain.member.dto.MemberResDTO; +import com.example.umc10th.domain.member.exception.code.MemberSuccessCode; +import com.example.umc10th.domain.member.service.MemberService; +import com.example.umc10th.global.apiPayload.ApiResponse; +import com.example.umc10th.global.apiPayload.code.BaseSuccessCode; +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.HttpStatus; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api") +@Tag(name = "Member", description = "회원 관련 API") +public class MemberController { + + private final MemberService memberService; + + // 회원가입 - Public API (로그인 불필요) + @Operation(summary = "회원가입", description = "이메일/비밀번호로 회원가입합니다. 비밀번호는 BCrypt 로 솔트 처리되어 저장됩니다.") + @ResponseStatus(HttpStatus.CREATED) + @PostMapping("/v1/auth/signup") + public ApiResponse signUp( + @RequestBody @Valid MemberReqDTO.SignUp dto + ){ + BaseSuccessCode code = MemberSuccessCode.MEMBER_CREATED; + return ApiResponse.onSuccess(code, memberService.signUp(dto)); + } + + // 마이페이지 - Private API (로그인 필요) + @Operation(summary = "마이페이지 조회", description = "회원 정보를 조회합니다. (인증 필요)") + @PostMapping("/v1/users/me") + public ApiResponse getInfo( + @RequestBody @Valid MemberReqDTO.GetInfo dto + ){ + BaseSuccessCode code = MemberSuccessCode.OK; + return ApiResponse.onSuccess(code, memberService.getInfo(dto)); + } +} diff --git a/src/main/java/com/example/umc10th/domain/member/converter/MemberConverter.java b/src/main/java/com/example/umc10th/domain/member/converter/MemberConverter.java new file mode 100644 index 0000000..8572332 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/converter/MemberConverter.java @@ -0,0 +1,36 @@ +package com.example.umc10th.domain.member.converter; + +import com.example.umc10th.domain.member.dto.MemberReqDTO; +import com.example.umc10th.domain.member.dto.MemberResDTO; +import com.example.umc10th.domain.member.entity.Member; + +public class MemberConverter { + public static MemberResDTO.GetInfo toGetInfo(Member member){ + return MemberResDTO.GetInfo.builder() + .email(member.getEmail()) + .name(member.getName()) + .point(member.getPoint()) + .phoneNumber(member.getPhoneNumber()) + .profileUrl(member.getProfileUrl()) + .build(); + } + + // 회원가입 요청 DTO + 암호화된 비밀번호 -> Member 엔티티 + public static Member toMember(MemberReqDTO.SignUp dto, String encodedPassword){ + return Member.builder() + .name(dto.name()) + .email(dto.email()) + .password(encodedPassword) + .build(); + } + + // 저장된 Member -> 회원가입 응답 DTO + public static MemberResDTO.SignUp toSignUpResult(Member member){ + return MemberResDTO.SignUp.builder() + .memberId(member.getId()) + .name(member.getName()) + .email(member.getEmail()) + .createdAt(member.getCreatedAt()) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/dto/MemberReqDTO.java b/src/main/java/com/example/umc10th/domain/member/dto/MemberReqDTO.java new file mode 100644 index 0000000..3ffefeb --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/dto/MemberReqDTO.java @@ -0,0 +1,33 @@ +package com.example.umc10th.domain.member.dto; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.Size; + +public class MemberReqDTO { + + // 회원 조회를 위해 요청에 필요한 id값만 받습니다. + public record GetInfo( + @NotNull(message = "회원 ID는 필수입니다.") + @Positive(message = "회원 ID는 0보다 커야 합니다.") + Long id + ){} + + // 회원가입(폼 로그인) 요청: 이름 + 이메일 + 비밀번호를 받습니다. + public record SignUp( + @NotBlank(message = "이름은 필수입니다.") + @Size(max = 30, message = "이름은 30자 이하여야 합니다.") + String name, + + @NotBlank(message = "이메일은 필수입니다.") + @Email(message = "올바른 이메일 형식이 아닙니다.") + @Size(max = 100, message = "이메일은 100자 이하여야 합니다.") + String email, + + @NotBlank(message = "비밀번호는 필수입니다.") + @Size(min = 8, max = 64, message = "비밀번호는 8자 이상 64자 이하여야 합니다.") + String password + ){} +} diff --git a/src/main/java/com/example/umc10th/domain/member/dto/MemberResDTO.java b/src/main/java/com/example/umc10th/domain/member/dto/MemberResDTO.java new file mode 100644 index 0000000..c454fe9 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/dto/MemberResDTO.java @@ -0,0 +1,26 @@ +package com.example.umc10th.domain.member.dto; + +import lombok.Builder; + +import java.time.LocalDateTime; + +public class MemberResDTO { + + // 회원가입 결과: 비밀번호는 응답에 절대 포함하지 않습니다. + @Builder + public record SignUp( + Long memberId, + String name, + String email, + LocalDateTime createdAt + ){} + + @Builder + public record GetInfo( + String name, + String profileUrl, + String email, + String phoneNumber, + Integer point + ){} +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/entity/Food.java b/src/main/java/com/example/umc10th/domain/member/entity/Food.java new file mode 100644 index 0000000..8b718e8 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/entity/Food.java @@ -0,0 +1,24 @@ +package com.example.umc10th.domain.member.entity; + +import com.example.umc10th.domain.member.enums.FoodName; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "food") +public class Food { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + @Enumerated(EnumType.STRING) + private FoodName name; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/entity/Member.java b/src/main/java/com/example/umc10th/domain/member/entity/Member.java new file mode 100644 index 0000000..5422d95 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/entity/Member.java @@ -0,0 +1,91 @@ +package com.example.umc10th.domain.member.entity; + +import com.example.umc10th.domain.member.entity.mapping.MemberFood; +import com.example.umc10th.domain.member.entity.mapping.MemberTerm; +import com.example.umc10th.domain.member.enums.Gender; +import com.example.umc10th.domain.member.enums.SocialType; +import com.example.umc10th.domain.mission.entity.mapping.MemberMission; +import com.example.umc10th.domain.mission.enums.Address; +import com.example.umc10th.domain.review.entity.Review; +import com.example.umc10th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Table(name = "member") +public class Member extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name", nullable = false, length = 30) + private String name; + + @Column(name = "nickname", length = 30) + private String nickname; + + @Column(name = "email", length = 100) + private String email; + + // 폼 로그인용 비밀번호 (BCrypt 해시 저장, 소셜 로그인 회원은 null 가능) + @Column(name = "password", length = 200) + private String password; + + @Column(name = "phone_number", length = 20) + private String phoneNumber; + + @Column(name = "profile_url", length = 500) + private String profileUrl; + + @Column(name = "point", nullable = false) + @Builder.Default + private Integer point = 0; + + @Column(name = "gender", nullable = false) + @Enumerated(EnumType.STRING) + @Builder.Default + private Gender gender = Gender.NONE; + + @Column(name = "birth") + private LocalDate birth; + + @Column(name = "address") + @Enumerated(EnumType.STRING) + private Address address; + + @Column(name = "detail_address", length = 200) + private String detailAddress; + + @Column(name = "social_type") + @Enumerated(EnumType.STRING) + private SocialType socialType; + + @Column(name = "social_id") + private String socialUid; + + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + @Builder.Default + private List memberFoodList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + @Builder.Default + private List memberTermList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + @Builder.Default + private List memberMissionList = new ArrayList<>(); + + @OneToMany(mappedBy = "member", cascade = CascadeType.ALL) + @Builder.Default + private List reviewList = new ArrayList<>(); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/entity/Term.java b/src/main/java/com/example/umc10th/domain/member/entity/Term.java new file mode 100644 index 0000000..9934b94 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/entity/Term.java @@ -0,0 +1,24 @@ +package com.example.umc10th.domain.member.entity; + +import com.example.umc10th.domain.member.enums.TermName; // ⭐ 이 부분이 추가되어야 합니다! +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "term") +public class Term { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + @Enumerated(EnumType.STRING) + private TermName name; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/entity/mapping/MemberFood.java b/src/main/java/com/example/umc10th/domain/member/entity/mapping/MemberFood.java new file mode 100644 index 0000000..6dccd34 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/entity/mapping/MemberFood.java @@ -0,0 +1,30 @@ +package com.example.umc10th.domain.member.entity.mapping; + +import com.example.umc10th.domain.member.entity.Food; +import com.example.umc10th.domain.member.entity.Member; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "member_food") +public class MemberFood { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "food_id") + private Food food; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/entity/mapping/MemberTerm.java b/src/main/java/com/example/umc10th/domain/member/entity/mapping/MemberTerm.java new file mode 100644 index 0000000..957fbc7 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/entity/mapping/MemberTerm.java @@ -0,0 +1,30 @@ +package com.example.umc10th.domain.member.entity.mapping; + +import com.example.umc10th.domain.member.entity.Member; +import com.example.umc10th.domain.member.entity.Term; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "member_term") +public class MemberTerm { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id") + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "term_id") + private Term term; +} diff --git a/src/main/java/com/example/umc10th/domain/member/enums/FoodName.java b/src/main/java/com/example/umc10th/domain/member/enums/FoodName.java new file mode 100644 index 0000000..e1bd9f2 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/enums/FoodName.java @@ -0,0 +1,5 @@ +package com.example.umc10th.domain.member.enums; + +public enum FoodName { + KOREAN, WESTERN, CHINESE, JAPANESE // 예시 음식 카테고리 +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/enums/Gender.java b/src/main/java/com/example/umc10th/domain/member/enums/Gender.java new file mode 100644 index 0000000..0a13b3d --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/enums/Gender.java @@ -0,0 +1,5 @@ +package com.example.umc10th.domain.member.enums; + +public enum Gender { + MALE, FEMALE, NONE +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/enums/SocialType.java b/src/main/java/com/example/umc10th/domain/member/enums/SocialType.java new file mode 100644 index 0000000..bd7112f --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/enums/SocialType.java @@ -0,0 +1,8 @@ +package com.example.umc10th.domain.member.enums; + +public enum SocialType { + KAKAO, + GOOGLE, + NAVER, + APPLE +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/enums/TermName.java b/src/main/java/com/example/umc10th/domain/member/enums/TermName.java new file mode 100644 index 0000000..71818e8 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/enums/TermName.java @@ -0,0 +1,5 @@ +package com.example.umc10th.domain.member.enums; + +public enum TermName { + TERMS_OF_SERVICE, PRIVACY_POLICY, MARKETING_CONSENT // 예시 약관 종류 +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/exception/MemberException.java b/src/main/java/com/example/umc10th/domain/member/exception/MemberException.java new file mode 100644 index 0000000..c1a9dfc --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/exception/MemberException.java @@ -0,0 +1,10 @@ +package com.example.umc10th.domain.member.exception; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import com.example.umc10th.global.apiPayload.exception.ProjectException; + +public class MemberException extends ProjectException { + public MemberException(BaseErrorCode errorCode) { + super(errorCode); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/exception/code/MemberErrorCode.java b/src/main/java/com/example/umc10th/domain/member/exception/code/MemberErrorCode.java new file mode 100644 index 0000000..285b6e0 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/exception/code/MemberErrorCode.java @@ -0,0 +1,18 @@ +package com.example.umc10th.domain.member.exception.code; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum MemberErrorCode implements BaseErrorCode { + MEMBER_NOT_FOUND(HttpStatus.NOT_FOUND, "MEMBER404_1", "해당 회원을 찾을 수 없습니다."), + MEMBER_EMAIL_DUPLICATE(HttpStatus.CONFLICT, "MEMBER409_1", "이미 가입된 이메일입니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/exception/code/MemberSuccessCode.java b/src/main/java/com/example/umc10th/domain/member/exception/code/MemberSuccessCode.java new file mode 100644 index 0000000..3000be1 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/exception/code/MemberSuccessCode.java @@ -0,0 +1,23 @@ +package com.example.umc10th.domain.member.exception.code; + +import com.example.umc10th.global.apiPayload.code.BaseSuccessCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum MemberSuccessCode implements BaseSuccessCode { + + OK(HttpStatus.OK, + "MEMBER200_1", + "성공적으로 유저를 조회했습니다."), + MEMBER_CREATED(HttpStatus.CREATED, + "MEMBER201_1", + "회원가입에 성공했습니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc10th/domain/member/repository/MemberRepository.java b/src/main/java/com/example/umc10th/domain/member/repository/MemberRepository.java new file mode 100644 index 0000000..4f83433 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/repository/MemberRepository.java @@ -0,0 +1,10 @@ +package com.example.umc10th.domain.member.repository; + +import com.example.umc10th.domain.member.entity.Member; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MemberRepository extends JpaRepository { + + // 회원가입 시 이메일 중복 검증에 사용 + boolean existsByEmail(String email); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/member/service/MemberService.java b/src/main/java/com/example/umc10th/domain/member/service/MemberService.java new file mode 100644 index 0000000..f26e847 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/member/service/MemberService.java @@ -0,0 +1,49 @@ +package com.example.umc10th.domain.member.service; + +import com.example.umc10th.domain.member.converter.MemberConverter; +import com.example.umc10th.domain.member.dto.MemberReqDTO; +import com.example.umc10th.domain.member.dto.MemberResDTO; +import com.example.umc10th.domain.member.exception.MemberException; +import com.example.umc10th.domain.member.exception.code.MemberErrorCode; +import com.example.umc10th.domain.member.repository.MemberRepository; +import com.example.umc10th.domain.member.entity.Member; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class MemberService { + private final MemberRepository memberRepository; + private final PasswordEncoder passwordEncoder; + + @Transactional(readOnly = true) + public MemberResDTO.GetInfo getInfo(MemberReqDTO.GetInfo dto){ + Long memberId = dto.id(); + Member member = memberRepository.findById(memberId) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + return MemberConverter.toGetInfo(member); + } + + /** + * 회원가입 (폼 로그인용) + * - 이메일 중복 검증 + * - 비밀번호는 BCrypt 로 솔트 처리하여 저장 (평문 저장 금지) + */ + @Transactional + public MemberResDTO.SignUp signUp(MemberReqDTO.SignUp dto){ + // 이메일 중복 검증 + if (memberRepository.existsByEmail(dto.email())) { + throw new MemberException(MemberErrorCode.MEMBER_EMAIL_DUPLICATE); + } + + // BCrypt 솔트 처리 (PasswordEncoder.encode 가 솔트를 자동 생성/포함) + String encodedPassword = passwordEncoder.encode(dto.password()); + + Member member = MemberConverter.toMember(dto, encodedPassword); + Member savedMember = memberRepository.save(member); + + return MemberConverter.toSignUpResult(savedMember); + } +} diff --git a/src/main/java/com/example/umc10th/domain/mission/controller/MissionController.java b/src/main/java/com/example/umc10th/domain/mission/controller/MissionController.java new file mode 100644 index 0000000..3ab5f1d --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/controller/MissionController.java @@ -0,0 +1,37 @@ +package com.example.umc10th.domain.mission.controller; + +import com.example.umc10th.domain.mission.dto.MissionReqDTO; +import com.example.umc10th.domain.mission.dto.MissionResDTO; +import com.example.umc10th.domain.mission.enums.MissionStatus; +import com.example.umc10th.domain.mission.exception.code.MissionSuccessCode; +import com.example.umc10th.domain.mission.service.MissionService; +import com.example.umc10th.global.apiPayload.ApiResponse; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v1/members/me/missions") +public class MissionController { + + private final MissionService missionService; + + /** + * 내가 진행중인 미션 조회 (오프셋 기반 페이지네이션) + * - 사용자 ID는 Request Body 로 받음 (하드코딩 X) + * - status, page, size 는 쿼리 파라미터로 받음 + */ + @GetMapping + public ApiResponse getMyMissions( + @RequestBody @Valid MissionReqDTO.GetMyMissions request, + @RequestParam(defaultValue = "ONGOING") MissionStatus status, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int size + ) { + MissionResDTO.MyMissionPreViewListDTO result = + missionService.getMyMissions(request.memberId(), status, page, size); + + return ApiResponse.onSuccess(MissionSuccessCode.OK, result); + } +} diff --git a/src/main/java/com/example/umc10th/domain/mission/converter/MissionConverter.java b/src/main/java/com/example/umc10th/domain/mission/converter/MissionConverter.java new file mode 100644 index 0000000..bc77f28 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/converter/MissionConverter.java @@ -0,0 +1,45 @@ +package com.example.umc10th.domain.mission.converter; + +import com.example.umc10th.domain.mission.dto.MissionResDTO; +import com.example.umc10th.domain.mission.enums.MissionStatus; +import com.example.umc10th.domain.mission.entity.mapping.MemberMission; +import org.springframework.data.domain.Page; + +import java.util.List; + +public class MissionConverter { + + private static String toStatusText(MissionStatus status) { + return switch (status) { + case ONGOING -> "진행중"; + case COMPLETED -> "성공"; + }; + } + + public static MissionResDTO.MyMissionPreViewDTO toMyMissionPreViewDTO(MemberMission memberMission) { + return MissionResDTO.MyMissionPreViewDTO.builder() + .missionId(memberMission.getMission().getId()) + .storeName(memberMission.getMission().getStore().getName()) + .rewardPoint(memberMission.getMission().getReward()) + .missionSpec(memberMission.getMission().getContent()) + .status(toStatusText(memberMission.getStatus())) + .build(); + } + + public static MissionResDTO.MyMissionPreViewListDTO toMyMissionPreViewListDTO( + Page page + ) { + List missionList = page.getContent().stream() + .map(MissionConverter::toMyMissionPreViewDTO) + .toList(); + + return MissionResDTO.MyMissionPreViewListDTO.builder() + .missionList(missionList) + .listSize(missionList.size()) + .totalPage(page.getTotalPages()) + .totalElements(page.getTotalElements()) + .isFirst(page.isFirst()) + .isLast(page.isLast()) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/dto/MissionReqDTO.java b/src/main/java/com/example/umc10th/domain/mission/dto/MissionReqDTO.java new file mode 100644 index 0000000..ab92819 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/dto/MissionReqDTO.java @@ -0,0 +1,31 @@ +package com.example.umc10th.domain.mission.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.Size; + +import java.time.LocalDate; + +public class MissionReqDTO { + + public record CreateMission( + @NotNull(message = "마감일은 필수입니다.") + LocalDate deadline, + + @NotNull(message = "보상 포인트는 필수입니다.") + @Positive(message = "보상 포인트는 0보다 커야 합니다.") + Integer point, + + @NotBlank(message = "미션 조건은 필수입니다.") + @Size(max = 200, message = "미션 조건은 200자 이하여야 합니다.") + String conditional + ){} + + // 내가 진행중인 미션 조회를 위한 Request Body + public record GetMyMissions( + @NotNull(message = "회원 ID는 필수입니다.") + @Positive(message = "회원 ID는 0보다 커야 합니다.") + Long memberId + ){} +} diff --git a/src/main/java/com/example/umc10th/domain/mission/dto/MissionResDTO.java b/src/main/java/com/example/umc10th/domain/mission/dto/MissionResDTO.java new file mode 100644 index 0000000..314faf4 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/dto/MissionResDTO.java @@ -0,0 +1,44 @@ +package com.example.umc10th.domain.mission.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.List; + +public class MissionResDTO { + + // 화면에 뿌려질 미션 리스트와 페이징 정보를 담는 객체 + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MyMissionPreViewListDTO { + private List missionList; + private Integer listSize; + private Integer totalPage; + private Long totalElements; + private Boolean isFirst; + private Boolean isLast; + } + + // 개별 미션 정보 (Figma 화면의 카드 1개에 해당) + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MyMissionPreViewDTO { + private Long missionId; + private String storeName; + private Integer rewardPoint; // 예: 500 + private String missionSpec; // 예: "12,000원 이상의 식사를 하세요!" + private String status; // 예: "진행중", "성공" + } + + public record GetMission( + Long missionId, + Integer point, + String conditional + ) {} +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/entity/Location.java b/src/main/java/com/example/umc10th/domain/mission/entity/Location.java new file mode 100644 index 0000000..ccc8b7e --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/entity/Location.java @@ -0,0 +1,34 @@ +package com.example.umc10th.domain.mission.entity; + +import com.example.umc10th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Table(name = "location") +public class Location extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 30) + private String province; + + @Column(nullable = false, length = 30) + private String city; + + @Column(nullable = false, length = 30) + private String district; + + @OneToMany(mappedBy = "location", cascade = CascadeType.ALL) + @Builder.Default + private List storeList = new ArrayList<>(); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/entity/Mission.java b/src/main/java/com/example/umc10th/domain/mission/entity/Mission.java new file mode 100644 index 0000000..0042d62 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/entity/Mission.java @@ -0,0 +1,45 @@ +package com.example.umc10th.domain.mission.entity; + +import com.example.umc10th.domain.mission.entity.mapping.MemberMission; +import com.example.umc10th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Table(name = "mission") +public class Mission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // 보상 포인트 (예: 500P) + @Column(nullable = false) + private Integer reward; + + // 미션 내용 (예: "12,000원 이상의 식사를 하세요!") + @Column(nullable = false, length = 200) + private String content; + + // 미션 마감일 (예: D-7) + @Column(name = "deadline") + private LocalDate deadline; + + // 어느 가게의 미션인지 연관관계 매핑 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id", nullable = false) + private Store store; + + // 회원-미션 매핑 (역방향) + @OneToMany(mappedBy = "mission", cascade = CascadeType.ALL) + @Builder.Default + private List memberMissionList = new ArrayList<>(); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/entity/Store.java b/src/main/java/com/example/umc10th/domain/mission/entity/Store.java new file mode 100644 index 0000000..57ab15d --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/entity/Store.java @@ -0,0 +1,48 @@ +package com.example.umc10th.domain.mission.entity; + +import com.example.umc10th.domain.review.entity.Review; +import com.example.umc10th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Table(name = "store") +public class Store extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + // 가게 이름 (예: 반이학생마라탕) + @Column(nullable = false, length = 50) + private String name; + + // 가게 주소 + @Column(nullable = false, length = 100) + private String address; + + // 가게 평점 (기획에 따라 생략 가능) + private Float score; + + // 지역(동) 연관관계 매핑 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "location_id") + private Location location; + + // 미션 목록 (역방향) + @OneToMany(mappedBy = "store", cascade = CascadeType.ALL) + @Builder.Default + private List missionList = new ArrayList<>(); + + // 리뷰 목록 (역방향) + @OneToMany(mappedBy = "store", cascade = CascadeType.ALL) + @Builder.Default + private List reviewList = new ArrayList<>(); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/entity/mapping/MemberMission.java b/src/main/java/com/example/umc10th/domain/mission/entity/mapping/MemberMission.java new file mode 100644 index 0000000..f4f21de --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/entity/mapping/MemberMission.java @@ -0,0 +1,34 @@ +package com.example.umc10th.domain.mission.entity.mapping; + +import com.example.umc10th.domain.member.entity.Member; +import com.example.umc10th.domain.mission.entity.Mission; +import com.example.umc10th.domain.mission.enums.MissionStatus; +import com.example.umc10th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Table(name = "member_mission") +public class MemberMission extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Enumerated(EnumType.STRING) + @Column(columnDefinition = "VARCHAR(15) DEFAULT 'ONGOING'") + @Builder.Default + private MissionStatus status = MissionStatus.ONGOING; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id", nullable = false) + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "mission_id", nullable = false) + private Mission mission; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/enums/Address.java b/src/main/java/com/example/umc10th/domain/mission/enums/Address.java new file mode 100644 index 0000000..f213c63 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/enums/Address.java @@ -0,0 +1,21 @@ +package com.example.umc10th.domain.mission.enums; + +public enum Address { + SEOUL, + BUSAN, + INCHEON, + DAEGU, + GWANGJU, + DAEJEON, + ULSAN, + SEJONG, + GYEONGGI, + GANGWON, + CHUNGBUK, + CHUNGNAM, + JEONBUK, + JEONNAM, + GYEONGBUK, + GYEONGNAM, + JEJU +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/enums/MissionStatus.java b/src/main/java/com/example/umc10th/domain/mission/enums/MissionStatus.java new file mode 100644 index 0000000..2b5b71a --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/enums/MissionStatus.java @@ -0,0 +1,6 @@ +package com.example.umc10th.domain.mission.enums; + +public enum MissionStatus { + ONGOING, + COMPLETED +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/exception/MissionException.java b/src/main/java/com/example/umc10th/domain/mission/exception/MissionException.java new file mode 100644 index 0000000..71cae57 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/exception/MissionException.java @@ -0,0 +1,10 @@ +package com.example.umc10th.domain.mission.exception; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import com.example.umc10th.global.apiPayload.exception.ProjectException; + +public class MissionException extends ProjectException { + public MissionException(BaseErrorCode errorCode) { + super(errorCode); + } +} diff --git a/src/main/java/com/example/umc10th/domain/mission/exception/code/MissionErrorCode.java b/src/main/java/com/example/umc10th/domain/mission/exception/code/MissionErrorCode.java new file mode 100644 index 0000000..4add556 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/exception/code/MissionErrorCode.java @@ -0,0 +1,18 @@ +package com.example.umc10th.domain.mission.exception.code; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum MissionErrorCode implements BaseErrorCode { + MISSION_NOT_FOUND(HttpStatus.NOT_FOUND, "MISSION404_1", "해당 미션을 찾을 수 없습니다."), + STORE_NOT_FOUND(HttpStatus.NOT_FOUND, "MISSION404_2", "해당 가게를 찾을 수 없습니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc10th/domain/mission/exception/code/MissionSuccessCode.java b/src/main/java/com/example/umc10th/domain/mission/exception/code/MissionSuccessCode.java new file mode 100644 index 0000000..3e2fc94 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/exception/code/MissionSuccessCode.java @@ -0,0 +1,22 @@ +package com.example.umc10th.domain.mission.exception.code; + +import com.example.umc10th.global.apiPayload.code.BaseSuccessCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum MissionSuccessCode implements BaseSuccessCode { + CREATED(HttpStatus.OK, + "MISSION200_1", + "성공적으로 미션을 생성했습니다."), + OK(HttpStatus.OK, + "MISSION200_2", + "성공적으로 미션을 조회했습니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc10th/domain/mission/repository/MemberMissionRepository.java b/src/main/java/com/example/umc10th/domain/mission/repository/MemberMissionRepository.java new file mode 100644 index 0000000..c9c885c --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/repository/MemberMissionRepository.java @@ -0,0 +1,33 @@ +package com.example.umc10th.domain.mission.repository; + +import com.example.umc10th.domain.mission.entity.mapping.MemberMission; +import com.example.umc10th.domain.mission.enums.MissionStatus; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface MemberMissionRepository extends JpaRepository { + + @Query("SELECT COUNT(mm) FROM MemberMission mm " + + "WHERE mm.member.id = :memberId AND mm.status = com.example.umc10th.domain.mission.enums.MissionStatus.ONGOING") + int countOngoingByMemberId(@Param("memberId") Long memberId); + + @Query( + value = "SELECT mm FROM MemberMission mm " + + "JOIN FETCH mm.mission m " + + "JOIN FETCH m.store s " + + "WHERE mm.member.id = :memberId " + + "AND mm.status = :status " + + "ORDER BY mm.createdAt DESC", + countQuery = "SELECT COUNT(mm) FROM MemberMission mm " + + "WHERE mm.member.id = :memberId " + + "AND mm.status = :status" + ) + Page findMyMissionsByStatus( + @Param("memberId") Long memberId, + @Param("status") MissionStatus status, + Pageable pageable + ); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/repository/MissionRepository.java b/src/main/java/com/example/umc10th/domain/mission/repository/MissionRepository.java new file mode 100644 index 0000000..b59d713 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/repository/MissionRepository.java @@ -0,0 +1,7 @@ +package com.example.umc10th.domain.mission.repository; + +import com.example.umc10th.domain.mission.entity.Mission; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MissionRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/repository/StoreRepository.java b/src/main/java/com/example/umc10th/domain/mission/repository/StoreRepository.java new file mode 100644 index 0000000..8fcac4c --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/repository/StoreRepository.java @@ -0,0 +1,7 @@ +package com.example.umc10th.domain.mission.repository; + +import com.example.umc10th.domain.mission.entity.Store; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface StoreRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/mission/service/MissionService.java b/src/main/java/com/example/umc10th/domain/mission/service/MissionService.java new file mode 100644 index 0000000..c9e3488 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/mission/service/MissionService.java @@ -0,0 +1,35 @@ +package com.example.umc10th.domain.mission.service; + +import com.example.umc10th.domain.mission.converter.MissionConverter; +import com.example.umc10th.domain.mission.dto.MissionResDTO; +import com.example.umc10th.domain.mission.enums.MissionStatus; +import com.example.umc10th.domain.mission.entity.mapping.MemberMission; +import com.example.umc10th.domain.mission.repository.MemberMissionRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class MissionService { + + private final MemberMissionRepository memberMissionRepository; + + @Transactional(readOnly = true) + public MissionResDTO.MyMissionPreViewListDTO getMyMissions( + Long memberId, + MissionStatus status, + int page, + int size + ) { + Pageable pageable = PageRequest.of(page, size); + + Page result = memberMissionRepository + .findMyMissionsByStatus(memberId, status, pageable); + + return MissionConverter.toMyMissionPreViewListDTO(result); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/review/controller/ReviewController.java b/src/main/java/com/example/umc10th/domain/review/controller/ReviewController.java new file mode 100644 index 0000000..2334fff --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/controller/ReviewController.java @@ -0,0 +1,62 @@ +package com.example.umc10th.domain.review.controller; + +import com.example.umc10th.domain.review.converter.ReviewConverter; +import com.example.umc10th.domain.review.dto.ReviewReqDTO; +import com.example.umc10th.domain.review.dto.ReviewResDTO; +import com.example.umc10th.domain.review.entity.Review; +import com.example.umc10th.domain.review.enums.ReviewSortType; +import com.example.umc10th.domain.review.exception.code.ReviewSuccessCode; +import com.example.umc10th.domain.review.service.ReviewService; +import com.example.umc10th.global.apiPayload.ApiResponse; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Slice; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +public class ReviewController { + + private final ReviewService reviewService; + + /** + * 특정 가게의 리뷰 목록 조회 (오프셋 기반) + */ + @GetMapping("/api/stores/{storeId}/reviews") + public ApiResponse getReviewList( + @PathVariable(name = "storeId") Long storeId, + @RequestParam(name = "page", defaultValue = "1") Integer page + ) { + Page reviewPage = reviewService.getReviewList(storeId, page); + return ApiResponse.onSuccess(ReviewSuccessCode.OK, ReviewConverter.reviewPreViewListDTO(reviewPage)); + } + + /** + * 내가 작성한 리뷰 목록 조회 (커서 기반) + * - 사용자 ID 는 Request Body 로 받음 + * - sortType: ID(기본, 최신순) / SCORE(별점 내림차순) + * - cursorId, cursorScore 는 직전 응답의 nextCursor 값을 그대로 보내면 됨 + * - 사진(ReviewPhoto)은 응답에 포함되지 않음 + */ + @GetMapping("/api/v1/members/me/reviews") + public ApiResponse getMyReviews( + @RequestBody @Valid ReviewReqDTO.GetMyReviews request, + @RequestParam(name = "sortType", defaultValue = "ID") ReviewSortType sortType, + @RequestParam(name = "cursorId", required = false) Long cursorId, + @RequestParam(name = "cursorScore", required = false) Float cursorScore, + @RequestParam(name = "size", defaultValue = "10") int size + ) { + Slice slice; + if (sortType == ReviewSortType.SCORE) { + slice = reviewService.getMyReviewsByScore(request.memberId(), cursorScore, cursorId, size); + } else { + slice = reviewService.getMyReviewsById(request.memberId(), cursorId, size); + } + + return ApiResponse.onSuccess( + ReviewSuccessCode.MY_REVIEW_OK, + ReviewConverter.toMyReviewPreViewListDTO(slice, sortType) + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/review/converter/ReviewConverter.java b/src/main/java/com/example/umc10th/domain/review/converter/ReviewConverter.java new file mode 100644 index 0000000..3fd49fc --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/converter/ReviewConverter.java @@ -0,0 +1,80 @@ +package com.example.umc10th.domain.review.converter; + +import com.example.umc10th.domain.review.dto.ReviewResDTO; +import com.example.umc10th.domain.review.entity.Review; +import com.example.umc10th.domain.review.enums.ReviewSortType; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Slice; + +import java.util.List; +import java.util.stream.Collectors; + +public class ReviewConverter { + + /* ============ 가게의 리뷰 목록 (기존, 오프셋 기반) ============ */ + + public static ReviewResDTO.ReviewPreViewDTO reviewPreViewDTO(Review review) { + return ReviewResDTO.ReviewPreViewDTO.builder() + .nickname(review.getMember().getName()) + .score(review.getScore()) + .body(review.getBody()) + .createdAt(review.getCreatedAt().toLocalDate()) + .build(); + } + + public static ReviewResDTO.ReviewPreViewListDTO reviewPreViewListDTO(Page reviewPage) { + List reviewPreViewDTOList = reviewPage.stream() + .map(ReviewConverter::reviewPreViewDTO) + .collect(Collectors.toList()); + + return ReviewResDTO.ReviewPreViewListDTO.builder() + .isFirst(reviewPage.isFirst()) + .isLast(reviewPage.isLast()) + .totalPage(reviewPage.getTotalPages()) + .totalElements(reviewPage.getTotalElements()) + .listSize(reviewPreViewDTOList.size()) + .reviewList(reviewPreViewDTOList) + .build(); + } + + /* ============ 내가 작성한 리뷰 목록 (커서 기반, 사진 제외) ============ */ + + public static ReviewResDTO.MyReviewPreViewDTO toMyReviewPreViewDTO(Review review) { + return ReviewResDTO.MyReviewPreViewDTO.builder() + .reviewId(review.getId()) + .storeName(review.getStore().getName()) + .score(review.getScore()) + .body(review.getBody()) + .createdAt(review.getCreatedAt().toLocalDate()) + .build(); + } + + public static ReviewResDTO.MyReviewPreViewListDTO toMyReviewPreViewListDTO( + Slice slice, + ReviewSortType sortType + ) { + List reviewList = slice.getContent().stream() + .map(ReviewConverter::toMyReviewPreViewDTO) + .collect(Collectors.toList()); + + Long nextCursorId = null; + Float nextCursorScore = null; + + // 다음 페이지가 있을 때 마지막 리뷰의 값으로 커서 세팅 + if (slice.hasNext() && !slice.getContent().isEmpty()) { + Review last = slice.getContent().get(slice.getContent().size() - 1); + nextCursorId = last.getId(); + if (sortType == ReviewSortType.SCORE) { + nextCursorScore = last.getScore(); + } + } + + return ReviewResDTO.MyReviewPreViewListDTO.builder() + .reviewList(reviewList) + .listSize(reviewList.size()) + .hasNext(slice.hasNext()) + .nextCursorId(nextCursorId) + .nextCursorScore(nextCursorScore) + .build(); + } +} diff --git a/src/main/java/com/example/umc10th/domain/review/dto/ReviewReqDTO.java b/src/main/java/com/example/umc10th/domain/review/dto/ReviewReqDTO.java new file mode 100644 index 0000000..fcf0dde --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/dto/ReviewReqDTO.java @@ -0,0 +1,34 @@ +package com.example.umc10th.domain.review.dto; + +import jakarta.validation.constraints.DecimalMax; +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.Size; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +public class ReviewReqDTO { + + @Getter + @NoArgsConstructor(access = AccessLevel.PUBLIC) + public static class CreateReview { + @NotBlank(message = "리뷰 내용은 필수입니다.") + @Size(max = 500, message = "리뷰는 500자 이하여야 합니다.") + private String body; + + @NotNull(message = "별점은 필수입니다.") + @DecimalMin(value = "0.0", message = "별점은 0.0 이상이어야 합니다.") + @DecimalMax(value = "5.0", message = "별점은 5.0 이하여야 합니다.") + private Float score; + } + + // 내가 작성한 리뷰 조회 - 사용자 ID 는 Request Body 로 받음 + public record GetMyReviews( + @NotNull(message = "회원 ID는 필수입니다.") + @Positive(message = "회원 ID는 0보다 커야 합니다.") + Long memberId + ){} +} diff --git a/src/main/java/com/example/umc10th/domain/review/dto/ReviewResDTO.java b/src/main/java/com/example/umc10th/domain/review/dto/ReviewResDTO.java new file mode 100644 index 0000000..ac64a4e --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/dto/ReviewResDTO.java @@ -0,0 +1,64 @@ +package com.example.umc10th.domain.review.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; +import java.util.List; + +public class ReviewResDTO { + + // 가게의 리뷰 리스트와 페이징 정보 (오프셋 기반) + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class ReviewPreViewListDTO { + private List reviewList; + private Integer listSize; + private Integer totalPage; + private Long totalElements; + private Boolean isFirst; + private Boolean isLast; + } + + // 개별 리뷰 (가게 리뷰 화면용) + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class ReviewPreViewDTO { + private String nickname; + private Float score; + private String body; + private LocalDate createdAt; + } + + // 내가 작성한 리뷰 리스트 + 커서 정보 (커서 기반) + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MyReviewPreViewListDTO { + private List reviewList; + private Integer listSize; + private Boolean hasNext; + private Long nextCursorId; // ID/별점 순 모두에서 사용 (tie-break용) + private Float nextCursorScore; // 별점 순일 때만 채워짐 + } + + // 내가 작성한 리뷰 개별 정보 (사진 제외) + @Builder + @Getter + @NoArgsConstructor + @AllArgsConstructor + public static class MyReviewPreViewDTO { + private Long reviewId; + private String storeName; + private Float score; + private String body; + private LocalDate createdAt; + } +} diff --git a/src/main/java/com/example/umc10th/domain/review/entity/Reply.java b/src/main/java/com/example/umc10th/domain/review/entity/Reply.java new file mode 100644 index 0000000..4832ef0 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/entity/Reply.java @@ -0,0 +1,26 @@ +package com.example.umc10th.domain.review.entity; + +import com.example.umc10th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Table(name = "reply") +public class Reply extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 500) + private String body; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "review_id", nullable = false) + private Review review; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/review/entity/Review.java b/src/main/java/com/example/umc10th/domain/review/entity/Review.java new file mode 100644 index 0000000..e89cf2a --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/entity/Review.java @@ -0,0 +1,45 @@ +package com.example.umc10th.domain.review.entity; + +import com.example.umc10th.domain.member.entity.Member; +import com.example.umc10th.domain.mission.entity.Store; +import com.example.umc10th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + +import java.util.ArrayList; +import java.util.List; + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Table(name = "review") +public class Review extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, length = 500) + private String body; + + @Column(nullable = false) + private Float score; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "member_id", nullable = false) + private Member member; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "store_id", nullable = false) + private Store store; + + @OneToMany(mappedBy = "review", cascade = CascadeType.ALL) + @Builder.Default + private List reviewPhotoList = new ArrayList<>(); + + @OneToMany(mappedBy = "review", cascade = CascadeType.ALL) + @Builder.Default + private List replyList = new ArrayList<>(); +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/review/entity/ReviewPhoto.java b/src/main/java/com/example/umc10th/domain/review/entity/ReviewPhoto.java new file mode 100644 index 0000000..811d733 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/entity/ReviewPhoto.java @@ -0,0 +1,27 @@ +package com.example.umc10th.domain.review.entity; + +import com.example.umc10th.global.entity.BaseEntity; +import jakarta.persistence.*; +import lombok.*; + + +@Entity +@Getter +@Builder +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@AllArgsConstructor +@Table(name = "review_photo") +public class ReviewPhoto extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + + @Column(nullable = false, length = 500) + private String url; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "review_id", nullable = false) + private Review review; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/domain/review/enums/ReviewSortType.java b/src/main/java/com/example/umc10th/domain/review/enums/ReviewSortType.java new file mode 100644 index 0000000..eb714bc --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/enums/ReviewSortType.java @@ -0,0 +1,6 @@ +package com.example.umc10th.domain.review.enums; + +public enum ReviewSortType { + ID, // ID(최신) 순 정렬 + SCORE // 별점 순 정렬 +} diff --git a/src/main/java/com/example/umc10th/domain/review/exception/ReviewException.java b/src/main/java/com/example/umc10th/domain/review/exception/ReviewException.java new file mode 100644 index 0000000..7c6f6ae --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/exception/ReviewException.java @@ -0,0 +1,10 @@ +package com.example.umc10th.domain.review.exception; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import com.example.umc10th.global.apiPayload.exception.ProjectException; + +public class ReviewException extends ProjectException { + public ReviewException(BaseErrorCode errorCode) { + super(errorCode); + } +} diff --git a/src/main/java/com/example/umc10th/domain/review/exception/code/ReviewErrorCode.java b/src/main/java/com/example/umc10th/domain/review/exception/code/ReviewErrorCode.java new file mode 100644 index 0000000..805dc97 --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/exception/code/ReviewErrorCode.java @@ -0,0 +1,19 @@ +package com.example.umc10th.domain.review.exception.code; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum ReviewErrorCode implements BaseErrorCode { + REVIEW_NOT_FOUND(HttpStatus.NOT_FOUND, "REVIEW404_1", "해당 리뷰를 찾을 수 없습니다."), + INVALID_CURSOR(HttpStatus.BAD_REQUEST, "REVIEW400_1", "잘못된 커서 값입니다."), + INVALID_SORT_TYPE(HttpStatus.BAD_REQUEST, "REVIEW400_2", "잘못된 정렬 타입입니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc10th/domain/review/exception/code/ReviewSuccessCode.java b/src/main/java/com/example/umc10th/domain/review/exception/code/ReviewSuccessCode.java new file mode 100644 index 0000000..32b821f --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/exception/code/ReviewSuccessCode.java @@ -0,0 +1,19 @@ +package com.example.umc10th.domain.review.exception.code; + +import com.example.umc10th.global.apiPayload.code.BaseSuccessCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum ReviewSuccessCode implements BaseSuccessCode { + CREATED(HttpStatus.CREATED, "REVIEW201_1", "성공적으로 리뷰를 작성했습니다."), + OK(HttpStatus.OK, "REVIEW200_1", "성공적으로 리뷰를 조회했습니다."), + MY_REVIEW_OK(HttpStatus.OK, "REVIEW200_2", "성공적으로 내가 작성한 리뷰를 조회했습니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc10th/domain/review/repository/ReviewRepository.java b/src/main/java/com/example/umc10th/domain/review/repository/ReviewRepository.java new file mode 100644 index 0000000..3a62bbc --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/repository/ReviewRepository.java @@ -0,0 +1,65 @@ +package com.example.umc10th.domain.review.repository; + +import com.example.umc10th.domain.review.entity.Review; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface ReviewRepository extends JpaRepository { + + @Query( + value = "SELECT r FROM Review r " + + "JOIN FETCH r.member m " + + "WHERE r.store.id = :storeId " + + "ORDER BY r.createdAt DESC", + countQuery = "SELECT COUNT(r) FROM Review r " + + "WHERE r.store.id = :storeId" + ) + Page findAllByStoreId( + @Param("storeId") Long storeId, + Pageable pageable + ); + + /** + * 내가 작성한 리뷰 - ID(최신) 순 커서 기반 조회 + * - 사진(ReviewPhoto)은 fetch 하지 않음 + * - cursorId 가 null 이면 처음부터 조회 + * - cursorId 가 있으면 그 ID 보다 작은 리뷰(=더 이전 리뷰)부터 size 만큼 조회 + */ + @Query("SELECT r FROM Review r " + + "JOIN FETCH r.store s " + + "WHERE r.member.id = :memberId " + + "AND (:cursorId IS NULL OR r.id < :cursorId) " + + "ORDER BY r.id DESC") + Slice findMyReviewsByIdCursor( + @Param("memberId") Long memberId, + @Param("cursorId") Long cursorId, + Pageable pageable + ); + + /** + * 내가 작성한 리뷰 - 별점 순(내림차순) 커서 기반 조회 + * - 사진(ReviewPhoto)은 fetch 하지 않음 + * - 별점이 같으면 id 내림차순으로 tie-break + * - cursorScore, cursorId 가 모두 null 이면 처음부터 조회 + * - 둘 다 있으면 (score < cursorScore) 또는 (score = cursorScore AND id < cursorId) 인 리뷰부터 조회 + */ + @Query("SELECT r FROM Review r " + + "JOIN FETCH r.store s " + + "WHERE r.member.id = :memberId " + + "AND (" + + " :cursorScore IS NULL " + + " OR r.score < :cursorScore " + + " OR (r.score = :cursorScore AND r.id < :cursorId)" + + ") " + + "ORDER BY r.score DESC, r.id DESC") + Slice findMyReviewsByScoreCursor( + @Param("memberId") Long memberId, + @Param("cursorScore") Float cursorScore, + @Param("cursorId") Long cursorId, + Pageable pageable + ); +} diff --git a/src/main/java/com/example/umc10th/domain/review/service/ReviewService.java b/src/main/java/com/example/umc10th/domain/review/service/ReviewService.java new file mode 100644 index 0000000..9b0d9cb --- /dev/null +++ b/src/main/java/com/example/umc10th/domain/review/service/ReviewService.java @@ -0,0 +1,92 @@ +package com.example.umc10th.domain.review.service; + +import com.example.umc10th.domain.member.entity.Member; +import com.example.umc10th.domain.member.exception.MemberException; +import com.example.umc10th.domain.member.exception.code.MemberErrorCode; +import com.example.umc10th.domain.member.repository.MemberRepository; +import com.example.umc10th.domain.mission.entity.Store; +import com.example.umc10th.domain.mission.exception.MissionException; +import com.example.umc10th.domain.mission.exception.code.MissionErrorCode; +import com.example.umc10th.domain.mission.repository.StoreRepository; +import com.example.umc10th.domain.review.dto.ReviewReqDTO; +import com.example.umc10th.domain.review.entity.Review; +import com.example.umc10th.domain.review.repository.ReviewRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Slice; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class ReviewService { + + private static final int PAGE_SIZE = 10; + + private final ReviewRepository reviewRepository; + private final MemberRepository memberRepository; + private final StoreRepository storeRepository; + + /** + * 특정 가게의 리뷰 목록 페이징 조회 (오프셋 기반) + */ + @Transactional(readOnly = true) + public Page getReviewList(Long storeId, Integer page) { + // 가게 존재 여부 확인 + storeRepository.findById(storeId) + .orElseThrow(() -> new MissionException(MissionErrorCode.STORE_NOT_FOUND)); + + // PageRequest 는 0-base 이므로 한 칸 보정 + int safePage = (page == null || page < 1) ? 0 : page - 1; + Pageable pageable = PageRequest.of(safePage, PAGE_SIZE); + + return reviewRepository.findAllByStoreId(storeId, pageable); + } + + /** + * 리뷰 작성 + */ + @Transactional + public Review createReview(Long storeId, Long memberId, ReviewReqDTO.CreateReview dto) { + Store store = storeRepository.findById(storeId) + .orElseThrow(() -> new MissionException(MissionErrorCode.STORE_NOT_FOUND)); + Member member = memberRepository.findById(memberId) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + + Review review = Review.builder() + .body(dto.getBody()) + .score(dto.getScore()) + .store(store) + .member(member) + .build(); + + return reviewRepository.save(review); + } + + /** + * 내가 작성한 리뷰 - ID(최신) 순 커서 기반 조회 + */ + @Transactional(readOnly = true) + public Slice getMyReviewsById(Long memberId, Long cursorId, int size) { + memberRepository.findById(memberId) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + + Pageable pageable = PageRequest.of(0, size); + return reviewRepository.findMyReviewsByIdCursor(memberId, cursorId, pageable); + } + + /** + * 내가 작성한 리뷰 - 별점 순 커서 기반 조회 + * - cursorScore 가 있으면 cursorId 도 함께 필요 (tie-break) + */ + @Transactional(readOnly = true) + public Slice getMyReviewsByScore(Long memberId, Float cursorScore, Long cursorId, int size) { + memberRepository.findById(memberId) + .orElseThrow(() -> new MemberException(MemberErrorCode.MEMBER_NOT_FOUND)); + + Pageable pageable = PageRequest.of(0, size); + return reviewRepository.findMyReviewsByScoreCursor(memberId, cursorScore, cursorId, pageable); + } +} diff --git a/src/main/java/com/example/umc10th/global/apiPayload/ApiResponse.java b/src/main/java/com/example/umc10th/global/apiPayload/ApiResponse.java new file mode 100644 index 0000000..37d48a0 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/apiPayload/ApiResponse.java @@ -0,0 +1,34 @@ +package com.example.umc10th.global.apiPayload; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import com.example.umc10th.global.apiPayload.code.BaseSuccessCode; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +@JsonPropertyOrder({"isSuccess", "code", "message", "result"}) +public class ApiResponse { + + @JsonProperty("isSuccess") + private final Boolean isSuccess; + + @JsonProperty("code") + private final String code; + + @JsonProperty("message") + private final String message; + + @JsonProperty("result") + private T result; + + public static ApiResponse onFailure(BaseErrorCode code, T result) { + return new ApiResponse<>(false, code.getCode(), code.getMessage(), result); + } + + public static ApiResponse onSuccess(BaseSuccessCode code, T result) { + return new ApiResponse<>(true, code.getCode(), code.getMessage(), result); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/global/apiPayload/code/BaseErrorCode.java b/src/main/java/com/example/umc10th/global/apiPayload/code/BaseErrorCode.java new file mode 100644 index 0000000..351b923 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/apiPayload/code/BaseErrorCode.java @@ -0,0 +1,10 @@ +package com.example.umc10th.global.apiPayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseErrorCode { + + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} diff --git a/src/main/java/com/example/umc10th/global/apiPayload/code/BaseSuccessCode.java b/src/main/java/com/example/umc10th/global/apiPayload/code/BaseSuccessCode.java new file mode 100644 index 0000000..038eb92 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/apiPayload/code/BaseSuccessCode.java @@ -0,0 +1,9 @@ +package com.example.umc10th.global.apiPayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseSuccessCode { + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} diff --git a/src/main/java/com/example/umc10th/global/apiPayload/code/GeneralErrorCode.java b/src/main/java/com/example/umc10th/global/apiPayload/code/GeneralErrorCode.java new file mode 100644 index 0000000..b41ee82 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/apiPayload/code/GeneralErrorCode.java @@ -0,0 +1,21 @@ +package com.example.umc10th.global.apiPayload.code; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum GeneralErrorCode implements BaseErrorCode { + BAD_REQUEST(HttpStatus.BAD_REQUEST, "COMMON400_1", "잘못된 요청입니다."), + VALIDATION_ERROR(HttpStatus.BAD_REQUEST, "COMMON400_2", "요청 값 검증에 실패했습니다."), + UNAUTHORIZED(HttpStatus.UNAUTHORIZED,"COMMON401_1", "인증되지 않았습니다."), + FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON403_1", "접근이 금지되었습니다."), + NOT_FOUND(HttpStatus.NOT_FOUND, "COMMON404_1", "해당 리소스를 찾을 수 없습니다."), + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON500_1", "서버 에러, 관리자에게 문의하세요."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc10th/global/apiPayload/code/GeneralSuccessCode.java b/src/main/java/com/example/umc10th/global/apiPayload/code/GeneralSuccessCode.java new file mode 100644 index 0000000..5d80d5d --- /dev/null +++ b/src/main/java/com/example/umc10th/global/apiPayload/code/GeneralSuccessCode.java @@ -0,0 +1,16 @@ +package com.example.umc10th.global.apiPayload.code; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum GeneralSuccessCode implements BaseSuccessCode { + OK(HttpStatus.OK, "COMMON200_1", "성공적으로 처리했습니다."), + ; + + private final HttpStatus status; + private final String code; + private final String message; +} diff --git a/src/main/java/com/example/umc10th/global/apiPayload/exception/ProjectException.java b/src/main/java/com/example/umc10th/global/apiPayload/exception/ProjectException.java new file mode 100644 index 0000000..ded50b7 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/apiPayload/exception/ProjectException.java @@ -0,0 +1,15 @@ +package com.example.umc10th.global.apiPayload.exception; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import lombok.Getter; + +@Getter +public class ProjectException extends RuntimeException { + + private final BaseErrorCode errorCode; + + public ProjectException(BaseErrorCode errorCode) { + super(errorCode.getMessage()); + this.errorCode = errorCode; + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/global/apiPayload/handler/GeneralExceptionAdvice.java b/src/main/java/com/example/umc10th/global/apiPayload/handler/GeneralExceptionAdvice.java new file mode 100644 index 0000000..0347643 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/apiPayload/handler/GeneralExceptionAdvice.java @@ -0,0 +1,91 @@ +package com.example.umc10th.global.apiPayload.handler; + + +import com.example.umc10th.global.apiPayload.ApiResponse; +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import com.example.umc10th.global.apiPayload.code.GeneralErrorCode; +import com.example.umc10th.global.apiPayload.exception.ProjectException; +import jakarta.validation.ConstraintViolationException; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class GeneralExceptionAdvice { + + /** + * 프로젝트 내부에서 던지는 비즈니스 예외 (MemberException, MissionException, ReviewException 등) + */ + @ExceptionHandler(ProjectException.class) + public ResponseEntity> handleProjectException( + ProjectException e + ) { + BaseErrorCode errorCode = e.getErrorCode(); + return ResponseEntity.status(errorCode.getStatus()) + .body(ApiResponse.onFailure(errorCode, null)); + } + + /** + * @Valid 로 검증한 @RequestBody DTO 가 검증에 실패했을 때 발생하는 예외 + * - 어떤 필드가 어떤 이유로 실패했는지 result 에 담아 응답 + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity>> handleMethodArgumentNotValidException( + MethodArgumentNotValidException e + ) { + Map errors = e.getBindingResult().getFieldErrors().stream() + .collect(Collectors.toMap( + FieldError::getField, + fieldError -> fieldError.getDefaultMessage() == null + ? "잘못된 값입니다." + : fieldError.getDefaultMessage(), + (existing, replacement) -> existing, + LinkedHashMap::new + )); + + BaseErrorCode code = GeneralErrorCode.VALIDATION_ERROR; + return ResponseEntity.status(code.getStatus()) + .body(ApiResponse.onFailure(code, errors)); + } + + /** + * @RequestParam, @PathVariable 등에 붙은 검증 어노테이션이 실패했을 때 발생 + */ + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity>> handleConstraintViolationException( + ConstraintViolationException e + ) { + Map errors = e.getConstraintViolations().stream() + .collect(Collectors.toMap( + cv -> cv.getPropertyPath().toString(), + cv -> cv.getMessage() == null ? "잘못된 값입니다." : cv.getMessage(), + (existing, replacement) -> existing, + LinkedHashMap::new + )); + + BaseErrorCode code = GeneralErrorCode.VALIDATION_ERROR; + return ResponseEntity.status(code.getStatus()) + .body(ApiResponse.onFailure(code, errors)); + } + + /** + * 그 외 처리되지 않은 모든 예외에 대한 fallback + */ + @ExceptionHandler(Exception.class) + public ResponseEntity> handleException( + Exception ex + ) { + BaseErrorCode code = GeneralErrorCode.INTERNAL_SERVER_ERROR; + return ResponseEntity.status(code.getStatus()) + .body(ApiResponse.onFailure( + code, + ex.getMessage() + )); + } +} diff --git a/src/main/java/com/example/umc10th/global/config/SecurityConfig.java b/src/main/java/com/example/umc10th/global/config/SecurityConfig.java new file mode 100644 index 0000000..68c4af3 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/config/SecurityConfig.java @@ -0,0 +1,55 @@ +package com.example.umc10th.global.config; + +import com.example.umc10th.global.security.handler.CustomAccessDeniedHandler; +import com.example.umc10th.global.security.handler.CustomAuthenticationEntryPoint; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +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; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + + private final CustomAuthenticationEntryPoint authenticationEntryPoint; + private final CustomAccessDeniedHandler accessDeniedHandler; + + private static final String[] PUBLIC_ENDPOINTS = { + "/swagger-ui/**", + "/swagger-ui.html", + "/v3/api-docs/**", + "/error" + }; + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .csrf(csrf -> csrf.disable()) + .formLogin(form -> form.disable()) + .httpBasic(basic -> basic.disable()) + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + + .authorizeHttpRequests(auth -> auth + .requestMatchers(PUBLIC_ENDPOINTS).permitAll() + .requestMatchers(HttpMethod.POST, "/api/v1/auth/signup").permitAll() + .anyRequest().authenticated()) + .exceptionHandling(exception -> exception + .authenticationEntryPoint(authenticationEntryPoint) + .accessDeniedHandler(accessDeniedHandler)); + + return http.build(); + } +} diff --git a/src/main/java/com/example/umc10th/global/config/SwaggerConfig.java b/src/main/java/com/example/umc10th/global/config/SwaggerConfig.java new file mode 100644 index 0000000..2f6146a --- /dev/null +++ b/src/main/java/com/example/umc10th/global/config/SwaggerConfig.java @@ -0,0 +1,36 @@ +package com.example.umc10th.global.config; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SwaggerConfig { + + @Bean + public OpenAPI swagger() { + Info info = new Info().title("UMC10th").description("10기 Swagger").version("0.0.1"); + + // JWT 토큰 헤더 방식 + String securityScheme = "JWT TOKEN"; + SecurityRequirement securityRequirement = new SecurityRequirement().addList(securityScheme); + + Components components = new Components() + .addSecuritySchemes(securityScheme, new SecurityScheme() + .name(securityScheme) + .type(SecurityScheme.Type.HTTP) + .scheme("Bearer") + .bearerFormat("JWT")); + + return new OpenAPI() + .info(info) + .addServersItem(new Server().url("/")) + .addSecurityItem(securityRequirement) + .components(components); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/global/entity/BaseEntity.java b/src/main/java/com/example/umc10th/global/entity/BaseEntity.java new file mode 100644 index 0000000..689d7eb --- /dev/null +++ b/src/main/java/com/example/umc10th/global/entity/BaseEntity.java @@ -0,0 +1,28 @@ +package com.example.umc10th.global.entity; + +import jakarta.persistence.Column; +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; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +@Getter +public abstract class BaseEntity { + + @CreatedDate + @Column(name = "created_at", nullable = false) + private LocalDateTime createdAt; + + @LastModifiedDate + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; + + @Column(name = "deleted_at") + private LocalDateTime deletedAt; +} \ No newline at end of file diff --git a/src/main/java/com/example/umc10th/global/security/handler/CustomAccessDeniedHandler.java b/src/main/java/com/example/umc10th/global/security/handler/CustomAccessDeniedHandler.java new file mode 100644 index 0000000..9744868 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/security/handler/CustomAccessDeniedHandler.java @@ -0,0 +1,21 @@ +package com.example.umc10th.global.security.handler; + +import com.example.umc10th.global.apiPayload.code.GeneralErrorCode; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + @Override + public void handle(HttpServletRequest request, + HttpServletResponse response, + AccessDeniedException accessDeniedException) throws IOException { + SecurityResponseWriter.write(response, GeneralErrorCode.FORBIDDEN); + } +} diff --git a/src/main/java/com/example/umc10th/global/security/handler/CustomAuthenticationEntryPoint.java b/src/main/java/com/example/umc10th/global/security/handler/CustomAuthenticationEntryPoint.java new file mode 100644 index 0000000..0a8ca95 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/security/handler/CustomAuthenticationEntryPoint.java @@ -0,0 +1,21 @@ +package com.example.umc10th.global.security.handler; + +import com.example.umc10th.global.apiPayload.code.GeneralErrorCode; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(HttpServletRequest request, + HttpServletResponse response, + AuthenticationException authException) throws IOException { + SecurityResponseWriter.write(response, GeneralErrorCode.UNAUTHORIZED); + } +} diff --git a/src/main/java/com/example/umc10th/global/security/handler/SecurityResponseWriter.java b/src/main/java/com/example/umc10th/global/security/handler/SecurityResponseWriter.java new file mode 100644 index 0000000..68379f4 --- /dev/null +++ b/src/main/java/com/example/umc10th/global/security/handler/SecurityResponseWriter.java @@ -0,0 +1,28 @@ +package com.example.umc10th.global.security.handler; + +import com.example.umc10th.global.apiPayload.code.BaseErrorCode; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.MediaType; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +public final class SecurityResponseWriter { + + private SecurityResponseWriter() { + } + + public static void write(HttpServletResponse response, BaseErrorCode errorCode) throws IOException { + response.setStatus(errorCode.getStatus().value()); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding(StandardCharsets.UTF_8.name()); + + // ApiResponse 와 동일한 구조: { isSuccess, code, message, result } + String body = String.format( + "{\"isSuccess\": false, \"code\": \"%s\", \"message\": \"%s\", \"result\": null}", + errorCode.getCode(), + errorCode.getMessage() + ); + response.getWriter().write(body); + } +} diff --git a/src/test/java/com/example/umc10th/Umc10thApplicationTests.java b/src/test/java/com/example/umc10th/Umc10thApplicationTests.java new file mode 100644 index 0000000..b43a96f --- /dev/null +++ b/src/test/java/com/example/umc10th/Umc10thApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.umc10th; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class Umc10thApplicationTests { + + @Test + void contextLoads() { + } + +}