diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 00000000..4edd2210 --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,54 @@ +# ---------------------------------------------------------------- # +# CodeRabbit AI 설정 +# ---------------------------------------------------------------- # + +# 응답 기본 언어 설정 +language: "ko-KR" + +# AI 페르소나 및 톤앤매너 지시 +tone_instructions: > + 1. 피드백은 명확하고 구체적이어야 하며, 문제의 원인과 개선 방법을 반드시 제시하세요. + 2. 리뷰는 교육적이어야 하며, 관련 개념이나 공식 문서를 함께 추천하세요. + 3. 비판보다는 개선 중심의 제안을 우선하세요. + 4. 칭찬은 짧고 위트 있게 작성하세요. + +# ---------------------------------------------------------------- # +# 코드 리뷰 기능 세부 설정 +# ---------------------------------------------------------------- # +reviews: + profile: "chill" # 리뷰 전반 스타일 (부드러운 톤) + request_changes_workflow: false # 코멘트 resolve 시 자동 Approve 처리 + high_level_summary: true # PR 변경 사항 고수준 요약 활성화 + collapse_walkthrough: true # 워크스루 코멘트 접기 활성화 + changed_files_summary: true # 변경된 파일별 요약 생성 + sequence_diagrams: true # 실행 흐름 시퀀스 다이어그램 생성 + assess_linked_issues: true # 연결된 이슈 분석 컨텍스트 활용 + related_issues: false # 연관 다른 이슈 링크 비활성화 + related_prs: true # 연관 다른 PR 링크 활성화 + suggested_labels: false # 적절한 레이블 제안 비활성화 + auto_apply_labels: false # 제안 레이블 자동 적용 비활성화 + suggested_reviewers: false # 동료 리뷰어 추천 비활성화 + auto_assign_reviewers: false # 추천 리뷰어 자동 할당 비활성화 + poem: true # 리뷰 요약에 위트 있는 시 포함 활성화 + + # ---------------------------------------------------------------- # + # 자동 리뷰 트리거 설정 + # ---------------------------------------------------------------- # + auto_review: + enabled: true + auto_incremental_review: true # 추가 커밋 시 변경된 부분만 자동 리뷰 + +# ---------------------------------------------------------------- # +# 채팅 기능 설정 +# ---------------------------------------------------------------- # +chat: + auto_reply: true # 태그하지 않아도 자동 답글 활성화 + +# ---------------------------------------------------------------- # +# CodeRabbit의 지식 기반(Knowledge Base) 설정 +# ---------------------------------------------------------------- # +knowledge_base: + web_search: + enabled: true # 최신 문서 검색 허용 + code_guidelines: + enabled: true \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..dd6d9897 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +# Git이 알아서 OS에 맞게 줄바꿈을 변환해 주도록 강제 +* text=auto + +# 윈도우 배치 파일은 무조건 CRLF로 고정 +*.bat text eol=crlf +*.cmd text eol=crlf + +# 리눅스/맥용 셸 스크립트는 무조건 LF로 고정 +gradlew text eol=lf +*.sh text eol=lf \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..46cec6d5 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,30 @@ +## 📍 개요 + +> 소셜 로그인 구현 + +### ⛓️‍💥 관련 이슈 + +- Closes #이슈번호 + +--- +### 🛠️ 작업 내용 + +- 소셜 로그인 API 추가 + +--- +### 🔥 리뷰 요청 사항 +> 리뷰어가 중점적으로 확인해주었으면 하는 내용을 작성해주세요. + +- 예외 코드 처리 방식 + +--- +### ✅ 체크리스트 + +* [ ] 코드 컨벤션을 준수했습니다. +* [ ] 불필요한 코드 및 import를 제거했습니다. +* [ ] 예외 처리를 적용했습니다. +* [ ] 테스트를 완료했습니다. +* [ ] 관련 Issue를 연결했습니다. + +--- +### 📎 참고 사항 diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..8e1ef4fc --- /dev/null +++ b/.gitignore @@ -0,0 +1,53 @@ +# ================================================================= # +# Git ignore for Spring Boot / Java / Gradle / IntelliJ (Muse Review) +# ================================================================= # + +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/resources/gradle/wrapper/gradle-wrapper.jar +!**/src/test/resources/gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Operating System ### +.DS_Store +Thumbs.db +desktop.ini + +# 암호키 및 보안 인증서 관련 파일 +*.key +*.pem +*.jks + + +MR_config/* + +MR_config/local/* + +!MR_config/local/application.example.yml \ No newline at end of file diff --git a/MR_config/local/application.example.yml b/MR_config/local/application.example.yml new file mode 100644 index 00000000..3dd38451 --- /dev/null +++ b/MR_config/local/application.example.yml @@ -0,0 +1,42 @@ +# ================================================================= # +# 🔒 [NOTICE] 본 파일은 로컬 환경 세팅용 '공통 예시 파일'입니다. +# 각자 로컬 PC 사양에 맞게 정보를 입력한 후, 파일 이름을 +# 'application.yml'로 변경하여 동일한 경로에 위치시켜 주세요! +# ================================================================= # + +spring: + # 1. 로컬 데이터베이스 커넥션 설정 (PostgreSQL 18) + datasource: + driver-class-name: org.postgresql.Driver + url: jdbc:postgresql://localhost:5432/mr_db # [체크] 로컬에 mr_db 빈 데이터베이스를 먼저 생성 + username: postgres # [입력] PostgreSQL 계정명 + password: "" # [입력] PostgreSQL 비밀번호 (빈값 입력 가능) + + # 2. JPA 및 하이버네이트 구동 설정 + jpa: + hibernate: + ddl-auto: update # 엔티티 매핑 정보 변경 시 DB 테이블 자동 반영 + show-sql: true # 콘솔에 실행 SQL 포맷 출력 + properties: + hibernate: + format_sql: true + dialect: org.hibernate.dialect.PostgreSQLDialect + +# 3. Spring Security 및 JWT 인증 설정 +jwt: + # [입력] HS256 알고리즘을 충족하는 256비트(32바이트) 이상의 임의의 비밀키를 채워주세요. + # 기입 예시: "your-local-custom-secret-key-must-be-very-long-and-secure-32bytes" + secret: "" + access-token-validity-in-seconds: 1800 # Access Token 만료 시간 (30분) + refresh-token-validity-in-seconds: 604800 # Refresh Token 만료 시간 (7일) + +# 4. 외부 소셜 로그인 API 연동 정보 (OAuth용) +oauth: + kakao: + client-id: "" # [입력] 카카오 디벨로퍼스 REST API 키 + client-secret: "" # [입력] 카카오 보안 Client Secret 키 + redirect-uri: http://localhost:8080/login/oauth2/code/kakao + google: + client-id: "" # [입력] 구글 클라우드 콘솔 OAuth 클라이언트 ID + client-secret: "" # [입력] 구글 클라우드 콘솔 보안 비밀번호 + redirect-uri: http://localhost:8080/login/oauth2/code/google \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..9070c994 --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# 🎵 Muse Review - Backend + +> **뮤즈리뷰 백엔드 개발 팀 공통 컨벤션 및 가이드북입니다.** > 모든 팀원은 원활한 협업을 위해 아래 규칙을 반드시 준수해 주세요! + +--- + +## 🌿 1. 브랜치 전략 (Git Flow) + +우리 팀은 안정적인 배포와 독립적인 기능 개발을 위해 브랜치를 분리하여 관리합니다. + +* 🔵 **`main`** : 항상 배포 가능한 상태를 유지하는 운영 브랜치 (직접 작업 금지, PR 머지만 허용) +* 🟢 **`develop`** : 다음 배포를 준비하는 통합 개발 브랜치 (모든 기능 개발본이 모이는 곳) +* 🟡 **`기능 브랜치`** : 기능/이슈 단위로 `develop`에서 파생하여 개발하는 브랜치 + +### 📌 Branch Naming Convention +* **구조:** `Prefix/#이슈번호-작업내용` (Kebab Case 사용) +* **예시:** `feat/#10-login-api`, `chore/#1-setting-base` + +| Prefix | 설명 | 사용 예시 | +| :--- | :--- | :--- | +| `feat` | 새로운 기능 추가 | `feat/#10-login-api` | +| `fix` | 버그 수정 | `fix/#23-header-layout` | +| `docs` | 문서 수정 (README 등) | `docs/#5-update-readme` | +| `style` | 코드 포맷팅 (로직 변경 없음) | `style/#12-format-code` | +| `refactor`| 코드 리팩토링 | `refactor/#30-user-service` | +| `chore` | 설정 파일 변경, 패키지 빌드 등 | `chore/#1-setting-base` | + +--- + +## 📝 2. 커밋 컨벤션 (Commit Convention) + +* **메시지 구조:** `타입: 작업 내용 (#이슈번호)` 형식으로 작성 (제목은 50자 이내 소문자 태그 권장) +* **예시:** `feat: 카카오 소셜 로그인 API 추가 (#10)` + +### 🔓 PR 머지 및 코드 리뷰 규칙 +* **PR 머지 조건:** 활발한 코드 리뷰를 위해 **최소 2명 이상의 승인(Approve)**이 있어야 머지 가능 +* **리뷰 태그 가이드:** + * `P1`: 꼭 반영해 주세요 (중대한 오류 가능성, Request Changes 필수) + * `P2`: 적극적으로 고려해 주세요 (토큰/논의 권장) + * `P3`: 웬만하면 반영해 주세요 / 가벼운 의견 (Comment 처리) + +--- + +## 🛠️ 3. 개발 환경 및 코드 컨벤션 + +### 💻 Tech Stack +* **Language & Framework:** Java 17 / Spring Boot 3.2.2 +* **Database:** PostgreSQL 18 / JPA + +### 🎨 Code Style (Spring JavaFormat) +우리 프로젝트는 `Spring JavaFormat` 플러그인을 사용하여 공통 포맷을 강제합니다. 빌드 시 포맷이 맞지 않으면 컴파일이 실패할 수 있습니다. +* **클래스명:** `PascalCase` (`class AuthController`) +* **변수/메서드명:** `camelCase` (`String accessToken`) +* **상수명:** `UPPER_SNAKE_CASE` (`int MAX_LIMIT = 3`) +* ⚠️ **주의:** 변수 및 메서드명에 언더바(`_`) 사용을 금지합니다. + +--- + +## 🔒 4. 로컬 환경 세팅 (민감 정보 보호) + +민감 정보(DB 패스워드, JWT Secret, OAuth Key) 유출 방지를 위해 `MR_config` 안전 금고 시스템을 사용합니다. + +1. 로컬 PostgreSQL에 `mr_db` 데이터베이스를 생성합니다. +2. 프로젝트 루트에 `MR_config/local/` 폴더를 생성합니다. +3. 공유된 `application.example.yml` 파일을 해당 폴더에 복사한 뒤, 파일명을 **`application.yml`**로 변경합니다. +4. 본인의 로컬 DB 비밀번호와 개인 API Key를 입력한 후 서버를 구동합니다. + +### 🚀 로컬 빌드 명령어 +* **Windows PowerShell:** `./gradlew.bat build -x test` +* **Git Bash / Mac:** `./gradlew build -x test` +* **Swagger UI 주소:** `http://localhost:8080/swagger-ui/index.html` \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..1002a12e --- /dev/null +++ b/build.gradle @@ -0,0 +1,76 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.2' + id 'io.spring.dependency-management' version '1.1.7' + // formater + id 'io.spring.javaformat' version '0.0.41' +} + +group = 'com.mr' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // Swagger + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' + + // JWT + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + + // PostgreSQL 18, JPA + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + runtimeOnly 'org.postgresql:postgresql' + + // Lombok , DevTools + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + + // Health Check + implementation 'org.springframework.boot:spring-boot-starter-actuator' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +test { + useJUnitPlatform() +} + +// Private Config Copy +tasks.register('copyPrivateConfig', Copy) { + def envDir = file('./MR_config/local') + + if (!envDir.exists()) { + envDir.mkdirs() + file('./MR_config/local/application.yml').text = "# 이 경로에 복사한 로컬 설정을 채워 넣어 주세요!" + } + + from './MR_config/local' + into 'src/main/resources' +} + +tasks.named('processResources') { + dependsOn 'copyPrivateConfig' +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..8bdaf60c 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 00000000..2a84e188 --- /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.0.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 00000000..ef07e016 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/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/HEAD/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 + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -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 00000000..db3a6ac2 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -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 00000000..7649b1cb --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'mr' diff --git a/src/main/java/com.mr/Application.java b/src/main/java/com.mr/Application.java new file mode 100644 index 00000000..11783c70 --- /dev/null +++ b/src/main/java/com.mr/Application.java @@ -0,0 +1,13 @@ +package com.mr; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/src/main/java/com.mr/global/apipayload/ApiResponse.java b/src/main/java/com.mr/global/apipayload/ApiResponse.java new file mode 100644 index 00000000..fb67124f --- /dev/null +++ b/src/main/java/com.mr/global/apipayload/ApiResponse.java @@ -0,0 +1,22 @@ +package com.mr.global.apipayload; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.mr.global.apipayload.code.CommonStatus; + +@JsonPropertyOrder({"isSuccess", "code", "message", "data"}) +public record ApiResponse( + boolean isSuccess, + String code, + String message, + T data +) { + // 성공 + public static ApiResponse onSuccess(T data) { + return new ApiResponse<>(true, CommonStatus.SUCCESS.getCode(), CommonStatus.SUCCESS.getMessage(), data); + } + + // 실패 + public static ApiResponse onFailure(String code, String message, T data) { + return new ApiResponse<>(false, code, message, data); + } +} \ No newline at end of file diff --git a/src/main/java/com.mr/global/apipayload/code/BaseCode.java b/src/main/java/com.mr/global/apipayload/code/BaseCode.java new file mode 100644 index 00000000..3ea7e460 --- /dev/null +++ b/src/main/java/com.mr/global/apipayload/code/BaseCode.java @@ -0,0 +1,9 @@ +package com.mr.global.apipayload.code; + +import org.springframework.http.HttpStatus; + +public interface BaseCode { + HttpStatus getStatus(); + String getCode(); + String getMessage(); +} \ No newline at end of file diff --git a/src/main/java/com.mr/global/apipayload/code/CommonStatus.java b/src/main/java/com.mr/global/apipayload/code/CommonStatus.java new file mode 100644 index 00000000..25d78bdc --- /dev/null +++ b/src/main/java/com.mr/global/apipayload/code/CommonStatus.java @@ -0,0 +1,20 @@ +package com.mr.global.apipayload.code; + +import org.springframework.http.HttpStatus; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum CommonStatus implements BaseCode { + + // 공통 성공 / 실패 + SUCCESS(HttpStatus.OK, "COMMON_200", "요청에 성공하였습니다."), + INVALID_INPUT_VALUE(HttpStatus.BAD_REQUEST, "COMMON_400_01", "입력값이 올바르지 않습니다."), + HTTP_MESSAGE_NOT_READABLE(HttpStatus.BAD_REQUEST, "COMMON_400_02", "요청 본문(JSON) 파싱에 실패했습니다."), + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON_500_01", "서버 에러가 발생했습니다."); + + 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.mr/global/apipayload/code/StatusReasonDTO.java b/src/main/java/com.mr/global/apipayload/code/StatusReasonDTO.java new file mode 100644 index 00000000..67ebb734 --- /dev/null +++ b/src/main/java/com.mr/global/apipayload/code/StatusReasonDTO.java @@ -0,0 +1,10 @@ +package com.mr.global.apipayload.code; + +import org.springframework.http.HttpStatus; + +public record StatusReasonDTO( + HttpStatus status, + boolean isSuccess, + String code, + String message +) {} \ No newline at end of file diff --git a/src/main/java/com.mr/global/apipayload/domain/AuthErrorStatus.java b/src/main/java/com.mr/global/apipayload/domain/AuthErrorStatus.java new file mode 100644 index 00000000..f78da427 --- /dev/null +++ b/src/main/java/com.mr/global/apipayload/domain/AuthErrorStatus.java @@ -0,0 +1,20 @@ +package com.mr.global.apipayload.domain; + +import com.mr.global.apipayload.code.BaseCode; +import org.springframework.http.HttpStatus; +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum AuthErrorStatus implements BaseCode { + + // 예원님 도메인 에러코드 컨벤션 적용 + TOKEN_MISSING(HttpStatus.BAD_REQUEST, "AUTH_400_07", "토큰 값이 필요합니다."), + INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_401_01", "유효하지 않은 토큰입니다."), + EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_401_02", "만료된 토큰입니다."); + + 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.mr/global/apipayload/exception/GeneralException.java b/src/main/java/com.mr/global/apipayload/exception/GeneralException.java new file mode 100644 index 00000000..ee390f6e --- /dev/null +++ b/src/main/java/com.mr/global/apipayload/exception/GeneralException.java @@ -0,0 +1,20 @@ +package com.mr.global.apipayload.exception; + +import com.mr.global.apipayload.code.BaseCode; +import com.mr.global.apipayload.code.StatusReasonDTO; +import lombok.Getter; + +@Getter +public class GeneralException extends RuntimeException { + + private final BaseCode code; + + public GeneralException(BaseCode code) { + super(code.getMessage()); + this.code = code; + } + + public StatusReasonDTO getErrorReason() { + return new StatusReasonDTO(this.code.getStatus(), false, this.code.getCode(), this.code.getMessage()); + } +} \ No newline at end of file diff --git a/src/main/java/com.mr/global/apipayload/handler/GlobalExceptionHandler.java b/src/main/java/com.mr/global/apipayload/handler/GlobalExceptionHandler.java new file mode 100644 index 00000000..4a0614f2 --- /dev/null +++ b/src/main/java/com.mr/global/apipayload/handler/GlobalExceptionHandler.java @@ -0,0 +1,68 @@ +package com.mr.global.apipayload.handler; + +import com.mr.global.apipayload.ApiResponse; +import com.mr.global.apipayload.code.CommonStatus; +import com.mr.global.apipayload.exception.GeneralException; +import jakarta.validation.ConstraintViolationException; +import java.util.stream.Collectors; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + // 커스텀 예외 + @ExceptionHandler(GeneralException.class) + public ResponseEntity> handleGeneralException(GeneralException e) { + var reason = e.getErrorReason(); + ApiResponse response = ApiResponse.onFailure(reason.code(), reason.message(), null); + return new ResponseEntity<>(response, reason.status()); + } + + // @Valid 검증 실패 예외 + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + var status = CommonStatus.INVALID_INPUT_VALUE; + var errors = e.getBindingResult().getFieldErrors().stream() + .collect(Collectors.toMap( + error -> error.getField(), + error -> error.getDefaultMessage() != null ? error.getDefaultMessage() : "올바르지 않은 형식입니다.", + (existing, replacement) -> existing + )); + ApiResponse response = ApiResponse.onFailure(status.getCode(), status.getMessage(), errors); + return new ResponseEntity<>(response, status.getStatus()); + } + + // JSON 파싱 에러 + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { + var status = CommonStatus.HTTP_MESSAGE_NOT_READABLE; + ApiResponse response = ApiResponse.onFailure(status.getCode(), status.getMessage(), null); + return new ResponseEntity<>(response, status.getStatus()); + } + + // 파라미터 제약 조건 위반 예외 + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity> handleConstraintViolationException(ConstraintViolationException e) { + var status = CommonStatus.INVALID_INPUT_VALUE; + var errors = e.getConstraintViolations().stream() + .collect(Collectors.toMap( + violation -> violation.getPropertyPath().toString(), + violation -> violation.getMessage(), + (existing, replacement) -> existing + )); + ApiResponse response = ApiResponse.onFailure(status.getCode(), status.getMessage(), errors); + return new ResponseEntity<>(response, status.getStatus()); + } + + // 그 외 전체 서버 에러 처리 + @ExceptionHandler(Exception.class) + public ResponseEntity> handleAllException(Exception e) { + var status = CommonStatus.INTERNAL_SERVER_ERROR; + ApiResponse response = ApiResponse.onFailure(status.getCode(), status.getMessage(), null); + return new ResponseEntity<>(response, status.getStatus()); + } +} \ No newline at end of file diff --git a/src/main/java/com.mr/global/config/SecurityConfig.java b/src/main/java/com.mr/global/config/SecurityConfig.java new file mode 100644 index 00000000..7993a7ae --- /dev/null +++ b/src/main/java/com.mr/global/config/SecurityConfig.java @@ -0,0 +1,30 @@ +package com.mr.global.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +@EnableWebSecurity +public class SecurityConfig { + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .csrf(csrf -> { + try { + http.csrf(csrfSpec -> csrfSpec.disable()); + } catch (Exception e) { + throw new RuntimeException(e); + } + }) // CSRF 해제 + .authorizeHttpRequests(auth -> auth + // Swagger + .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() + .anyRequest().authenticated() + ); + return http.build(); + } +} \ No newline at end of file diff --git a/src/main/java/com.mr/global/file/FileCategory.java b/src/main/java/com.mr/global/file/FileCategory.java new file mode 100644 index 00000000..e69de29b diff --git a/src/main/java/com.mr/global/file/FileException.java b/src/main/java/com.mr/global/file/FileException.java new file mode 100644 index 00000000..e69de29b diff --git a/src/main/java/com.mr/global/file/S3Config.java b/src/main/java/com.mr/global/file/S3Config.java new file mode 100644 index 00000000..e69de29b diff --git a/src/main/java/com.mr/global/file/S3Service.java b/src/main/java/com.mr/global/file/S3Service.java new file mode 100644 index 00000000..e69de29b