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..c26cc44 --- /dev/null +++ b/.gitignore @@ -0,0 +1,261 @@ +### claude ### +CLAUDE.md + +### gradle ### +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### application.yml, application.properties +**/application-local.yml +**/application-dev.yml +**/application-test.yml +**/application.properties +src/main/resources/local +src/main/resources/application-prod.yml +**/application-dev-dev.yml +**/application-test-dev.yml +**/application-prod-secret.yml + +### logback-variables.properties +src/main/resources/logback-variables.properties + +### QueryDsl +**/generated +src/main/generated/ + + +### git ignore +# Created by https://www.toptal.com/developers/gitignore/api/java,intellij,macos,windows +# Edit at https://www.toptal.com/developers/gitignore?templates=java,intellij,macos,windows + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.toptal.com/developers/gitignore/api/java,intellij,macos,windows \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..db1f64f --- /dev/null +++ b/build.gradle @@ -0,0 +1,77 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.9' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'greenfirst' +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' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + // spring-boot-starter-validation + implementation 'org.springframework.boot:spring-boot-starter-validation' + // spring-data-jpa + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + // lombok + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + testCompileOnly 'org.projectlombok:lombok' + testAnnotationProcessor 'org.projectlombok:lombok' + // maria-db + runtimeOnly 'org.mariadb.jdbc:mariadb-java-client' + // swagger + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' + // modelmapper + implementation group: 'org.modelmapper', name: 'modelmapper', version: '3.0.0' + // querydsl + implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta' + annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jakarta" // 버전 변경 + annotationProcessor "jakarta.annotation:jakarta.annotation-api" + annotationProcessor "jakarta.persistence:jakarta.persistence-api" + // assertJ + implementation 'org.assertj:assertj-core:3.24.2' + // security + implementation 'org.springframework.boot:spring-boot-starter-security' + testImplementation 'org.springframework.security:spring-security-test' + // jwt + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5', + 'io.jsonwebtoken:jjwt-jackson:0.11.5' + // @Retryable + implementation 'org.springframework.retry:spring-retry:1.3.1' + // @Nullable 사용시, 'class file for javax.annotation.Nullable not found' 방지를 위한 의존성 추가 + implementation 'com.google.code.findbugs:jsr305:3.0.2' + // commons-io-IOUtils 사용을 위한 의존성 추가 + implementation 'commons-io:commons-io:2.14.0' + // HTML 파싱을 위한 jsoup + implementation 'org.jsoup:jsoup:1.14.3' + // slack + implementation 'com.slack.api:slack-api-client:1.30.0' + // redis + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + // email + implementation 'org.springframework.boot:spring-boot-starter-mail' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 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..d4081da --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# 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 0000000..db3a6ac --- /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 0000000..529a163 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'greenfirst-be' diff --git a/src/main/java/greenfirst/be/GreenfirstBeApplication.java b/src/main/java/greenfirst/be/GreenfirstBeApplication.java new file mode 100644 index 0000000..ccb874c --- /dev/null +++ b/src/main/java/greenfirst/be/GreenfirstBeApplication.java @@ -0,0 +1,17 @@ +package greenfirst.be; + + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + + +@EnableJpaAuditing +@SpringBootApplication +public class GreenfirstBeApplication { + + public static void main(String[] args) { + SpringApplication.run(GreenfirstBeApplication.class, args); + } + +} diff --git a/src/main/java/greenfirst/be/global/common/basetime/BaseTimeEntity.java b/src/main/java/greenfirst/be/global/common/basetime/BaseTimeEntity.java new file mode 100644 index 0000000..41614ef --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/basetime/BaseTimeEntity.java @@ -0,0 +1,27 @@ +package greenfirst.be.global.common.basetime; + + +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; + + +@EntityListeners(AuditingEntityListener.class) // Auditing(자동 값 매핑)기능 추가 +@Getter +@MappedSuperclass // 멤버 인스턴스가, entity의 컬럼으로 들어가도록 해줌 +public abstract class BaseTimeEntity { + + @CreatedDate // 최초 생성 시점 + @Column(updatable = false) + private LocalDateTime createdAt; + + @LastModifiedDate // 마지막 수정 시점 + private LocalDateTime updatedAt; + +} diff --git a/src/main/java/greenfirst/be/global/common/enums/base/BaseEnum.java b/src/main/java/greenfirst/be/global/common/enums/base/BaseEnum.java new file mode 100644 index 0000000..57fa9d5 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/enums/base/BaseEnum.java @@ -0,0 +1,14 @@ +package greenfirst.be.global.common.enums.base; + + +// 어떠한 type으로 들어오든 converter에 적용시킬 수 있도록, generic을 로 설정 +// V는 객체의 value, K는 객체의 Key값을 의미 +public interface BaseEnum { + + /** + * 각 Enum은 code와 desc를 return한다 + */ + V getCode(); + K getDescription(); + +} diff --git a/src/main/java/greenfirst/be/global/common/enums/base/BaseEnumConverter.java b/src/main/java/greenfirst/be/global/common/enums/base/BaseEnumConverter.java new file mode 100644 index 0000000..3719861 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/enums/base/BaseEnumConverter.java @@ -0,0 +1,43 @@ +package greenfirst.be.global.common.enums.base; + + +import jakarta.persistence.AttributeConverter; + +import java.util.Arrays; +import java.util.Objects; + + +// BaseEnum의 구현체인 Enum클래스와, T, K를 매개변수로 받아서 생성된다 +public class BaseEnumConverter & BaseEnum, V, K> implements AttributeConverter { + + //필드값 + private final Class eClass; + + + //생성자 + protected BaseEnumConverter(Class eClass) { + this.eClass = eClass; + } + + + // Db에 저장할 때 -> Enum의 V(여기서는 코드)로 저장함 + @Override + public V convertToDatabaseColumn(E attribute) { + return attribute != null ? attribute.getCode() : null; + } + + + // Db에서 가져올 때 -> V(코드)를 받아서 Enum으로 변환해줌 + @Override + public E convertToEntityAttribute(V dbData) { + // db에서 가져온 값이 null일때 + if (Objects.isNull(dbData)) { + return null; + } + return Arrays.stream(eClass.getEnumConstants()) + .filter(e -> e.getCode().equals(dbData)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown code: " + dbData)); + } + +} \ No newline at end of file diff --git a/src/main/java/greenfirst/be/global/common/enums/common/UserType.java b/src/main/java/greenfirst/be/global/common/enums/common/UserType.java new file mode 100644 index 0000000..1eb2980 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/enums/common/UserType.java @@ -0,0 +1,5 @@ +package greenfirst.be.global.common.enums.common; + + +public enum UserType { +} diff --git a/src/main/java/greenfirst/be/global/common/exception/AsyncExceptionHandler.java b/src/main/java/greenfirst/be/global/common/exception/AsyncExceptionHandler.java new file mode 100644 index 0000000..6c15cbd --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/exception/AsyncExceptionHandler.java @@ -0,0 +1,53 @@ +package greenfirst.be.global.common.exception; + + +import greenfirst.be.global.common.slack.SlackMessageSender; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; + + +@Slf4j +@Component +@RequiredArgsConstructor +public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler { + + // util + private final SlackMessageSender slackMessageSender; + private final BaseExceptionHandler baseExceptionHandler; + + + /** + * AsyncExceptionHandler + * 1. 비동기 작업에서 예외가 발생했을 때 처리 + * 2. 슬랙 메시지 전송 + */ + + // 1. 비동기 작업에서 예외가 발생했을 때 처리 + @Override + public void handleUncaughtException(Throwable ex, Method method, Object... params) { + // BaseException인 경우 + if (ex instanceof BaseException baseException) { + log.error("BaseException: [{}] {}", baseException.getStatus(), baseException.getStatus().getMessage()); + this.sendMessageToSlack(baseException); + } + // 이외의 경우 + else { + log.error("EventException: ", ex); + this.sendMessageToSlack((Exception) ex); + } + } + + + // 2. 슬랙 메시지 전송 + private void sendMessageToSlack(Exception e) { + // 에러 메시지 조합 + String slackErrorMessage = baseExceptionHandler.concatErrorMessage(e); + // 슬랙 메시지 전송 + slackMessageSender.sendMessage("☠ 예기치 못한 에러가 발생했습니다. 확인이 필요합니다.", slackErrorMessage); + } + +} diff --git a/src/main/java/greenfirst/be/global/common/exception/BaseException.java b/src/main/java/greenfirst/be/global/common/exception/BaseException.java new file mode 100644 index 0000000..3d33444 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/exception/BaseException.java @@ -0,0 +1,18 @@ +package greenfirst.be.global.common.exception; + + +import greenfirst.be.global.common.response.BaseResponseStatusInterface; +import lombok.Getter; + + +@Getter +public class BaseException extends RuntimeException { + + private final BaseResponseStatusInterface status; + + + public BaseException(BaseResponseStatusInterface status) { + this.status = status; + } + +} diff --git a/src/main/java/greenfirst/be/global/common/exception/BaseExceptionHandler.java b/src/main/java/greenfirst/be/global/common/exception/BaseExceptionHandler.java new file mode 100644 index 0000000..f56316d --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/exception/BaseExceptionHandler.java @@ -0,0 +1,203 @@ +package greenfirst.be.global.common.exception; + + +import greenfirst.be.global.common.response.BaseResponse; +import greenfirst.be.global.common.response.BaseResponseStatus; +import greenfirst.be.global.common.slack.SlackEvent; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.ConstraintViolationException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageConversionException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.stream.Collectors; + + +@Slf4j +@RestControllerAdvice +@RequiredArgsConstructor +public class BaseExceptionHandler { + + // util + private final ApplicationEventPublisher eventPublisher; + // value + @Value("${spring.config.activate.on-profile}") + private String activeProfile; + + + /** + * 발생한 예외 처리 + * 1. 등록된 에러 (BaseException) + * 2. security 인증 에러 (BadCredentialsException, AuthenticationException, AccessDeniedException) + * 3. 런타임 에러 (RuntimeException) + * 4. 유효성 검사 에러 (ConstraintViolationException, MethodArgumentNotValidException) + * 5. 컨버전 에러 (HttpMessageConversionException) + */ + + // 1. 등록된 에러 + @ExceptionHandler(BaseException.class) + protected ResponseEntity> BaseError(BaseException e) { + // BaseException의 BaseResponseStatus를 가져와서 BaseResponse를 만들어서 return해줌 + BaseResponse response = new BaseResponse<>(e.getStatus()); + log.error("BaseException -> {}({})", e.getStatus(), e.getStatus().getMessage(), e); + return new ResponseEntity<>(response, response.httpStatus()); + } + + + // 2. security 인증 에러 + @ExceptionHandler(BadCredentialsException.class) + protected ResponseEntity> handleBadCredentialsException(BadCredentialsException e) { + BaseResponse response = new BaseResponse<>(BaseResponseStatus.FAILED_TO_LOGIN); + log.error("BadCredentialsException: ", e); + return new ResponseEntity<>(response, response.httpStatus()); + } + + + // 3. 런타임 에러 + @ExceptionHandler(RuntimeException.class) + protected ResponseEntity> RuntimeError(RuntimeException e) { + // BaseException으로 잡히지 않는 RuntimeError는, INTERNAL_SEBVER_ERROR로 처리해줌 + BaseResponse response = new BaseResponse<>(BaseResponseStatus.INTERNAL_SERVER_ERROR); + // 로그 출력 + log.error("RuntimeException: ", e); + for (StackTraceElement s : e.getStackTrace()) { + System.out.println(s); + } + // slack 이벤트 + SlackEvent event = new SlackEvent("☠ 예기치 못한 에러가 발생했습니다. 확인이 필요합니다.", concatErrorMessage(e)); + eventPublisher.publishEvent(event); + return new ResponseEntity<>(response, response.httpStatus()); + } + + + // 4. 유효성 검사 에러 + @ExceptionHandler({ ConstraintViolationException.class, MethodArgumentNotValidException.class }) + protected ResponseEntity> ConstraintViolationException(Exception e) { + // BaseException으로 잡히지 않는 ConstraintViolationException 과 MethodArgumentNotValidException 은 INVALID_INPUT_VALUE 로 처리 + BaseResponse response = new BaseResponse<>(BaseResponseStatus.INVALID_INPUT_VALUE); + // 에러 메시지 + log.error("ConstraintViolationException: ", e); + return new ResponseEntity<>(response, response.httpStatus()); + } + + + // 5. 컨버전 에러 + @ExceptionHandler({ HttpMessageConversionException.class }) + protected ResponseEntity> HttpMessageConversionException(Exception e) { + // BaseException으로 잡히지 않는 HttpMessageConversionException 은 INVALID_INPUT_VALUE 로 처리 + BaseResponse response = new BaseResponse<>(BaseResponseStatus.MESSAGE_CONVERSION_ERROR); + // 에러 메시지 + log.error("HttpMessageConversionException: ", e); + return new ResponseEntity<>(response, response.httpStatus()); + } + + + // 에러 메시지 조합 + public String concatErrorMessage(Exception e) { + // 에러 전문 출력 + log.error("에러 전문: ", e); + // 1. 타임스탬프 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String timestamp = LocalDateTime.now().format(formatter); + // 2. 에러 발생 위치 정보 + StackTraceElement firstElement = (e.getStackTrace().length > 0) ? e.getStackTrace()[0] : null; + String classAndLine = (firstElement != null) + ? firstElement.getClassName() + " (" + firstElement.getFileName() + ":" + firstElement.getLineNumber() + ")" + : "알 수 없음"; + // 3. 스레드 정보 + String threadInfo = Thread.currentThread().getName(); + // 4. HTTP 요청 정보 (가능한 경우) + String requestInfo = "N/A"; + try { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); + requestInfo = request.getMethod() + " " + request.getRequestURI(); + // 요청 파라미터도 포함 (선택적) + String params = request.getParameterMap().entrySet().stream() + .map(entry -> entry.getKey() + "=" + String.join(",", entry.getValue())) + .collect(Collectors.joining("&")); + if (!params.isEmpty()) { + requestInfo += "?" + params; + } + } catch (Exception requestEx) { + // HTTP 요청 컨텍스트가 아닌 경우 무시 + } + // 5. 원인 체인 추출 (중첩된 모든 예외) + String causeChain = this.extractCauseChain(e); + // 6. 스택 트레이스 (주요 부분만) + String stackTrace = Arrays.stream(e.getStackTrace()) + .limit(5) + .map(StackTraceElement::toString) + .collect(Collectors.joining("\n")); + // 7. 액티브 프로필 (환경 정보) + String environment = activeProfile != null ? activeProfile : "unknown"; + // 메시지 생성 후 리턴 + return String.format( + "*🎯 Spring Boot 에러 발생 알림*\n" + + "*⏰ 발생 시간:* `%s`\n" + + "*🔴 에러 유형:* `%s`\n" + + "*📍 발생 위치:* `%s`\n" + + "*🧵 스레드:* `%s`\n" + + "*🌐 요청 정보:* `%s`\n" + + "*🔧 환경:* `%s`\n" + + "*⚠️ 메시지:* `%s`\n" + + "*🔎 원인 체인:* `%s`\n" + + "*📜 스택 트레이스:*\n```\n%s\n```", + timestamp, + e.getClass().getSimpleName(), + classAndLine, + threadInfo, + requestInfo, + environment, + e.getMessage() != null ? e.getMessage() : "상세 메시지 없음", + causeChain, + stackTrace + ); + } + + + // 원인 체인 추출 메서드 + private String extractCauseChain(Throwable throwable) { + // 원인 체인을 구성할 StringBuilder 초기화 + StringBuilder causeChain = new StringBuilder(); + // 현재 검사 중인 예외 객체 (처음에는 매개변수로 받은 예외) + Throwable current = throwable; + // 현재까지 처리한 예외 체인의 깊이 + int depth = 0; + // 순환 참조나 매우 깊은 체인 처리를 위한 최대 깊이 제한 + final int MAX_DEPTH = 10; // 무한 루프 방지 + // 예외 체인을 따라 내려가며 각 예외 정보 추출 + while (current != null && depth < MAX_DEPTH) { + // 두 번째 예외부터는 구분자 추가 + if (!causeChain.isEmpty()) { + causeChain.append(" → "); // 화살표로 원인 간의 연결 표시 + } + // 예외 클래스 이름 추가 (전체 패키지 경로 없이 단순 이름만) + causeChain.append(current.getClass().getSimpleName()); + // 예외 메시지가 있으면 클래스 이름 뒤에 콜론과 함께 추가 + if (current.getMessage() != null && !current.getMessage().isEmpty()) { + causeChain.append(": ").append(current.getMessage()); + } + // 다음 원인 예외로 이동 + current = current.getCause(); + depth++; + } + // 최대 깊이에 도달했지만 여전히 더 깊은 원인이 있는 경우 표시 + if (depth == MAX_DEPTH && current != null) { + causeChain.append(" → ..."); // 추가 원인이 더 있음을 표시 + } + return causeChain.toString(); + } + +} diff --git a/src/main/java/greenfirst/be/global/common/exception/BaseExceptionHandlerFilter.java b/src/main/java/greenfirst/be/global/common/exception/BaseExceptionHandlerFilter.java new file mode 100644 index 0000000..a27b670 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/exception/BaseExceptionHandlerFilter.java @@ -0,0 +1,80 @@ +package greenfirst.be.global.common.exception; + + +import com.fasterxml.jackson.databind.ObjectMapper; +import greenfirst.be.global.common.response.BaseResponse; +import greenfirst.be.global.common.response.BaseResponseStatus; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.security.sasl.AuthenticationException; +import java.io.IOException; + + +@Slf4j +@Component +public class BaseExceptionHandlerFilter extends OncePerRequestFilter { + + /** + * filter단에서 발생하는 에러는, 서블릿이 실행되기 전에 발생하므로 controller에서 잡지 못한다. + * 따라서 Error를 처리할 filter를 만들어서 사용한다 + */ + + // Filter단에서 발생하는 exception을 처리하는 필터 + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + try { + filterChain.doFilter(request, response); + } catch (BaseException e) { + log.error("BaseException -> {}({})", e.getStatus(), e.getStatus().getMessage(), e); + setErrorResponse(response, e); + } catch (AuthenticationException e) { + log.error("AuthenticationException -> {}", e.getMessage(), e); + // request url 로깅 + log.error("Request URL: {}", request.getRequestURI()); + // 에러 응답 + setErrorResponse(response, new BaseException(BaseResponseStatus.NO_SIGN_IN)); + } catch (AccessDeniedException e) { + log.error("AccessDeniedException -> {}", e.getMessage(), e); + // request url 로깅 + log.error("Request URL: {}", request.getRequestURI()); + // 요청자 권한 로깅 + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + authentication.getAuthorities().forEach(authority -> log.error("Request Role: {}", authority.getAuthority())); + // 에러 응답 + setErrorResponse(response, new BaseException(BaseResponseStatus.NO_ACCESS_AUTHORITY)); + } catch (Exception e) { + log.error("Exception -> {}", e.getMessage(), e); + setErrorResponse(response, new BaseException(BaseResponseStatus.INTERNAL_SERVER_ERROR)); + } + } + + + // Error를 Json으로 바꿔서 클라이언트에 전달 + private void setErrorResponse(HttpServletResponse response, + BaseException be) { + // 직렬화 하기위한 object mapper + ObjectMapper objectMapper = new ObjectMapper(); + // response의 contentType, 인코딩, 응답값을 정함 + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setCharacterEncoding("UTF-8"); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + BaseResponse baseResponse = new BaseResponse(be.getStatus()); + // BaseResponse를 return 하도록 설정 + try { + response.getWriter().write(objectMapper.writeValueAsString(baseResponse)); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/greenfirst/be/global/common/interceptor/ApiLogInterceptor.java b/src/main/java/greenfirst/be/global/common/interceptor/ApiLogInterceptor.java new file mode 100644 index 0000000..2b84ef8 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/interceptor/ApiLogInterceptor.java @@ -0,0 +1,106 @@ +package greenfirst.be.global.common.interceptor; + + +import greenfirst.be.global.common.enums.common.UserType; +import greenfirst.be.global.common.security.CustomUserDetails; +import greenfirst.be.global.common.wrapper.CachingRequestWrapper; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.HandlerMapping; + +import java.io.BufferedReader; +import java.util.Map; + + +@Slf4j +@Component +public class ApiLogInterceptor implements HandlerInterceptor { + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + try { + // request를 여러 번 읽기 위한 wrapping + CachingRequestWrapper requestWrapper = new CachingRequestWrapper(request); + // 로그 내용 + String contents = ""; + // 회원 여부 + contents += this.checkUser(requestWrapper); + // pathVariable 추출 + String pathVariables = this.getPathVariables(requestWrapper); + // Body 추출 및 password 보안 처리 + StringBuilder body = this.getBody(requestWrapper); + // 호출한 API, parameter, Path-vairable, body를 contents에 추가 + contents += this.completeContents(requestWrapper, pathVariables, body); + log.info(contents); + } catch (Exception e) { + log.error("ApiLogInterceptor Error: {}", e.getMessage()); + } + return true; + } + + + // 호출한 API, parameter, Path-vairable, body를 contents에 추가 + private String completeContents(CachingRequestWrapper requestWrapper, String pathVariables, StringBuilder body) { + return "Request Method: " + requestWrapper.getMethod() + "\n" + + "Request token: " + requestWrapper.getHeader("Authorization") + "\n" + + "Request URI: " + requestWrapper.getRequestURI() + "\n" + + "Request Parameter: " + requestWrapper.getQueryString() + "\n" + + "Request PathVariable: " + pathVariables + "\n" + + "Request Body: " + body + "\n" + + "====================================================================================="; + } + + + // 회원,비회원 확인 + private String checkUser(CachingRequestWrapper request) { + // contextHolder에서 principal 추출 + Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + CustomUserDetails authentication; + // 회원,비회원에 따라서 로그 내용 분리 + if (!principal.equals("anonymousUser")) { + authentication = (CustomUserDetails) principal; + UserType userType = authentication.getUserType(); + return "\n=====================================================================================\n[" + userType + "] -> Uuid: " + authentication.getUserUuid() + "\n" + "userEmail: " + + authentication.getUserEmail() + "\n"; + } else { + return "\n=====================================================================================\n[Non-User]\n"; + } + } + + + // PathVariable 추출 + private String getPathVariables(CachingRequestWrapper request) { + Map pathVariables; + try { + pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); + return pathVariables.toString(); + } catch (Exception e) { + return null; + } + + } + + + // Body 추출 및 password 보안 처리 + private StringBuilder getBody(CachingRequestWrapper request) { + StringBuilder body = new StringBuilder(); + BufferedReader reader; + try { + reader = request.getReader(); + String line; + // password, userPassword가 포함된 라인은 보안처리 + while ((line = reader.readLine()) != null) { + if (line.contains("password") || line.contains("userPassword") || line.contains("Password")) line = " \"password\": -- "; + body.append(line); + } + } catch (Exception e) { + log.error("ApiLogInterceptor Error: {}", e.getMessage()); + } + return body; + } + +} diff --git a/src/main/java/greenfirst/be/global/common/querydsl/CommonQueryDslUtil.java b/src/main/java/greenfirst/be/global/common/querydsl/CommonQueryDslUtil.java new file mode 100644 index 0000000..0754a7f --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/querydsl/CommonQueryDslUtil.java @@ -0,0 +1,23 @@ +package greenfirst.be.global.common.querydsl; + + +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Component; + + +@Component +public class CommonQueryDslUtil { + + /** + * CommonQueryDslUtil + * 1. 전체 페이지 수 계산 + */ + + // 1. 전체 페이지 수 계산 + public Long calculateTotalPage(Pageable pageable, Long totalCount) { + return totalCount != null + ? (long) Math.ceil((double) totalCount / pageable.getPageSize()) + : 0L; + } + +} diff --git a/src/main/java/greenfirst/be/global/common/redis/RedisUtil.java b/src/main/java/greenfirst/be/global/common/redis/RedisUtil.java new file mode 100644 index 0000000..b12101f --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/redis/RedisUtil.java @@ -0,0 +1,129 @@ +package greenfirst.be.global.common.redis; + + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.*; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.time.LocalDate; +import java.util.*; + + +@Slf4j +@Service +@RequiredArgsConstructor +public class RedisUtil { + + private final StringRedisTemplate template; + private final RedisTemplate integerTemplate; + private final RedisTemplate> localDateListTemplate; + + + // 값 가져오기 + public String getData(String key) { + ValueOperations valueOperations = template.opsForValue(); + return valueOperations.get(key); + } + + + // 값 존재 여부 + public boolean existData(String key) { + return Boolean.TRUE.equals(template.hasKey(key)); + } + + + // 값 저장 및 만료 시간 설정 + public void createDataExpire(String key, String value, long duration) { + ValueOperations valueOperations = template.opsForValue(); + Duration expireDuration = Duration.ofSeconds(duration); + valueOperations.set(key, value, expireDuration); + } + + + // List 값 저장 + public void createLocalDateListData(String key, List value) { + ValueOperations> valueOperations = localDateListTemplate.opsForValue(); + valueOperations.set(key, value); + } + + + // List 값 조회 + public List getLocalDateListData(String key) { + ValueOperations> valueOperations = localDateListTemplate.opsForValue(); + return valueOperations.get(key); + } + + + // int 값 저장 + public void createIntegerData(String key, int value) { + ValueOperations valueOperations = integerTemplate.opsForValue(); + valueOperations.set(key, value); + } + + + // 값 삭제 + public void deleteData(String key) { + template.delete(key); + } + + + // Integer 값 +1 증가 + public Long increment(String key) { + ValueOperations valueOperations = template.opsForValue(); + return valueOperations.increment(key); + } + + + // Integer 값 -1 감소 + public Long decrement(String key) { + ValueOperations valueOperations = template.opsForValue(); + return valueOperations.decrement(key); + } + + + // 특정 문자열로 시작되는 key 와 value 를 조회 + public Map scanKeysAndValue(String pattern) { + // 한번 스캔시에 가져올 최대 개수와, 패턴을 설정 + ScanOptions scanOptions = ScanOptions.scanOptions().count(100).match(pattern + "*").build(); + Map dataMap = new HashMap<>(); + // 스캔 시작 + try (Cursor cursor = template.getConnectionFactory().getConnection().keyCommands().scan(scanOptions)) { + // 더 이상 가져올 데이터가 없을 때까지 반복 + while (cursor.hasNext()) { + String key = new String(cursor.next()); + dataMap.put(key, Integer.parseInt(getData(key))); + } + } + log.info("dataMap: {}", dataMap); + return dataMap; + } + + + // key가 있는지 확인 + public Boolean hasKey(String key) { + return template.hasKey(key); + } + + + // 키에 해당되는 값을 가져오고, 해당 키의 값을 value로 설정 + public String getAndSetData(String key, String value) { + ValueOperations valueOperations = template.opsForValue(); + return valueOperations.getAndSet(key, value); + } + + + // 특정 문자열로 시작되는 key와, Scan 범위를 전달받아 조회 + public Set scanKeys(String pattern, int scanCount) { + ScanOptions scanOptions = ScanOptions.scanOptions().count(scanCount).match(pattern + "*").build(); + Set keys = new HashSet<>(); + try (Cursor cursor = template.getConnectionFactory().getConnection().keyCommands().scan(scanOptions)) { + while (cursor.hasNext()) { + keys.add(new String(cursor.next())); + } + } + return keys; + } + +} diff --git a/src/main/java/greenfirst/be/global/common/response/BaseResponse.java b/src/main/java/greenfirst/be/global/common/response/BaseResponse.java new file mode 100644 index 0000000..b632a4a --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/response/BaseResponse.java @@ -0,0 +1,33 @@ +package greenfirst.be.global.common.response; + + +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; + +import static greenfirst.be.global.common.response.BaseResponseStatus.SUCCESS; + + +public record BaseResponse(HttpStatusCode httpStatus, Boolean isSuccess, String message, int code, T result) { + + /** + * 필요값 : Http상태코드, 성공여부, 메시지, 에러코드, 결과값 + */ + + // 요청에 성공한 경우 -> return 객체가 필요한 경우 + public BaseResponse(T result) { + this(HttpStatus.OK, true, SUCCESS.getMessage(), SUCCESS.getCode(), result); + } + + + // 요청에 성공한 경우 -> return 객체가 필요 없는 경우 + public BaseResponse() { + this(HttpStatus.OK, true, SUCCESS.getMessage(), SUCCESS.getCode(), null); + } + + + // 요청 실패한 경우 + public BaseResponse(BaseResponseStatusInterface status) { + this(status.getHttpStatusCode(), false, status.getMessage(), status.getCode(), null); + } + +} diff --git a/src/main/java/greenfirst/be/global/common/response/BaseResponseStatus.java b/src/main/java/greenfirst/be/global/common/response/BaseResponseStatus.java new file mode 100644 index 0000000..9e47498 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/response/BaseResponseStatus.java @@ -0,0 +1,264 @@ +package greenfirst.be.global.common.response; + + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; + + +@Getter +@AllArgsConstructor +public enum BaseResponseStatus implements BaseResponseStatusInterface { + + /** + * 200: 요청 성공 + **/ + SUCCESS(HttpStatus.OK, true, 200, "요청에 성공하였습니다."), + + /** + * 400: security 에러 + */ + WRONG_JWT_TOKEN(HttpStatus.UNAUTHORIZED, false, 401, "다시 로그인 해주세요"), + NO_SIGN_IN(HttpStatus.UNAUTHORIZED, false, 402, "로그인을 먼저 진행해주세요"), + NO_ACCESS_AUTHORITY(HttpStatus.FORBIDDEN, false, 403, "접근 권한이 없거나, 로그인이 필요합니다"), + DISABLED_USER(HttpStatus.FORBIDDEN, false, 404, "비활성화된 계정입니다"), + FAILED_TO_RESTORE(HttpStatus.INTERNAL_SERVER_ERROR, false, 405, "계정 복구에 실패했습니다. 관리자에게 문의해주세요."), + + /** + * 900: 기타 에러 + */ + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false, 900, "서버 오류가 발생했습니다. 관리자에게 문의해주세요."), + SSE_SEND_FAIL(HttpStatus.INTERNAL_SERVER_ERROR, false, 901, "알림 전송에 실패하였습니다."), + INVALID_INPUT_VALUE(HttpStatus.BAD_REQUEST, false, 902, "잘못된 입력값입니다. 다시 확인해주세요."), + LOGGING_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false, 903, "로그 기록 중 에러가 발생했습니다."), + SLACK_SEND_MESSAGE_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false, 904, "Slack 메시지 전송에 실패하였습니다."), + MESSAGE_CONVERSION_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, false, 905, "값 변환 중 에러가 발생했습니다. 다시 확인해주세요"), + + /** + * 2000: users service error + */ + // token + TOKEN_NOT_VALID(HttpStatus.UNAUTHORIZED, false, 2001, "토큰이 유효하지 않습니다."), + + // Users + DUPLICATED_USER(HttpStatus.CONFLICT, false, 2101, "이미 가입된 멤버입니다."), + FAILED_TO_LOGIN(HttpStatus.UNAUTHORIZED, false, 2102, "아이디 또는 패스워드를 다시 확인하세요."), + DUPLICATED_SOCIAL_USER(HttpStatus.CONFLICT, false, 2103, "이미 소셜 연동된 계정입니다."), + DUPLICATED_SOCIAL_PROVIDER_USER(HttpStatus.CONFLICT, false, 2104, "계정에 동일한 플랫폼이 이미 연동되어있습니다"), + NO_EXIST_USER(HttpStatus.NOT_FOUND, false, 2105, "존재하지 않는 유저 정보입니다."), + PASSWORD_SAME_FAILED(HttpStatus.BAD_REQUEST, false, 2106, "현재 사용중인 비밀번호 입니다."), + PASSWORD_CONTAIN_NUM_FAILED(HttpStatus.BAD_REQUEST, false, 2107, "휴대폰 번호를 포함한 비밀번호 입니다."), + PASSWORD_MATCH_FAILED(HttpStatus.BAD_REQUEST, false, 2108, "패스워드를 다시 확인해주세요."), + NO_SUPPORTED_PROVIDER(HttpStatus.BAD_REQUEST, false, 2109, "지원하지 않는 플랫폼입니다"), + DUPLICATED_NICKNAME(HttpStatus.CONFLICT, false, 2010, "이미 사용중인 닉네임입니다."), + SAME_NICKNAME(HttpStatus.CONFLICT, false, 2011, "현재 사용중인 닉네임입니다."), + INVALID_EMAIL_ADDRESS(HttpStatus.BAD_REQUEST, false, 2012, "이메일을 다시 확인해주세요."), + NO_PRIVACY_SETTINGS(HttpStatus.INTERNAL_SERVER_ERROR, false, 2013, "개인정보 설정이 존재하지 않습니다. 서버 관리자에게 문의해주세요"), + WRONG_AUTH_EMAIL(HttpStatus.BAD_REQUEST, false, 2014, "요청 이메일이 일치하지 않습니다"), + MISSING_CREATE_USER_VALUE(HttpStatus.BAD_REQUEST, false, 2015, "유저 생성시 필요한 값이 누락되었습니다"), + MISSING_CREATE_PRIVACY_SETTING_VALUE(HttpStatus.BAD_REQUEST, false, 2016, "개인정보 설정 생성시 필요한 값이 누락되었습니다"), + MISSING_CREATE_NATIONALITY_VALUE(HttpStatus.BAD_REQUEST, false, 2017, "국적 생성시 필요한 값이 누락되었습니다"), + MISSING_CREATE_COMPANY_VALUE(HttpStatus.BAD_REQUEST, false, 2018, "회사 생성시 필요한 값이 누락되었습니다"), + MISSING_CREATE_USER_COURSE_REGISTRATION_VALUE(HttpStatus.BAD_REQUEST, false, 2019, "유저 수강신청내역 생성시 필요한 값이 누락되었습니다"), + NO_EXIST_USER_COURSE_REGISTRATION(HttpStatus.NOT_FOUND, false, 2020, "결제 내역이 존재하지 않습니다."), + NOT_MATCH_ORDER_NUMBER_AND_COHORT_ATTENDEE_ID(HttpStatus.BAD_REQUEST, false, 2021, "주문번호, 혹은 수강생 id가 일치하지 않습니다."), + ONLY_ORDER_USER_CAN_CHECK(HttpStatus.BAD_REQUEST, false, 2022, "본인의 결제 내역만 확인할 수 있습니다."), + MISSING_REQUIRED_PRIVACY_SETTING(HttpStatus.BAD_REQUEST, false, 2023, "필수 개인정보 설정이 누락되었습니다."), + NO_EXIST_PRIVACY_SETTING_TYPE(HttpStatus.NOT_FOUND, false, 2024, "존재하지 않는 개인정보 설정 타입입니다."), + PASSWORD_NOT_MATCH(HttpStatus.BAD_REQUEST, false, 2025, "입력하신 비밀번호가 일치하지 않습니다. 다시 확인해주세요."), + NO_EXIST_USER_STATISTICS(HttpStatus.NOT_FOUND, false, 2026, "존재하지 않는 유저 통계입니다."), + /** + * 3000: admin service error + */ + MISSING_CREATE_ADMIN_VALUE(HttpStatus.BAD_REQUEST, false, 3001, "관리자 생성시 필요한 값이 누락되었습니다"), + NO_EXIST_ADMIN(HttpStatus.NOT_FOUND, false, 3002, "존재하지 않는 관리자입니다."), + MISSING_CREATE_VENDOR_VALUE(HttpStatus.BAD_REQUEST, false, 3003, "벤더 생성시 필요한 값이 누락되었습니다"), + NO_EXIST_VENDOR(HttpStatus.NOT_FOUND, false, 3004, "존재하지 않는 벤더입니다."), + NO_EXIST_ADMIN_ROLE(HttpStatus.NOT_FOUND, false, 3005, "존재하지 않는 관리자 권한입니다."), + INACTIVE_ACCOUNT(HttpStatus.FORBIDDEN, false, 3006, "비활성화된 관리자입니다."), + + /** + * 4000: category service error + */ + MISSING_CREATE_COURSE_CATEGORY_VALUE(HttpStatus.BAD_REQUEST, false, 4001, "카테고리 생성시 필요한 값이 누락되었습니다"), + NO_EXIST_CATEGORY(HttpStatus.NOT_FOUND, false, 4002, "존재하지 않는 카테고리입니다."), + CATEGORY_HAS_SUBCATEGORY(HttpStatus.BAD_REQUEST, false, 4003, "하위 카테고리가 존재하는 카테고리는 삭제할 수 없습니다."), + NOT_REGULAR_COURSE_CANNOT_GET_CATEGORY(HttpStatus.BAD_REQUEST, false, 4004, "정규 과정이 아닙니다. 카테고리를 조회할 수 없습니다."), + CATEGORY_NAME_DUPLICATION(HttpStatus.BAD_REQUEST, false, 4005, "입력한 카테고리 이름은 상위 카테고리의 하위 그룹에 존재하는 이름입니다."), + CATEGORY_ADMIN_ROLE_NOT_MATCH(HttpStatus.BAD_REQUEST, false, 4006, "카테고리 관리 권한이 없습니다."), + CATEGORY_HAS_COURSE(HttpStatus.BAD_REQUEST, false, 4007, "해당 카테고리에 속한 과정이 존재하여 삭제할 수 없습니다."), + CATEGORY_HAS_COURSE_AND_SUBCATEGORY(HttpStatus.BAD_REQUEST, false, 4008, "해당 카테고리에 속한 과정과 하위 카테고리가 존재하여 삭제할 수 없습니다."), + CATEGORY_CODE_INVALID(HttpStatus.BAD_REQUEST, false, 4009, "카테고리 코드는 3~10자 이내의 영문 대문자, 숫자, 하이픈(-)으로 구성되어야 합니다."), + /** + * 5000: notification service error + */ + // Notification + NO_EXIST_NOTIFICATION_SETTING(HttpStatus.NOT_FOUND, false, 5001, "유저의 알림 설정이 존재하지 않습니다."), + EXIST_NOTIFICATION_SETTING(HttpStatus.BAD_REQUEST, false, 5002, "유저의 알림 설정이 이미 존재합니다."), + NO_EXIST_NOTIFICATION(HttpStatus.NOT_FOUND, false, 5003, "존재하지 않는 알림입니다."), + CANNOT_SHARE(HttpStatus.BAD_REQUEST, false, 5004, "공유할 수 없는 유저입니다."), + + /** + * 6000: center service error + */ + MISSING_CREATE_EDUCATION_CENTER_VALUE(HttpStatus.BAD_REQUEST, false, 6001, "교육장 생성시 필요한 값이 누락되었습니다."), + NO_EXIST_EDUCATION_CENTER(HttpStatus.NOT_FOUND, false, 6002, "존재하지 않는 교육장입니다"), + + /** + * 7000: banner service error + */ + MISSING_CREATE_BANNER_VALUE(HttpStatus.BAD_REQUEST, false, 7001, "배너 생성시 필요한 값이 누락되었습니다"), + NO_EXIST_BANNER_PAGE(HttpStatus.NOT_FOUND, false, 7002, "존재하지 않는 페이지입니다."), + NO_EXIST_BANNER(HttpStatus.NOT_FOUND, false, 7003, "존재하지 않는 배너입니다."), + + /** + * 8000: course service error + */ + // course + MISSING_CREATE_COURSE(HttpStatus.BAD_REQUEST, false, 8001, "과정 생성시 필요한 값이 누락되었습니다. - 교육 과정"), + NO_EXIST_COURSE(HttpStatus.NOT_FOUND, false, 8002, "존재하지 않는 교육과정입니다."), + NO_EXIST_COURSE_TYPE(HttpStatus.NOT_FOUND, false, 8003, "존재하지 않는 과정 종류입니다.- 과정 타입별 옵션"), + MISSING_CREATE_COURSE_TYPE_OPTION(HttpStatus.BAD_REQUEST, false, 8004, "과정 생성시 필요한 값이 누락되었습니다. - 과정 옵션"), + MISSING_CREATE_COURSE_OPTION(HttpStatus.BAD_REQUEST, false, 8005, "과정 생성시 필요한 값이 누락되었습니다."), + MISSING_COURSE_CODE(HttpStatus.BAD_REQUEST, false, 8006, "과정 코드가 누락되었습니다."), + DUPLICATE_COURSE_CODE(HttpStatus.BAD_REQUEST, false, 8007, "존재하는 과정 코드입니다."), + MISSING_ORDER_TYPE(HttpStatus.BAD_REQUEST, false, 8008, "정렬 타입이 누락되었습니다."), + VENDOR_NOT_MATCH(HttpStatus.BAD_REQUEST, false, 8009, "소속 회사의 데이터만 조회할 수 있습니다."), + COURSE_UNIT_LEARNING_TIME_NOT_MATCH(HttpStatus.BAD_REQUEST, false, 8010, "과정의 시수와 단원들의 시수의 합이 일치하지 않습니다."), + COURSE_UNIT_LEARNING_PERIOD_NOT_MATCH(HttpStatus.BAD_REQUEST, false, 8011, "과정의 일수와 단원들의 일수의 합이 일치하지 않습니다."), + INVALID_COURSE_CODE(HttpStatus.BAD_REQUEST, false, 8012, "과정 코드는 6자 이내의 영문 대문자, 소문자, 숫자로 구성되어야 합니다."), + FAILED_TO_LINK_COURSE(HttpStatus.BAD_REQUEST, false, 8013, "과정 연계에 실패했습니다."), + // unit + MISSING_CREATE_COURSE_UNIT_VALUE(HttpStatus.BAD_REQUEST, false, 8101, "교육과정 단원 생성시 필요한 값이 누락되었습니다."), + INVALID_UNIT_SCHEDULE_DATE(HttpStatus.BAD_REQUEST, false, 8102, "단원 시작일은 종료일보다 늦을 수 없습니다."), + MISSING_CREATE_COURSE_LINKED_COURSE(HttpStatus.BAD_REQUEST, false, 8103, "과정 생성시 필요한 값이 누락되었습니다.- 연계 과정"), + NO_EXIST_COURSE_UNIT(HttpStatus.NOT_FOUND, false, 8104, "존재하지 않는 교육단원입니다."), + MISSING_COURSE_UNIT_CODE(HttpStatus.BAD_REQUEST, false, 8105, "단원 코드가 누락되었습니다."), + MISSING_CREATE_UNIT_SCHEDULE_VALUE(HttpStatus.BAD_REQUEST, false, 8106, "단원 스케쥴 생성시 필요한 값이 누락되었습니다."), + NO_EXIST_UNIT_SCHEDULE(HttpStatus.NOT_FOUND, false, 8107, "존재하지 않는 단원 스케쥴입니다."), + COURSE_SESSION_LEARNING_TIME_NOT_MATCH(HttpStatus.BAD_REQUEST, false, 8108, "단원의 시수와 차수들의 시수의 합이 일치하지 않습니다."), + COURSE_SESSION_LEARNING_PERIOD_NOT_MATCH(HttpStatus.BAD_REQUEST, false, 8109, "단원의 일수와 차수들의 일수의 합이 일치하지 않습니다."), + CANNOT_DELETE_COHORT_EXIST_UNIT(HttpStatus.BAD_REQUEST, false, 8110, "단원에 연계된 기수가 존재하여 삭제할 수 없습니다."), + CANNOT_DELETE_COHORT_EXIST_COURSE(HttpStatus.BAD_REQUEST, false, 8111, "과정에 연계된 기수가 존재하여 삭제할 수 없습니다."), + CANNOT_DELETE_COHORT_EXIST_SESSION(HttpStatus.BAD_REQUEST, false, 8112, "차수에 연계된 기수가 존재하여 삭제할 수 없습니다."), + COURSE_SESSION_LEARNING_TIME_EXCEEDS_UNIT_LIMIT(HttpStatus.BAD_REQUEST, false, 8113, "입력한 차수의 시수 합이 단원의 시수를 초과합니다."), + COURSE_SESSION_LEARNING_PERIOD_EXCEEDS_UNIT_LIMIT(HttpStatus.BAD_REQUEST, false, 8014, "입력한 차수의 기간의 합이 단원의 일수를 초과합니다."), + CANNOT_UPDATE_COURSE_UNIT(HttpStatus.BAD_REQUEST, false, 8015, "단원이 속한 과정에서 이미 기수가 생성되어 있어 수정할 수 없습니다."), + // session + MISSING_CREATE_COURSE_SESSION_VALUE(HttpStatus.BAD_REQUEST, false, 8201, "교육단원 차수 생성시 필요한 값이 누락되었습니다."), + MISSING_CREATE_SESSION_SCHEDULE_VALUE(HttpStatus.BAD_REQUEST, false, 8202, "차수 스케쥴 생성시 필요한 값이 누락되었습니다."), + NO_EXIST_SESSION_SCHEDULE(HttpStatus.NOT_FOUND, false, 8203, "존재하지 않는 차수 스케쥴입니다."), + INVALID_SESSION_SCHEDULE_DATE(HttpStatus.BAD_REQUEST, false, 8204, "차수 시작시간은 종료시간보다 늦을 수 없습니다.."), + NO_EXIST_COURSE_SESSION(HttpStatus.NOT_FOUND, false, 8205, "존재하지 않는 교육 차수입니다."), + COURSE_SESSION_DETAIL_LEARNING_TIME_EXCEEDS_UNIT_LIMIT(HttpStatus.BAD_REQUEST, false, 8206, "입력한 차수 상세의 시수 합이 차수의 시수를 초과합니다."), + MISSING_CREATE_COURSE_SESSION_DETAIL_VALID(HttpStatus.BAD_REQUEST, false, 8207, "세션 상세 값 생성시 필요한 값이 누락되었습니다. - 세션 상세"), + DUPLICATED_SESSION_DETAIL_ORDER(HttpStatus.BAD_REQUEST, false, 8208, "같은 그룹 내부에 중복되는 순서가 있습니다."), + CANNOT_UPDATE_COURSE_SESSION(HttpStatus.BAD_REQUEST, false, 8209, "교육 차수가 속한 과정에서 이미 기수가 생성되어 있어 수정할 수 없습니다."), + // cohort + MISSING_CREATE_COHORT_VALUE(HttpStatus.BAD_REQUEST, false, 8301, "기수 생성시 필요한 값이 누락되었습니다."), + COHORT_REGISTRATION_START_DATE_CANNOT_LATER_THAN_END_DATE(HttpStatus.BAD_REQUEST, false, 8302, "기수 등록 시작일은 등록 종료일보다 늦을 수 없습니다."), + COHORT_REGISTRATION_END_DATE_CANNOT_LATER_THAN_COHORT_START_DATE(HttpStatus.BAD_REQUEST, false, 8303, "기수 등록 종료일은 기수 시작일보다 늦을 수 없습니다."), + INVALID_COHORT_DATE(HttpStatus.BAD_REQUEST, false, 8303, "기수 시작일은 기수 종료일보다 늦을 수 없습니다."), + REGULAR_COURSE_COHORT_OPTION_INVALID(HttpStatus.BAD_REQUEST, false, 8304, "정규 과정 기수 옵션이 유효하지 않습니다."), + NO_EXIST_COHORT(HttpStatus.NOT_FOUND, false, 8305, "존재하지 않는 기수입니다."), + MISSING_CREATE_COHORT_ATTENDEE_VALUE(HttpStatus.BAD_REQUEST, false, 8306, "기수 신청자 생성시 필요한 값이 누락되었습니다."), + ALREADY_REGISTERED_COHORT(HttpStatus.BAD_REQUEST, false, 8307, "이미 신청이 완료된 과정 기수입니다."), + NO_EXIST_COHORT_UNIT_SCHEDULE(HttpStatus.NOT_FOUND, false, 8308, "해당 기수의 단원 스케쥴이 존재하지 않습니다."), + DUPLICATED_COHORT_NUMBER(HttpStatus.BAD_REQUEST, false, 8309, "이미 존재하는 기수 번호입니다."), + ONLY_PENDING_COHORT_CAN_DELETE(HttpStatus.BAD_REQUEST, false, 8310, "대기중이거나 폐강된 기수만 삭제할 수 있습니다."), + CANNOT_DELETE_ATTENDEE_EXIST_COHORT(HttpStatus.BAD_REQUEST, false, 8311, "기수에 수강 신청자가 존재하여 삭제할 수 없습니다."), + NO_EXIST_SUPPORT_FUND_TYPE(HttpStatus.NOT_FOUND, false, 8312, "존재하지 않는 지원금 종류입니다."), + PAYMENT_METHOD_REQUIRED(HttpStatus.BAD_REQUEST, false, 8313, "기수 생성시 결제 방법은 필수입니다."), + TOO_FAR_YEAR(HttpStatus.BAD_REQUEST, false, 8314, "최대 내년까지의 일정만 등록하실 수 있습니다. 기간을 다시 설정해주세요."), + CLOSED_COHORT_CANNOT_UPDATE(HttpStatus.BAD_REQUEST, false, 8315, "폐강된 기수는 수정이 불가능합니다."), + INVALID_COHORT_DATA_COLUMN(HttpStatus.BAD_REQUEST, false, 8316, "일정 검색 기준 값이 잘못되었습니다."), + START_DATE_CANNOT_BE_HOLIDAY(HttpStatus.BAD_REQUEST, false, 8317, "과정 시작일은 휴일로 설정할 수 없습니다. 시작일을 다시 확인해주세요"), + // attendee + NO_EXIST_COHORT_ATTENDEE(HttpStatus.BAD_REQUEST, false, 8401, "존재하지 않는 기수 수강 신청자입니다."), + COHORT_ATTENDEE_REJECTED(HttpStatus.BAD_REQUEST, false, 8402, "신청이 거부된 과정입니다. 관리자에게 문의해주세요."), + COHORT_STATUS_NOT_RECRUITING(HttpStatus.BAD_REQUEST, false, 8403, "현재 모집중인 교육 기수가 아닙니다. 관리자에게 문의해주세요."), + COHORT_ENROLLMENT_CAPACITY_EXCEEDED(HttpStatus.BAD_REQUEST, false, 8404, "해당 교육 과정은 현재 수강 정원이 초과되어 신청이 불가능합니다. 관리자에게 문의해주세요."), + COHORT_ATTENDEE_NOT_DELETABLE(HttpStatus.BAD_REQUEST, false, 8405, "현재 승인/결제가 완료되거나 진행중인 교육과정이 존재하여 탈퇴가 불가능합니다. 관리자에게 문의해주세요."), + // certification + MISSING_CREATE_CERTIFICATION(HttpStatus.BAD_REQUEST, false, 8501, "수료증 생성시 필요한 값이 누락되었습니다."), + NO_COMPLETE_COHORT_ATTENDEE_EXISTS(HttpStatus.BAD_REQUEST, false, 8502, "수료증을 발급할 수 있는 과정이 없습니다."), + /** + * 9000: payment service error + */ + NO_EXIST_VAT_STATUS(HttpStatus.NOT_FOUND, false, 9001, "VAT 여부를 잘못 입력하셨습니다. 다시 확인해주세요. 계속해서 동일한 문제가 발생하는 경우, 관리자에게 문의해주세요."), + NO_EXIST_INVOICE_ISSUE_STATUS(HttpStatus.NOT_FOUND, false, 9002, "계산서 발행 여부를 잘못 입력하셨습니다. 다시 확인해주세요. 계속해서 동일한 문제가 발생하는 경우, 관리자에게 문의해주세요."), + NO_EXIST_PAYMENT_STATUS(HttpStatus.NOT_FOUND, false, 9003, "결제 상태를 잘못 입력하셨습니다. 다시 확인해주세요. 계속해서 동일한 문제가 발생하는 경우, 관리자에게 문의해주세요."), + NO_EXIST_PAYMENT(HttpStatus.NOT_FOUND, false, 9004, "결제 내역이 존재하지 않습니다. 만약 결제를 진행하셨다면, 관리자에게 문의해주세요."), + + /** + * 10,000: board service error + */ + BOARD_TYPE_NOT_FOUND(HttpStatus.NOT_FOUND, false, 10001, "존재하지 않는 게시판 종류입니다."), + MISSING_BOARD_VALUE(HttpStatus.BAD_REQUEST, false, 10002, "게시판 종류 생성시 필요한 값이 누락되었습니다."), + BOARD_NOT_FOUND(HttpStatus.NOT_FOUND, false, 10003, "소속된 벤더사의 게시판이 아니거나 존재하지 않는 게시판입니다."), + MISSING_BOARD_CLASSIFICATION_VALUE(HttpStatus.BAD_REQUEST, false, 10004, "게시판 분류 생성시 필요한 값이 누락되었습니다."), + CANNOT_CREATE_BOARD(HttpStatus.BAD_REQUEST, false, 10005, "해당 타입의 게시판은 정책상 하나만 유지 가능합니다."), + + /** + * 11,000: post service error + */ + MISSING_POST_VALUE(HttpStatus.BAD_REQUEST, false, 11001, "게시물 생성시 필요한 값이 누락되었습니다."), + MISSING_POST_IMAGE_VALUE(HttpStatus.BAD_REQUEST, false, 11002, "게시물 이미지 생성시 필요한 값이 누락되었습니다."), + MISSING_POST_FILE_VALUE(HttpStatus.BAD_REQUEST, false, 11002, "게시물 이미지 생성시 필요한 값이 누락되었습니다."), + MISSING_TAG_VALUE(HttpStatus.BAD_REQUEST, false, 11003, "태그 생성시 필요한 값이 누락되었습니다."), + MISSING_POST_OPTION_VALUE(HttpStatus.BAD_REQUEST, false, 11004, "게시물 옵션 생성시 필요한 값이 누락되었습니다."), + CANNOT_POST_ON_BOARD(HttpStatus.BAD_REQUEST, false, 11005, "해당 게시판에 게시물을 작성할 수 없습니다."), + CANNOT_ACCESS_ON_BOARD(HttpStatus.BAD_REQUEST, false, 11007, "해당 게시판에 접근할 수 없습니다."), + CANNOT_ACCESS_ON_POST(HttpStatus.BAD_REQUEST, false, 11008, "해당 게시물에 접근할 수 없습니다."), + POST_NOT_FOUND(HttpStatus.NOT_FOUND, false, 11009, "게시글이 삭제되었거나 없습니다."), + POST_OPTION_NOT_FOUND(HttpStatus.NOT_FOUND, false, 11010, "존재하지 않는 게시물 옵션입니다."), + VENDOR_NOT_MATCHED(HttpStatus.BAD_REQUEST, false, 11011, "같은 벤더의 게시판이 아닙니다."), + CANNOT_UPDATE_POST(HttpStatus.BAD_REQUEST, false, 11012, "본인의 게시물만 수정할 수 있습니다."), + CANNOT_DELETE_POST(HttpStatus.BAD_REQUEST, false, 11013, "본인의 게시물만 삭제할 수 있습니다."), + VALID_REQUEST_BOARD_RELATION(HttpStatus.BAD_REQUEST, false, 11014, "게시판과 분류가 연관되어있지 않습니다."), + /** + * 12,000: comment service error + */ + MISSING_COMMENT_VALUE(HttpStatus.BAD_REQUEST, false, 12001, "댓글 상세 내용 값이 누락되었습니다."), + MISSING_RECOMMENT_VALUE(HttpStatus.BAD_REQUEST, false, 12002, "대댓글 생성시 필요한 값이 누락되었습니다."), + MISSING_POST_COMMENT_VALUE(HttpStatus.BAD_REQUEST, false, 12003, "게시글 댓글 생성시 필요한 값이 누락되었습니다."), + COMMENT_DETAIL_NOT_FOUND(HttpStatus.NOT_FOUND, false, 12004, "존재하지 않는 댓글 내용입니다."), + POST_COMMENT_NOT_FOUND(HttpStatus.NOT_FOUND, false, 12005, "존재하지 않는 게시글 댓글입니다."), + CANNOT_DELETE_COMMENT(HttpStatus.BAD_REQUEST, false, 12006, "본인의 댓글만 삭제할 수 있습니다."), + CANNOT_COMMENT_ON_POST(HttpStatus.BAD_REQUEST, false, 12007, "댓글을 작성할 수 있는 게시물이 아닙니다."), + CANNOT_UPDATE_COMMENT(HttpStatus.BAD_REQUEST, false, 12008, "본인의 댓글만 수정할 수 있습니다."), + POST_RE_COMMENT_NOT_FOUND(HttpStatus.NOT_FOUND, false, 12009, "존재하지 않는 게시글 대댓글입니다."), + CANNOT_RE_COMMENT_ON_POST(HttpStatus.BAD_REQUEST, false, 12010, "대댓글을 작성할 수 있는 게시물이 아닙니다."), + CANNOT_DELETE_RE_COMMENT(HttpStatus.BAD_REQUEST, false, 12011, "본인의 대댓글만 삭제할 수 있습니다."), + CANNOT_UPDATE_RE_COMMENT(HttpStatus.BAD_REQUEST, false, 12012, "본인의 대댓글만 수정할 수 있습니다."), + + /** + * 13,000: schedule service error + */ + NO_EXIST_SCHEDULE(HttpStatus.NOT_FOUND, false, 13001, "존재하지 않는 일정표입니다."), + + /** + * 14,000: company service error + */ + NO_EXIST_COMPANY(HttpStatus.NOT_FOUND, false, 14001, "존재하지 않는 업체입니다."), + + /** + * 15,000: instructor service error + */ + NO_EXIST_INSTRUCTOR_TYPE(HttpStatus.NOT_FOUND, false, 15001, "존재하지 않는 강사 종류입니다."), + NO_EXIST_INSTRUCTOR(HttpStatus.NOT_FOUND, false, 15002, "존재하지 않는 강사입니다."), + ; + + private final HttpStatusCode httpStatusCode; + private final boolean isSuccess; + private final int code; + private String message; + + + // custom message를 사용 + public BaseResponseStatusInterface withMessage(String message) { + return new CustomBaseResponseStatus(this, message); + } + +} diff --git a/src/main/java/greenfirst/be/global/common/response/BaseResponseStatusInterface.java b/src/main/java/greenfirst/be/global/common/response/BaseResponseStatusInterface.java new file mode 100644 index 0000000..8387247 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/response/BaseResponseStatusInterface.java @@ -0,0 +1,14 @@ +package greenfirst.be.global.common.response; + + +import org.springframework.http.HttpStatusCode; + + +public interface BaseResponseStatusInterface { + + HttpStatusCode getHttpStatusCode(); + boolean isSuccess(); + int getCode(); + String getMessage(); + +} \ No newline at end of file diff --git a/src/main/java/greenfirst/be/global/common/response/CustomBaseResponseStatus.java b/src/main/java/greenfirst/be/global/common/response/CustomBaseResponseStatus.java new file mode 100644 index 0000000..64b4667 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/response/CustomBaseResponseStatus.java @@ -0,0 +1,49 @@ +package greenfirst.be.global.common.response; + + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatusCode; + + +/** + * Custom implementation of BaseResponseStatusInterface that wraps a BaseResponseStatus + * and provides a custom message. + */ +@Getter +@RequiredArgsConstructor +public class CustomBaseResponseStatus implements BaseResponseStatusInterface { + + private final BaseResponseStatus baseStatus; + private final String customMessage; + + + public static CustomBaseResponseStatus of(BaseResponseStatus baseStatus, String customMessage) { + return new CustomBaseResponseStatus(baseStatus, customMessage); + } + + + @Override + public HttpStatusCode getHttpStatusCode() { + return baseStatus.getHttpStatusCode(); + } + + + @Override + public boolean isSuccess() { + return baseStatus.isSuccess(); + } + + + @Override + public int getCode() { + return baseStatus.getCode(); + } + + + @Override + public String getMessage() { + return customMessage; + } + +} diff --git a/src/main/java/greenfirst/be/global/common/security/CustomUserDetails.java b/src/main/java/greenfirst/be/global/common/security/CustomUserDetails.java new file mode 100644 index 0000000..8d72fd3 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/security/CustomUserDetails.java @@ -0,0 +1,76 @@ +package greenfirst.be.global.common.security; + + +import greenfirst.be.global.common.enums.common.UserType; +import lombok.Getter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import unionclass.campus7xhpeuser.user.domain.model.Users; + +import java.util.Collection; +import java.util.List; +import java.util.UUID; + + +@Getter +public class CustomUserDetails implements UserDetails { + + private UUID userUuid; + private String password; + private String userEmail; + private UserType userType; + + + public CustomUserDetails(Users user) { + this.userUuid = user.getUserUuid(); + this.password = user.getUserPassword(); + this.userEmail = user.getUserEmail(); + this.userType = user.getUserType(); + } + + + @Override + public Collection getAuthorities() { + String role = userType.getCode(); + return List.of(new SimpleGrantedAuthority(role)); + } + + + @Override + public String getPassword() { + return this.password; + } + + + @Override + public String getUsername() { + // token에 userUUID를 넘겨주기 위해, userUUID를 return + return this.userUuid.toString(); + } + + + @Override + public boolean isAccountNonExpired() { + return true; + } + + + @Override + public boolean isAccountNonLocked() { + return true; + } + + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + + @Override + public boolean isEnabled() { + return true; + } + +} \ No newline at end of file diff --git a/src/main/java/greenfirst/be/global/common/security/CustomUserDetailsService.java b/src/main/java/greenfirst/be/global/common/security/CustomUserDetailsService.java new file mode 100644 index 0000000..7b48a38 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/security/CustomUserDetailsService.java @@ -0,0 +1,45 @@ +package greenfirst.be.global.common.security; + + +import greenfirst.be.global.common.exception.BaseException; +import greenfirst.be.global.common.response.BaseResponseStatus; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.stereotype.Service; + +import java.util.UUID; + + +@Service +@RequiredArgsConstructor +public class CustomUserDetailsService implements UserDetailsService { + + private final UserRepository userRepository; + private final HttpServletRequest request; + + + // 인증을 위해 uuid로 UserDetails를 조회 + @Override + public UserDetails loadUserByUsername(String uuidString) { + // uuid + UUID uuid = UUID.fromString(uuidString); + // request url에 따라 admin인지 user인지 구분 + String requestURI = request.getRequestURI(); + if (requestURI.startsWith("/api/v1/user")) { + return this.getUserDetails(uuid); + } else { + return this.getAdminDetails(uuid); + } + } + + + // UserDetails 조회 + public CustomUserDetails getUserDetails(UUID userUuid) { + Users user = userRepository.findByUserUuid(userUuid).orElseThrow(() -> new BaseException(BaseResponseStatus.NO_EXIST_USER)); + return new CustomUserDetails(user); + } + +} + diff --git a/src/main/java/greenfirst/be/global/common/security/jwt/JwtAuthenticationFilter.java b/src/main/java/greenfirst/be/global/common/security/jwt/JwtAuthenticationFilter.java new file mode 100644 index 0000000..f97a512 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/security/jwt/JwtAuthenticationFilter.java @@ -0,0 +1,119 @@ +package greenfirst.be.global.common.security.jwt; + + +import greenfirst.be.global.common.security.CustomUserDetails; +import greenfirst.be.global.common.wrapper.CachingRequestWrapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.UUID; + + +@Component +@RequiredArgsConstructor +@Slf4j +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + // 필터 과정 + private final JwtTokenProvider jwtTokenProvider; + private final UserManagementService userManagementService; + + + /** + * 1. jwt 토큰 유효성 검사 및 인증 정보 저장 로직 + * 2. 헤더 검사 + * 3. 유효성 검사 & 토큰에서 사용자 UUID 추출 + * 4. ContextHolder에 유저 정보 저장 + * 5. 유저 권한 확인 + */ + + // 1. jwt 토큰 유효성 검사 및 인증 정보 저장 로직 + @Override + protected void doFilterInternal( + @NonNull + HttpServletRequest request, + @NonNull + HttpServletResponse response, + @NonNull + FilterChain filterChain + + ) throws ServletException, IOException { + // 요청을 CachingRequestWrapper로 감싸서, 여러번 요청을 받아도 문제가 없도록 함 + CachingRequestWrapper requestWrapper = new CachingRequestWrapper(request); + // 각종 변수 설정 + final String authHeader = requestWrapper.getHeader("Authorization"); // HTTP 요청 헤더에서 "Authorization" 값을 가져옴 + + /** + * 토큰 유효성 검사 및 인증 정보 저장 로직 + * 1-1. 헤더가 null이거나, "Bearer"로 시작하지 않는다면 pass + * 1-2. user 요청이 아닌 경우 pass + * 2. 유효성 검사 & JWT 토큰에서 사용자 email을 가져옴 + * 3. 중복되지 않았다면 ContextHolder에 유저 정보를 담음 (여기선 userUuid가 담김) + * 4. ContextHolder에 유저 정보를 저장 후, 다음 필터로 요청과 응답을 전달 + */ + + // 1-1. 헤더가 null이거나, "Bearer"로 시작하지 않는다면 pass + if (!this.checkHeader(authHeader)) { + filterChain.doFilter(requestWrapper, response); + return; + } + + // 1-2. user 요청이 아닌 경우 pass + if (!requestWrapper.getRequestURI().startsWith("/api/v1/user")) { + filterChain.doFilter(request, response); + return; + } + + // 2. 유효성 검사 & JWT 토큰에서 사용자 email을 가져옴 + String userUuidString = this.validateAndExtractUuid(authHeader); + UUID userUuid = UUID.fromString(userUuidString); + + // 3. 중복되지 않았다면 ContextHolder에 유저 정보를 담음 (여기선 userUuid가 담김) + this.setUserDataToSecurityContextHolder(userUuid, requestWrapper); + + // ContextHolder에 유저 정보를 저장 후, 다음 필터로 요청과 응답을 전달 + filterChain.doFilter(requestWrapper, response); + } + + + // 2. 헤더 검사 + private boolean checkHeader(String authHeader) { + return authHeader != null && authHeader.startsWith("Bearer "); + } + + + // 3. 유효성 검사 & 토큰에서 사용자 UUID 추출 + private String validateAndExtractUuid(String authHeader) { + return jwtTokenProvider.validateAndGetUserUuid(authHeader.substring(7)); + } + + + // 4. ContextHolder에 유저 정보 저장 + private void setUserDataToSecurityContextHolder(UUID userUuid, CachingRequestWrapper requestWrapper) { + // userEmail 기반으로 사용자 정보를 가져옴 + UserDetails userDetails = new CustomUserDetails(userManagementService.findByUserUuid(userUuid)); + // 인증 정보를 생성하고 Security Context에 유저 정보를 설정 -> (principal, credentials, authorities) 순서로 들어감 + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + userDetails, + null, + userDetails.getAuthorities()); + // 현재 요청에 대한 세부 정보를 인증 토큰에 설정 + authenticationToken.setDetails( + new WebAuthenticationDetailsSource().buildDetails(requestWrapper)); + // 인증 토큰을 Security Context에 설정 + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + } + +} \ No newline at end of file diff --git a/src/main/java/greenfirst/be/global/common/security/jwt/JwtTokenProvider.java b/src/main/java/greenfirst/be/global/common/security/jwt/JwtTokenProvider.java new file mode 100644 index 0000000..caab4a4 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/security/jwt/JwtTokenProvider.java @@ -0,0 +1,142 @@ +package greenfirst.be.global.common.security.jwt; + + +import greenfirst.be.global.common.exception.BaseException; +import greenfirst.be.global.common.response.BaseResponseStatus; +import io.jsonwebtoken.*; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Service; + +import java.security.Key; +import java.util.Date; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + + +@Slf4j +@Service +@RequiredArgsConstructor +public class JwtTokenProvider { + + @Value("${JWT.secret-key}") + private String secretKey; + + @Value("${JWT.token.access-expiration-time}") + private long accessExpirationTime; + + /** + * TokenProvider + * 1. 토큰에서 uuid 가져오기 + * 2. Claims에서 원하는 claim 값 추출 + * 3. 토큰에서 모든 claims 추출 + * 4. 액세스 토큰 생성 + */ + + /** + * 1. 토큰에서 uuid 가져오기 + * + * @param token + * @return jwt토큰에서 추출한 사용자 UUID 반환 + * 토큰에서 추출한 클레임에서 사용자 UUID를 추출하여 반환합니다. + */ + public String validateAndGetUserUuid(String token) throws BaseException { + try { + return extractClaim(token, Claims::getSubject); + } catch (NullPointerException e) { + log.info("토큰에 담긴 유저 정보가 없습니다"); + throw new BaseException(BaseResponseStatus.WRONG_JWT_TOKEN); + } + } + + + /** + * 2. Claims에서 원하는 claim 값 추출 + * + * @param token + * @param claimsResolver jwt토큰에서 추출한 정보를 어떻게 처리할지 결정하는 함수 + * @return jwt토큰에서 모든 클레임(클레임은 토큰에 담긴 정보 의미 ) 추출한 다음 claimsResolver함수를 처리해 결과 반환 + */ + public T extractClaim(String token, Function claimsResolver) { + Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + + /** + * 3. 토큰에서 모든 claims 추출 + * + * @param token 주어진 JWT 토큰에서 모든 클레임을 추출하여 반환합니다. + * 토큰의 서명을 확인하기 위해 사용할 서명 키(getSigningKey())를 설정하고 토큰을 파싱하여 클레임들을 추출합니다. + */ + private Claims extractAllClaims(String token) { + try { + return Jwts + .parserBuilder() + .setSigningKey(getSigningKey()) + .build() + .parseClaimsJws(token) // 이 단계에서 token의 유효성 검사 및 만료일 검사를 실시한다! + .getBody(); + } + // 파싱 예외 처리 + catch (ExpiredJwtException e) { + log.error("만료된 토큰입니다"); + throw new BaseException(BaseResponseStatus.WRONG_JWT_TOKEN); + } catch (UnsupportedJwtException e) { + log.error("지원되지 않는 유형의 토큰입니다"); + throw new BaseException(BaseResponseStatus.WRONG_JWT_TOKEN); + } catch (MalformedJwtException | IllegalArgumentException e) { + log.error("잘못된 토큰입니다"); + throw new BaseException(BaseResponseStatus.WRONG_JWT_TOKEN); + } catch (io.jsonwebtoken.security.SignatureException e) { + log.error("SecretKey가 일치하지 않습니다"); + throw new BaseException(BaseResponseStatus.WRONG_JWT_TOKEN); + } + } + + + /** + * 4. 액세스 토큰 생성 + * + * @param userDetails 사용자 정보 + * @return 클레임 정보와 사용자 정보를 기반으로 jwt 토큰 생성 + * 클레임 정보, 사용자 ID, 생성 시간, 만료 시간 등을 설정하고, 서명 알고리즘과 서명 키를 사용하여 토큰을 생성합니다. + * Access Token 역활 + */ + public String generateToken(UserDetails userDetails) { + return generateToken(Map.of(), userDetails); + } + + + public String generateToken(Map extractClaims, UserDetails userDetails) { + return buildToken(extractClaims, userDetails, accessExpirationTime); + } + + + // 토큰 생성 + public String buildToken( + Map extractClaims, + UserDetails userDetails, + long expiration) { + return Jwts.builder() + .setClaims(extractClaims) + .setSubject(userDetails.getUsername()) // uuid를 subject로 설정 + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + expiration)) + .signWith(getSigningKey(), SignatureAlgorithm.HS256) + .compact(); + } + + + // 3개로 이루어진 키값을 풀기위한 메소드 + private Key getSigningKey() { + byte[] keyBytes = Decoders.BASE64.decode(secretKey); + return Keys.hmacShaKeyFor(keyBytes); + } + +} diff --git a/src/main/java/greenfirst/be/global/common/slack/NotificationColor.java b/src/main/java/greenfirst/be/global/common/slack/NotificationColor.java new file mode 100644 index 0000000..42cd7ef --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/slack/NotificationColor.java @@ -0,0 +1,17 @@ +package greenfirst.be.global.common.slack; + + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + + +@Getter +@RequiredArgsConstructor +public enum NotificationColor { + + RED("#FF0000"), + ; + + private final String code; + +} diff --git a/src/main/java/greenfirst/be/global/common/slack/SlackEvent.java b/src/main/java/greenfirst/be/global/common/slack/SlackEvent.java new file mode 100644 index 0000000..2c0a580 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/slack/SlackEvent.java @@ -0,0 +1,15 @@ +package greenfirst.be.global.common.slack; + + +import lombok.AllArgsConstructor; +import lombok.Getter; + + +@Getter +@AllArgsConstructor +public class SlackEvent { + + private String title; + private String data; + +} diff --git a/src/main/java/greenfirst/be/global/common/slack/SlackMessageSender.java b/src/main/java/greenfirst/be/global/common/slack/SlackMessageSender.java new file mode 100644 index 0000000..4e6d9d1 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/slack/SlackMessageSender.java @@ -0,0 +1,70 @@ +package greenfirst.be.global.common.slack; + + +import com.slack.api.Slack; +import com.slack.api.model.Attachment; +import com.slack.api.model.Field; +import com.slack.api.webhook.Payload; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import unionclass.campus7xhpeuser.global.common.exception.BaseException; +import unionclass.campus7xhpeuser.global.common.response.BaseResponseStatus; + +import java.util.List; + +import static com.slack.api.webhook.WebhookPayloads.payload; + + +@Service +public class SlackMessageSender { + + private final Slack slackClient = Slack.getInstance(); + @Value("${webhook.slack.url}") + private String SLACK_WEBHOOK_URL; + + + /** + * SlackService + * 1. Slack 메시지 전송 + * 2. payload 생성 + * 3. slack field 생성 + */ + + // 1. Slack 메시지 전송 + public void sendMessage(String title, String data) { + try { + slackClient.send(SLACK_WEBHOOK_URL, this.createPayload(title, data)); + } catch (Exception e) { + throw new BaseException(BaseResponseStatus.SLACK_SEND_MESSAGE_ERROR); + } + } + + + // 2. payload 생성 + private Payload createPayload(String title, String data) { + return payload(p -> p + .text(title) // 메시지 제목 + .attachments( + List.of( + Attachment.builder() + // 알림 색상 + .color(NotificationColor.RED.getCode()) + // 메시지 본문 내용 + .fields(List.of(generateField("Error Details", data))) + .build() + ) + ) + ); + } + + + // 3. slack field 생성 + private Field generateField(String title, String value) { + return Field.builder() + .title(title) + .value(value) + .valueShortEnough(false) + .build(); + } + +} diff --git a/src/main/java/greenfirst/be/global/common/timezone/TimeZoneController.java b/src/main/java/greenfirst/be/global/common/timezone/TimeZoneController.java new file mode 100644 index 0000000..93f6690 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/timezone/TimeZoneController.java @@ -0,0 +1,47 @@ +package greenfirst.be.global.common.timezone; + + +import io.swagger.v3.oas.annotations.Operation; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; + + +@RestController +@RequestMapping("/api/v1/common/timezone") +public class TimeZoneController { + + @Operation(summary = "시스템 시간대 확인", description = "시스템의 시간대와 현재 시간을 확인합니다.") + @GetMapping + public Map checkTimeZone() { + Map info = new HashMap<>(); + + // 시스템 시간대 + TimeZone defaultTz = TimeZone.getDefault(); + info.put("systemTimeZone", defaultTz.getID()); + info.put("systemTimeZoneDisplayName", defaultTz.getDisplayName()); + + // 현재 시간 (여러 형식으로) + LocalDateTime localNow = LocalDateTime.now(); + ZonedDateTime zonedNow = ZonedDateTime.now(); + Instant instantNow = Instant.now(); + + info.put("localDateTime", localNow.toString()); + info.put("zonedDateTime", zonedNow.toString()); + info.put("instant", instantNow.toString()); + + // ZoneId 정보 + info.put("zoneId", ZoneId.systemDefault().toString()); + + return info; + } + +} \ No newline at end of file diff --git a/src/main/java/greenfirst/be/global/common/util/CustomUuidGenerator.java b/src/main/java/greenfirst/be/global/common/util/CustomUuidGenerator.java new file mode 100644 index 0000000..83647f3 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/util/CustomUuidGenerator.java @@ -0,0 +1,11 @@ +package greenfirst.be.global.common.util; + + +import java.util.UUID; + + +public interface CustomUuidGenerator { + + UUID generateUuid(); + +} diff --git a/src/main/java/greenfirst/be/global/common/util/UuidGeneratorImpl.java b/src/main/java/greenfirst/be/global/common/util/UuidGeneratorImpl.java new file mode 100644 index 0000000..8875c42 --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/util/UuidGeneratorImpl.java @@ -0,0 +1,17 @@ +package greenfirst.be.global.common.util; + + +import org.springframework.stereotype.Component; + +import java.util.UUID; + + +@Component +public class UuidGeneratorImpl implements CustomUuidGenerator { + + @Override + public UUID generateUuid() { + return UUID.randomUUID(); + } + +} diff --git a/src/main/java/greenfirst/be/global/common/wrapper/CachingRequestWrapper.java b/src/main/java/greenfirst/be/global/common/wrapper/CachingRequestWrapper.java new file mode 100644 index 0000000..e71b88f --- /dev/null +++ b/src/main/java/greenfirst/be/global/common/wrapper/CachingRequestWrapper.java @@ -0,0 +1,91 @@ +package greenfirst.be.global.common.wrapper; + + +import greenfirst.be.global.common.exception.BaseException; +import greenfirst.be.global.common.response.BaseResponseStatus; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.IOUtils; +import org.springframework.util.StringUtils; + +import java.io.*; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + + +@Slf4j +public class CachingRequestWrapper extends HttpServletRequestWrapper { + + private final Charset encoding; + private byte[] rawData; + + + public CachingRequestWrapper(HttpServletRequest request) { + super(request); + + String characterEncoding = request.getCharacterEncoding(); + if (StringUtils.isEmpty(characterEncoding)) { + characterEncoding = StandardCharsets.UTF_8.name(); + } + this.encoding = Charset.forName(characterEncoding); + + try (InputStream inputStream = request.getInputStream()) { + this.rawData = IOUtils.toByteArray(inputStream); + } catch (IOException e) { + log.error("CachingRequestWrapper Error: {}", e.getMessage()); + throw new BaseException(BaseResponseStatus.LOGGING_ERROR); + } + } + + + @Override + public ServletInputStream getInputStream() { + return new CachedServletInputStream(this.rawData); + } + + + @Override + public BufferedReader getReader() { + return new BufferedReader(new InputStreamReader(this.getInputStream(), this.encoding)); + } + + + private static class CachedServletInputStream extends ServletInputStream { + + private final ByteArrayInputStream buffer; + + + public CachedServletInputStream(byte[] contents) { + this.buffer = new ByteArrayInputStream(contents); + } + + + @Override + public int read() throws IOException { + return buffer.read(); + } + + + @Override + public boolean isFinished() { + return buffer.available() == 0; + } + + + @Override + public boolean isReady() { + return true; + } + + + @Override + public void setReadListener(ReadListener listener) { + throw new UnsupportedOperationException("not support"); + } + + } + +} diff --git a/src/main/java/greenfirst/be/global/config/application/SecurityAppConfig.java b/src/main/java/greenfirst/be/global/config/application/SecurityAppConfig.java new file mode 100644 index 0000000..cd07fa4 --- /dev/null +++ b/src/main/java/greenfirst/be/global/config/application/SecurityAppConfig.java @@ -0,0 +1,54 @@ +package greenfirst.be.global.config.application; + + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + + +@Configuration +@RequiredArgsConstructor +public class SecurityAppConfig { + + private final UserDetailsService userDetailsService; + + + /** + * Security Config + * - passwordEncoder: BCrypt 방식의 비밀번호 인코더 사용 + * - AuthenticationProvider: Dao Provider와 customUserDetailsService를 사용 + * - AuthenticationManager: 인증을 진행할 AuthenticationManager를 Bean으로 등록 + */ + + // 비밀번호 인코더를 제공. 여기서는 BCrypt 방식의 비밀번호 인코딩 사용 + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + + // AuthenticationProvider: 인증을 처리하는데 사용하는 authenticationProvider를 생성한다. + // DaoAuthenticationProvider는 가장 일반적인 인증 제공자 형태로, UserDetailsService에서 제공받은 사용자 이름과 비밀번호를 기반으로 인증을 수행한다 + @Bean + public AuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); // DAO 기반의 인증 제공자 생성 + authenticationProvider.setUserDetailsService(userDetailsService); // 사용자의 세부 정보 서비스 설정 + authenticationProvider.setPasswordEncoder(passwordEncoder()); // 비밀번호 인코더 설정 + return authenticationProvider; + } + + + // AuthenticationManager: 인증을 진행할 AuthenticationManager를 Bean으로 등록 + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { + return authenticationConfiguration.getAuthenticationManager(); // 기본 인증 관리자를 가져옴 + } + +} diff --git a/src/main/java/greenfirst/be/global/config/application/WebMvcConfig.java b/src/main/java/greenfirst/be/global/config/application/WebMvcConfig.java new file mode 100644 index 0000000..1b7245a --- /dev/null +++ b/src/main/java/greenfirst/be/global/config/application/WebMvcConfig.java @@ -0,0 +1,20 @@ +package greenfirst.be.global.config.application; + + +import greenfirst.be.global.common.interceptor.ApiLogInterceptor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + @Override + public void addInterceptors(InterceptorRegistry registry) { + // api 로그 인터셉터 등록 + registry.addInterceptor(new ApiLogInterceptor()) + .addPathPatterns("/api/v1/**"); + } + +} diff --git a/src/main/java/greenfirst/be/global/config/mapper/modelmapper/ModelMapperConfig.java b/src/main/java/greenfirst/be/global/config/mapper/modelmapper/ModelMapperConfig.java new file mode 100644 index 0000000..bff0371 --- /dev/null +++ b/src/main/java/greenfirst/be/global/config/mapper/modelmapper/ModelMapperConfig.java @@ -0,0 +1,23 @@ +package greenfirst.be.global.config.mapper.modelmapper; + + +import org.modelmapper.ModelMapper; +import org.modelmapper.convention.MatchingStrategies; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +public class ModelMapperConfig { + + @Bean(name = "modelMapper") + public ModelMapper modelMapper() { + ModelMapper modelMapper = new ModelMapper(); + modelMapper.getConfiguration() + .setFieldAccessLevel(org.modelmapper.config.Configuration.AccessLevel.PRIVATE) // private 필드에도 접근하여 매핑할 수 있도록 허용합니다. + .setMatchingStrategy(MatchingStrategies.STRICT) // 필드명이 완전히 일치하는 경우에만 매핑을 수행 + .setFieldMatchingEnabled(true); // 사용하지 않으면 매핑이 안됨 + return modelMapper; + } + +} \ No newline at end of file diff --git a/src/main/java/greenfirst/be/global/config/querydsl/QueryDslConfig.java b/src/main/java/greenfirst/be/global/config/querydsl/QueryDslConfig.java new file mode 100644 index 0000000..98bc3f8 --- /dev/null +++ b/src/main/java/greenfirst/be/global/config/querydsl/QueryDslConfig.java @@ -0,0 +1,24 @@ +package greenfirst.be.global.config.querydsl; + + +import com.querydsl.jpa.JPQLTemplates; +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +@RequiredArgsConstructor +public class QueryDslConfig { + + private final EntityManager em; + + + @Bean + public JPAQueryFactory jpaQueryFactory() { + return new JPAQueryFactory(JPQLTemplates.DEFAULT, em); + } + +} diff --git a/src/main/java/greenfirst/be/global/config/sercurity/CorsOriginDto.java b/src/main/java/greenfirst/be/global/config/sercurity/CorsOriginDto.java new file mode 100644 index 0000000..1bfdb9d --- /dev/null +++ b/src/main/java/greenfirst/be/global/config/sercurity/CorsOriginDto.java @@ -0,0 +1,25 @@ +package greenfirst.be.global.config.sercurity; + + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.util.List; + + +@Getter +@Setter +@Component +@ConfigurationProperties(prefix = "origins") +public class CorsOriginDto { + + // origins: 허용할 도메인 or ip주소 + private List DEVELOPMENT_CLIENT_LOCAL; + private List DEVELOPMENT_CLIENT_DOCKER; + private List DEVELOPMENT_CLIENT_DOMAIN; + private List PRODUCTION_CLIENT_DOCKER; + private List PRODUCTION_CLIENT_DOMAIN; + +} diff --git a/src/main/java/greenfirst/be/global/config/sercurity/CustomCorsConfig.java b/src/main/java/greenfirst/be/global/config/sercurity/CustomCorsConfig.java new file mode 100644 index 0000000..3ae99a6 --- /dev/null +++ b/src/main/java/greenfirst/be/global/config/sercurity/CustomCorsConfig.java @@ -0,0 +1,59 @@ +package greenfirst.be.global.config.sercurity; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +import java.util.List; +import java.util.stream.Stream; + + +@Configuration +public class CustomCorsConfig { + + // origins: 허용할 도메인 or ip주소 + private final CorsOriginDto corsOriginDto; + + + @Autowired + public CustomCorsConfig(CorsOriginDto corsOriginDto) { + this.corsOriginDto = corsOriginDto; + } + + + @Bean + public CorsConfigurationSource corsConfigurationSource() { + // 허용할 도메인 or ip주소 + List ALLOWED_ORIGINS = Stream.of( + corsOriginDto.getDEVELOPMENT_CLIENT_LOCAL(), + corsOriginDto.getDEVELOPMENT_CLIENT_DOCKER(), + corsOriginDto.getDEVELOPMENT_CLIENT_DOMAIN(), + corsOriginDto.getPRODUCTION_CLIENT_DOCKER(), + corsOriginDto.getPRODUCTION_CLIENT_DOMAIN() + ).flatMap(List::stream).toList(); + + // CorsConfig (maxAge는 default로 30분, maxAge: preflight 요청 결과를 캐싱할 시간) + CorsConfiguration config = new CorsConfiguration(); + config.addAllowedMethod("*"); + config.addAllowedHeader("*"); + config.setAllowCredentials(true); + config.setAllowedOriginPatterns(ALLOWED_ORIGINS); + + // URL 별로 다른 설정을 적용할 수 있도록 UrlBasedCorsConfigurationSource를 사용 + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", config); // 모든 url에 대해 적용, origin으로 제어 + return source; + } + + + @Bean + public CorsFilter corsFilter() { + return new CorsFilter(corsConfigurationSource()); + } + +} diff --git a/src/main/java/greenfirst/be/global/config/sercurity/UserSecurityConfig.java b/src/main/java/greenfirst/be/global/config/sercurity/UserSecurityConfig.java new file mode 100644 index 0000000..0cdcf98 --- /dev/null +++ b/src/main/java/greenfirst/be/global/config/sercurity/UserSecurityConfig.java @@ -0,0 +1,144 @@ +package greenfirst.be.global.config.sercurity; + + +import greenfirst.be.global.common.exception.BaseExceptionHandlerFilter; +import greenfirst.be.global.common.security.jwt.JwtAuthenticationFilter; +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.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.intercept.AuthorizationFilter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; +import org.springframework.web.cors.CorsUtils; + + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class UserSecurityConfig { + + // HTTP METHOD + private static final String GET = HttpMethod.GET.name(); + private static final String POST = HttpMethod.POST.name(); + private static final String PUT = HttpMethod.PUT.name(); + private static final String PATCH = HttpMethod.PATCH.name(); + private static final String DELETE = HttpMethod.DELETE.name(); + + // 허용할 url 배열 + private static final String[] commonUrl = new String[] { + "/swagger-ui/**", // 스웨거 + "/swagger-resources/**",// 스웨거 + "/v3/api-docs/**", // 스웨거 + "/api-docs/**", // 스웨거 + "/error" // 에러 페이지 + }; + + // auth + private static final RequestMatcher[] authUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/signup", POST), // 회원가입 + new AntPathRequestMatcher("/api/v1/user/signin", POST), // 로그인 + new AntPathRequestMatcher("/api/v1/user/email/auth", POST), // 이메일 인증 요청 + new AntPathRequestMatcher("/api/v1/user/email/verify/auth-code", GET), // 이메일 인증 코드 확인 + new AntPathRequestMatcher("/api/v1/user/email/find-id", POST), // 아이디 찾기 + new AntPathRequestMatcher("/api/v1/user/email/temp-password", POST), // 비밀번호 확인 + }; + + // user + private static final RequestMatcher[] userUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/", GET), // 조회 + }; + + // category + private static final RequestMatcher[] categoryUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/category/list", GET), // 카테고리 리스트 조회 + }; + + // course + private static final RequestMatcher[] courseUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/course/**/list", GET), // 교육과정 리스트 조회 + new AntPathRequestMatcher("/api/v1/user/course/cohort/**/detail", GET), // 교육과정 기수 상세조회 + new AntPathRequestMatcher("/api/v1/user/course/cohort/**/unit/list", GET), // 기수 단원정보 리스트 조회 + new AntPathRequestMatcher("/api/v1/user/course/type/list", GET), // 과정타입 리스트 조회 + }; + + // board + private static final RequestMatcher[] boardUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/board/list", GET), // 게시판 리스트 조회 + new AntPathRequestMatcher("/api/v1/user/board/**", GET), // 게시판 상세조회 + }; + + // post + private static final RequestMatcher[] postUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/post/list", GET), // 게시글 리스트 조회 + new AntPathRequestMatcher("/api/v1/user/post/**", GET), // 게시글 상세조회 + }; + + // schedule + private static final RequestMatcher[] scheduleUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/schedule/vendor/**/all", GET), // 벤더사별 일정표 전체 조회 + }; + + // comment + private static final RequestMatcher[] commentUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/comment/{postId}", GET), // 댓글 조회 + new AntPathRequestMatcher("/api/v1/user/recomment/**", GET), // 대댓글 조회 + }; + + // company + private static final RequestMatcher[] companyUrl = new RequestMatcher[] { + new AntPathRequestMatcher("/api/v1/user/company/all", GET), // 업체 전체 조회 + }; + + // security + private final CustomCorsConfig customCorsConfig; + private final JwtAuthenticationFilter jwtAuthenticationFilter; + private final BaseExceptionHandlerFilter baseExceptionHandlerFilter; + + + // securityFilterChain + @Bean + public SecurityFilterChain userSecurityFilterChain(HttpSecurity http) throws Exception { + http + // Restful API를 사용하므로, csrf는 사용할 필요가 없다 + .csrf(CsrfConfigurer::disable) + // cors + .cors(cors -> cors.configurationSource(customCorsConfig.corsConfigurationSource())) + // 토큰 방식을 사용하므로, 서버에서 session을 관리하지 않음. 따라서 STATELESS로 설정 + .sessionManagement(sessionManagement -> + sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + // FilterSecurityInterceptor에서 사용 -> 인증 절차에 대한 설정을 시작 : 필터를 적용시키지 않을 url과, 적용시킬 url을 구분 + .authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests + // 예비 요청을 허용 + .requestMatchers(CorsUtils::isPreFlightRequest) + .permitAll() + // 로그인 없이 허용할 url + .requestMatchers(courseUrl).permitAll() + .requestMatchers(categoryUrl).permitAll() + .requestMatchers(userUrl).permitAll() + .requestMatchers(authUrl).permitAll() + .requestMatchers(boardUrl).permitAll() + .requestMatchers(postUrl).permitAll() + .requestMatchers(scheduleUrl).permitAll() + .requestMatchers(commentUrl).permitAll() + .requestMatchers(companyUrl).permitAll() + .requestMatchers(commonUrl).permitAll() // 공통 url + .requestMatchers("/api/v1/user/test/**").permitAll() // 테스트 url + // 이외의 url은 허용하지 않음 + .anyRequest().authenticated()) + // 폼 로그인 사용 안함 + .formLogin(AbstractHttpConfigurer::disable) + // filter단에서 발생하는 에러를 처리할 ExceptionHandlerFilter를 인증필터 바로 앞에 위치시킨다(예외 전파는 역순으로 전파되므로, 맨앞에 위치시키면 안됨) + .addFilterBefore(baseExceptionHandlerFilter, AuthorizationFilter.class) + // JWT 인증 필터를 AuthorizationFilter 전에 추가 + .addFilterBefore(jwtAuthenticationFilter, AuthorizationFilter.class); + return http.build(); + } + +} \ No newline at end of file diff --git a/src/main/java/greenfirst/be/global/config/swagger/SwaggerConfig.java b/src/main/java/greenfirst/be/global/config/swagger/SwaggerConfig.java new file mode 100644 index 0000000..7762e87 --- /dev/null +++ b/src/main/java/greenfirst/be/global/config/swagger/SwaggerConfig.java @@ -0,0 +1,64 @@ +package greenfirst.be.global.config.swagger; + + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import io.swagger.v3.oas.models.tags.Tag; +import org.springdoc.core.models.GroupedOpenApi; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import java.util.List; + + +@OpenAPIDefinition( + info = @io.swagger.v3.oas.annotations.info.Info( + title = "GreenFirst Service API", + version = "v1", + description = "SSO API Docs" + ) +) + +@SecurityScheme( + name = "Bearer Auth", + type = SecuritySchemeType.HTTP, + bearerFormat = "JWT", + scheme = "bearer" +) + +@Profile("!prod") +@Configuration +public class SwaggerConfig { + + // 유저 API 그룹 + @Bean + public GroupedOpenApi userGroup() { + // api 경로 + String[] paths = { "/api/v1/user/**" }; + // 사용하는 태그 + List tags = List.of( + new Tag().name("Course - user"), + new Tag().name("Category - user"), + new Tag().name("Auth - user"), + new Tag().name("Banner - user"), + new Tag().name("Email - user"), + new Tag().name("User - user"), + new Tag().name("Payment - user"), + new Tag().name("Vendor - user"), + new Tag().name("Unit - user"), + new Tag().name("Session - user"), + new Tag().name("Cohort - user"), + new Tag().name("Attendee - user"), + new Tag().name("Post - user"), + new Tag().name("Instructor - user") + ); + return GroupedOpenApi.builder() + .group("user-api") + .pathsToMatch(paths) + .addOpenApiCustomizer(openApi -> openApi.setTags(tags)) + .build(); + } + +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..fc31704 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,19 @@ +spring: + application: + name: greenfirst-be + profiles: + default: local + +# swagger 설정 +springdoc: + swagger-ui: + path: /swagger-ui.html + groups-order: DESC + operationsSorter: method + disable-swagger-default-url: true + display-request-duration: true + api-docs: + path: /api-docs + show-actuator: true + default-consumes-media-type: application/json + default-produces-media-type: application/json \ No newline at end of file diff --git a/src/test/java/greenfirst/be/GreenfirstBeApplicationTests.java b/src/test/java/greenfirst/be/GreenfirstBeApplicationTests.java new file mode 100644 index 0000000..2419abb --- /dev/null +++ b/src/test/java/greenfirst/be/GreenfirstBeApplicationTests.java @@ -0,0 +1,15 @@ +package greenfirst.be; + + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + + +@SpringBootTest +class GreenfirstBeApplicationTests { + + @Test + void contextLoads() { + } + +}