diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..10e588e --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,60 @@ +name: deploy-actions + +on: + push: + branches: [ "main" ] + +jobs: + ci: + runs-on: ubuntu-20.04 + + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + token: ${{ secrets.GIT_TOKEN }} + submodules: true + + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Build with Gradle + run: ./gradlew clean build -x test + + - name: Login to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + - name: Build and push + uses: docker/build-push-action@v4 + with: + context: . + file: ./Dockerfile + push: true + tags: ${{ secrets.DOCKERHUB_USERNAME }}/${{ secrets.DOCKERHUB_PROD_REPONAME }}:0.0.1 + + cd: + needs: [ci] + runs-on: ubuntu-20.04 + + steps: + - name: Connect Bastion Host And Run deploy.sh + uses: appleboy/ssh-action@v1.0.0 + with: + key: ${{ secrets.SSH_PRIVATE_KEY }} + host: ${{ secrets.SSH_HOST }} + username: ${{ secrets.SSH_USERNAME }} + port: ${{ 22 }} + script: | + sh /home/ubuntu/deploy/deploy.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b20a810 --- /dev/null +++ b/.gitignore @@ -0,0 +1,236 @@ +# Created by https://www.toptal.com/developers/gitignore/api/java,macos,intellij,gradle,windows +# Edit at https://www.toptal.com/developers/gitignore?templates=java,macos,intellij,gradle,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 + +# Credentials +src/main/resources/application-prod.yml +src/main/resources/application-local.yml + +.idea +HELP.md + +# 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 # +*.jar +*.war +*.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 + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/java,macos,intellij,gradle,windows diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..b35fee9 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "Choco-Express-BE-Properties"] + path = Choco-Express-BE-Properties + url = https://github.com/Choco-Express/Choco-Express-BE-Properties.git diff --git a/Choco-Express-BE-Properties b/Choco-Express-BE-Properties new file mode 160000 index 0000000..807f5e2 --- /dev/null +++ b/Choco-Express-BE-Properties @@ -0,0 +1 @@ +Subproject commit 807f5e2cc2dde893e891910cdd5a947c74111bc5 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..227469e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:17-alpine +ARG JAR_FILE=build/libs/*.jar +COPY ${JAR_FILE} app.jar +ENTRYPOINT ["java","-jar","/app.jar", "--spring.profiles.active=prod"] \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..8cd741c --- /dev/null +++ b/build.gradle @@ -0,0 +1,62 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.3' + id 'io.spring.dependency-management' version '1.1.6' +} + +group = 'dgu' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +repositories { + mavenCentral() +} + +dependencies { + //database + implementation 'org.springframework.boot:spring-boot-starter-data-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + runtimeOnly 'com.mysql:mysql-connector-j' + + // redis + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + + // spring security + implementation 'org.springframework.boot:spring-boot-starter-security' + testImplementation 'org.springframework.security:spring-security-test' + implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' + + // spring boot + implementation 'org.springframework.boot:spring-boot-starter-web' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + // jwt + implementation 'jakarta.xml.bind:jakarta.xml.bind-api:4.0.0' + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + + //json + implementation 'net.minidev:json-smart:2.4.7' +} + +task copyGitSubmodule(type: Copy) { + copy { + from './Choco-Express-BE-Properties' + include '*.yml' + into './src/main/resources' + } +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/deploy.sh b/deploy.sh new file mode 100644 index 0000000..5d06aad --- /dev/null +++ b/deploy.sh @@ -0,0 +1,4 @@ +#!/bin/bash +./gradlew clean build -x test +docker buildx build --platform linux/amd64 --load --tag jeongheumchoi/choco_express:0.0.1 . +docker push jeongheumchoi/choco_express:0.0.1 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 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..a441313 --- /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.8-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..b740cf1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 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=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..cf4dbeb --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'choco-express' diff --git a/src/main/java/dgu/choco_express/ChocoExpressApplication.java b/src/main/java/dgu/choco_express/ChocoExpressApplication.java new file mode 100644 index 0000000..f97302a --- /dev/null +++ b/src/main/java/dgu/choco_express/ChocoExpressApplication.java @@ -0,0 +1,13 @@ +package dgu.choco_express; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ChocoExpressApplication { + + public static void main(String[] args) { + SpringApplication.run(ChocoExpressApplication.class, args); + } + +} diff --git a/src/main/java/dgu/choco_express/annotation/UserId.java b/src/main/java/dgu/choco_express/annotation/UserId.java new file mode 100644 index 0000000..f046f8e --- /dev/null +++ b/src/main/java/dgu/choco_express/annotation/UserId.java @@ -0,0 +1,11 @@ +package dgu.choco_express.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface UserId { +} diff --git a/src/main/java/dgu/choco_express/config/JpaAuditingConfiguration.java b/src/main/java/dgu/choco_express/config/JpaAuditingConfiguration.java new file mode 100644 index 0000000..b0f38cb --- /dev/null +++ b/src/main/java/dgu/choco_express/config/JpaAuditingConfiguration.java @@ -0,0 +1,9 @@ +package dgu.choco_express.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@Configuration +@EnableJpaAuditing +public class JpaAuditingConfiguration { +} diff --git a/src/main/java/dgu/choco_express/config/WebConfig.java b/src/main/java/dgu/choco_express/config/WebConfig.java new file mode 100644 index 0000000..3ba329c --- /dev/null +++ b/src/main/java/dgu/choco_express/config/WebConfig.java @@ -0,0 +1,34 @@ +package dgu.choco_express.config; + +import dgu.choco_express.constant.Constants; +import dgu.choco_express.interceptor.pre.UserIdArgumentResolver; +import dgu.choco_express.interceptor.pre.UserIdInterceptor; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class WebConfig implements WebMvcConfigurer { + + private final UserIdArgumentResolver userIdArgumentResolver; + + @Override + public void addArgumentResolvers(List resolvers) { + WebMvcConfigurer.super.addArgumentResolvers(resolvers); + resolvers.add(this.userIdArgumentResolver); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new UserIdInterceptor()) + .addPathPatterns("/**") + .excludePathPatterns(Constants.NO_NEED_AUTH); + } +} diff --git a/src/main/java/dgu/choco_express/constant/Constants.java b/src/main/java/dgu/choco_express/constant/Constants.java new file mode 100644 index 0000000..0f29a30 --- /dev/null +++ b/src/main/java/dgu/choco_express/constant/Constants.java @@ -0,0 +1,18 @@ +package dgu.choco_express.constant; + +import java.util.List; + +public class Constants { + public static String CLAIM_USER_ID = "uuid"; + public static String CLAIM_USER_ROLE = "role"; + public static String PREFIX_BEARER = "Bearer "; + public static String PREFIX_AUTH = "authorization"; + public static String ACCESS_COOKIE_NAME = "access_token"; + public static String REFRESH_COOKIE_NAME = "refresh_token"; + public static List NO_NEED_AUTH = List.of( + "/api/health-check", + "/api/auth/sign-up", + "/api/auth/sign-in", + "/oauth2/authorization/kakao" + ); +} diff --git a/src/main/java/dgu/choco_express/controller/HealthCheckController.java b/src/main/java/dgu/choco_express/controller/HealthCheckController.java new file mode 100644 index 0000000..b513e78 --- /dev/null +++ b/src/main/java/dgu/choco_express/controller/HealthCheckController.java @@ -0,0 +1,18 @@ +package dgu.choco_express.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api") +public class HealthCheckController { + + @GetMapping("/health-check") + public ResponseEntity healthCheck() { + return ResponseEntity.ok().build(); + } +} diff --git a/src/main/java/dgu/choco_express/domain/global/BaseTimeEntity.java b/src/main/java/dgu/choco_express/domain/global/BaseTimeEntity.java new file mode 100644 index 0000000..ce44248 --- /dev/null +++ b/src/main/java/dgu/choco_express/domain/global/BaseTimeEntity.java @@ -0,0 +1,24 @@ +package dgu.choco_express.domain.global; + +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; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public class BaseTimeEntity { + @Column(name = "created_date", nullable = false, updatable = false) + @CreatedDate + private LocalDateTime createdDate; + + @Column(name = "modified_date") + @LastModifiedDate + private LocalDateTime modifiedDate; +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/domain/refreshToken/RefreshToken.java b/src/main/java/dgu/choco_express/domain/refreshToken/RefreshToken.java new file mode 100644 index 0000000..817b3ef --- /dev/null +++ b/src/main/java/dgu/choco_express/domain/refreshToken/RefreshToken.java @@ -0,0 +1,30 @@ +package dgu.choco_express.domain.refreshToken; + +import jakarta.persistence.Id; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.data.redis.core.RedisHash; +import org.springframework.data.redis.core.index.Indexed; + +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@RedisHash(value = "token", timeToLive = 60 * 60 * 24 * 14) +public class RefreshToken { + @Id + private Long id; + + @Indexed + private String token; + + @Builder + public RefreshToken(Long id, String token) { + this.id = id; + this.token = token; + } + + public static RefreshToken issueRefreshToken(final Long userId, final String refreshToken) { + return new RefreshToken(userId, refreshToken); + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/domain/user/EProvider.java b/src/main/java/dgu/choco_express/domain/user/EProvider.java new file mode 100644 index 0000000..c3b7b82 --- /dev/null +++ b/src/main/java/dgu/choco_express/domain/user/EProvider.java @@ -0,0 +1,14 @@ +package dgu.choco_express.domain.user; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public enum EProvider { + KAKAO("KAKAO"), + NAVER("NAVER"), + GOOGLE("GOOGLE"); + + private final String name; +} diff --git a/src/main/java/dgu/choco_express/domain/user/ERole.java b/src/main/java/dgu/choco_express/domain/user/ERole.java new file mode 100644 index 0000000..6e3713f --- /dev/null +++ b/src/main/java/dgu/choco_express/domain/user/ERole.java @@ -0,0 +1,15 @@ +package dgu.choco_express.domain.user; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public enum ERole { + GUEST("GUEST", "ROLE_GUEST"), + USER("USER", "ROLE_USER"), + ADMIN("ADMIN", "ROLE_ADMIN"); + + private final String role; + private final String securityRole; +} diff --git a/src/main/java/dgu/choco_express/domain/user/User.java b/src/main/java/dgu/choco_express/domain/user/User.java new file mode 100644 index 0000000..68f2158 --- /dev/null +++ b/src/main/java/dgu/choco_express/domain/user/User.java @@ -0,0 +1,63 @@ +package dgu.choco_express.domain.user; + + +import dgu.choco_express.domain.global.BaseTimeEntity; +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.hibernate.annotations.DynamicUpdate; + +@Entity +@Getter +@DynamicUpdate +@Table(name = "users") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class User extends BaseTimeEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "serial_id", nullable = false, unique = true, updatable = false) + private String serialId; + + @Column(name = "name", nullable = false, updatable = false) + private String name; + + @Column(name = "provider", nullable = false, updatable = false) + @Enumerated(EnumType.STRING) + private EProvider provider; + + @Column(name = "role", nullable = false) + @Enumerated(EnumType.STRING) + private ERole role; + + @Builder + private User( + final String serialId, + final String name, + final ERole role, + final EProvider provider + ) { + this.serialId = serialId; + this.name = name; + this.role = role; + this.provider = provider; + } + + public static User from( + final String serialId, + final String name, + final ERole role, + final EProvider provider + ) { + return User.builder() + .serialId(serialId) + .name(name) + .role(role) + .provider(provider) + .build(); + } +} diff --git a/src/main/java/dgu/choco_express/dto/common/ResponseDto.java b/src/main/java/dgu/choco_express/dto/common/ResponseDto.java new file mode 100644 index 0000000..7eefeb1 --- /dev/null +++ b/src/main/java/dgu/choco_express/dto/common/ResponseDto.java @@ -0,0 +1,31 @@ +package dgu.choco_express.dto.common; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import dgu.choco_express.exception.ErrorResponse; +import lombok.AllArgsConstructor; +import lombok.Getter; + +import static dgu.choco_express.exception.GlobalErrorCode.SUCCESS; + +@Getter +@AllArgsConstructor +@JsonPropertyOrder({"errorCode", "message", "result"}) +public class ResponseDto { + private final String errorCode; + private final String message; + private T result; + + public static ResponseDto success(final T data) { + return new ResponseDto<>(null, "SUCCESS", data); + } + + public static ResponseDto fail(ErrorResponse errorResponse) { + return new ResponseDto<>(errorResponse.getErrorCode(), errorResponse.getMessage(), null); + } + + public ResponseDto(T result) { + this.errorCode = SUCCESS.getErrorCode(); + this.message = SUCCESS.getMessage(); + this.result = result; + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/dto/jwt/response/JwtDto.java b/src/main/java/dgu/choco_express/dto/jwt/response/JwtDto.java new file mode 100644 index 0000000..4eafb2a --- /dev/null +++ b/src/main/java/dgu/choco_express/dto/jwt/response/JwtDto.java @@ -0,0 +1,18 @@ +package dgu.choco_express.dto.jwt.response; + +import lombok.Builder; + +import java.io.Serializable; + +@Builder +public record JwtDto( + String accessToken, + String refreshToken +) implements Serializable { + public static JwtDto of(String accessToken, String refreshToken){ + return JwtDto.builder() + .accessToken(accessToken) + .refreshToken(refreshToken) + .build(); + } +} diff --git a/src/main/java/dgu/choco_express/exception/CommonException.java b/src/main/java/dgu/choco_express/exception/CommonException.java new file mode 100644 index 0000000..cc92b07 --- /dev/null +++ b/src/main/java/dgu/choco_express/exception/CommonException.java @@ -0,0 +1,17 @@ +package dgu.choco_express.exception; + +import lombok.Getter; + +@Getter +public class CommonException extends RuntimeException { + private final ErrorCode code; + + public CommonException(ErrorCode code) { + super(code.getMessage()); + this.code = code; + } + + public static CommonException type(ErrorCode code) { + return new CommonException(code); + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/exception/ErrorCode.java b/src/main/java/dgu/choco_express/exception/ErrorCode.java new file mode 100644 index 0000000..8d907fe --- /dev/null +++ b/src/main/java/dgu/choco_express/exception/ErrorCode.java @@ -0,0 +1,9 @@ +package dgu.choco_express.exception; + +import org.springframework.http.HttpStatus; + +public interface ErrorCode { + HttpStatus getStatus(); + String getErrorCode(); + String getMessage(); +} diff --git a/src/main/java/dgu/choco_express/exception/ErrorResponse.java b/src/main/java/dgu/choco_express/exception/ErrorResponse.java new file mode 100644 index 0000000..8bd12d5 --- /dev/null +++ b/src/main/java/dgu/choco_express/exception/ErrorResponse.java @@ -0,0 +1,29 @@ +package dgu.choco_express.exception; + +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor(access = AccessLevel.PRIVATE) +@AllArgsConstructor +public class ErrorResponse { + private int status; + private String errorCode; + private String message; + + private ErrorResponse(ErrorCode code) { + this.status = code.getStatus().value(); + this.errorCode = code.getErrorCode(); + this.message = code.getMessage(); + } + + public static ErrorResponse from(ErrorCode errorCode) { + return new ErrorResponse(errorCode); + } + + public static ErrorResponse of(ErrorCode errorCode, String message) { + return new ErrorResponse(errorCode.getStatus().value(), errorCode.getErrorCode(), message); + } +} diff --git a/src/main/java/dgu/choco_express/exception/GlobalErrorCode.java b/src/main/java/dgu/choco_express/exception/GlobalErrorCode.java new file mode 100644 index 0000000..f23193c --- /dev/null +++ b/src/main/java/dgu/choco_express/exception/GlobalErrorCode.java @@ -0,0 +1,64 @@ +package dgu.choco_express.exception; + +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +public enum GlobalErrorCode implements ErrorCode { + /** + * 100 : 진행 정보 + */ + + /** + * 200 : 요청 성공 + */ + SUCCESS(HttpStatus.OK, "SUCCESS", "요청에 성공했습니다."), + CREATED(HttpStatus.CREATED, "CREATED", "요청에 성공했으며 리소스가 정상적으로 생성되었습니다."), + ACCEPTED(HttpStatus.ACCEPTED, "ACCEPTED", "요청에 성공했으나 처리가 완료되지 않았습니다."), + + /** + * 300 : 리다이렉션 + */ + SEE_OTHER(HttpStatus.SEE_OTHER, "REDIRECT", "다른 주소로 요청해주세요."), + + /** + * 400 : 요청 실패 + */ + VALIDATION_ERROR(HttpStatus.BAD_REQUEST, "REQUEST_001", "잘못된 요청입니다."), + EMPTY_JWT(HttpStatus.UNAUTHORIZED, "REQUEST_002", "JWT를 입력해주세요."), + INVALID_JWT(HttpStatus.UNAUTHORIZED, "REQUEST_003", "유효하지 않은 JWT입니다."), + INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "REQUEST_004", "JWT 토큰이 일치하지 않습니다"), + UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "REQUEST_005", "자격 증명이 이루어지지 않았습니다."), + INVALID_USER(HttpStatus.FORBIDDEN,"REQUEST_006","권한이 없는 유저의 접근입니다."), + NOT_FOUND(HttpStatus.NOT_FOUND, "REQUEST_007", "잘못된 접근입니다."), + REQUEST_TIMEOUT(HttpStatus.REQUEST_TIMEOUT, "REQUEST_008", "만료된 접근입니다."), + NOT_SUPPORTED_URI_ERROR(HttpStatus.NOT_FOUND, "REQUEST_009", "지원하지 않는 URL입니다."), + NOT_SUPPORTED_METHOD_ERROR(HttpStatus.METHOD_NOT_ALLOWED, "REQUEST_010", "지원하지 않는 HTTP Method 요청입니다."), + NOT_SUPPORTED_MEDIA_TYPE_ERROR(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "REQUEST_011", "잘못된 미디어 타입입니다."), + INVALID_ENUM(HttpStatus.BAD_REQUEST, "REQUEST_012", "Enum 타입으로 변경할 수 없습니다."), + INVALID_HEADER_VALUE(HttpStatus.UNAUTHORIZED, "REQUEST_13", "올바르지 않은 헤더값입니다."), + EXPIRED_TOKEN_ERROR(HttpStatus.UNAUTHORIZED, "REQUEST_14", "만료된 토큰입니다."), + TOKEN_MALFORMED_ERROR(HttpStatus.UNAUTHORIZED, "REQUEST_15", "토큰이 올바르지 않습니다."), + TOKEN_TYPE_ERROR(HttpStatus.UNAUTHORIZED, "REQUEST_16", "토큰 타입이 일치하지 않거나 비어있습니다."), + TOKEN_UNSUPPORTED_ERROR(HttpStatus.UNAUTHORIZED, "REQUEST_17", "지원하지않는 토큰입니다."), + TOKEN_UNKNOWN_ERROR(HttpStatus.UNAUTHORIZED, "REQUEST_18", "알 수 없는 토큰입니다."), + + /** + * 500 : 응답 실패 + */ + INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "RESPONSE_001", "서버와의 연결에 실패했습니다."), + BAD_GATEWAY(HttpStatus.BAD_GATEWAY, "RESPONSE_002", "다른 서버로부터 잘못된 응답이 수신되었습니다."), + INSUFFICIENT_STORAGE(HttpStatus.INSUFFICIENT_STORAGE, "RESPONSE_003", "서버의 용량이 부족해 요청에 실패했습니다."), + UNSUPPORTED_ENCODING(HttpStatus.INTERNAL_SERVER_ERROR, "RESPONSE_004", "지원하지 않는 인코딩입니다.") + ; + + private final HttpStatus status; + private final String errorCode; + private final String message; + + GlobalErrorCode(HttpStatus status, String errorCode, String message) { + this.status = status; + this.errorCode = errorCode; + this.message = message; + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/exception/GlobalExceptionHandler.java b/src/main/java/dgu/choco_express/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..4c427d6 --- /dev/null +++ b/src/main/java/dgu/choco_express/exception/GlobalExceptionHandler.java @@ -0,0 +1,124 @@ +package dgu.choco_express.exception; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.validation.BindException; +import org.springframework.validation.FieldError; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import org.springframework.web.servlet.NoHandlerFoundException; + +import java.util.List; + +@Slf4j +@RestControllerAdvice +@RequiredArgsConstructor +public class GlobalExceptionHandler { + /** + * Custom Exception 전용 ExceptionHandler (@RequestBody) + */ + @ExceptionHandler(CommonException.class) + public ResponseEntity applicationException(CommonException e) { + ErrorCode code = e.getCode(); + logging(code); + + return ResponseEntity + .status(code.getStatus()) + .body(ErrorResponse.from(code)); + } + + /** + * 요청 데이터 Validation 전용 ExceptionHandler (@RequestBody) + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e) { + List fieldErrors = e.getBindingResult().getFieldErrors(); + return convert(GlobalErrorCode.VALIDATION_ERROR, extractErrorMessage(fieldErrors)); + } + + /** + * 요청 데이터 Validation 전용 ExceptionHandler (@ModelAttribute) + */ + @ExceptionHandler(BindException.class) + public ResponseEntity bindException(BindException e) { + List fieldErrors = e.getBindingResult().getFieldErrors(); + return convert(GlobalErrorCode.VALIDATION_ERROR, extractErrorMessage(fieldErrors)); + } + + private String extractErrorMessage(List fieldErrors) { + if (fieldErrors.size() == 1) { + return fieldErrors.get(0).getDefaultMessage(); + } + + StringBuffer buffer = new StringBuffer(); + for (FieldError error : fieldErrors) { + buffer.append(error.getDefaultMessage()).append("\n"); + } + return buffer.toString(); + } + + /** + * 존재하지 않는 Endpoint 전용 ExceptionHandler + */ + @ExceptionHandler({NoHandlerFoundException.class, MethodArgumentTypeMismatchException.class}) + public ResponseEntity noHandlerFoundException() { + return convert(GlobalErrorCode.NOT_SUPPORTED_URI_ERROR); + } + + /** + * HTTP Request Method 오류 전용 ExceptionHandler + */ + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public ResponseEntity httpRequestMethodNotSupportedException() { + return convert(GlobalErrorCode.NOT_SUPPORTED_METHOD_ERROR); + } + + /** + * MediaType 전용 ExceptionHandler + */ + @ExceptionHandler(HttpMediaTypeNotSupportedException.class) + public ResponseEntity httpMediaTypeNotSupportedException() { + return convert(GlobalErrorCode.NOT_SUPPORTED_MEDIA_TYPE_ERROR); + } + + /** + * HTTP Request Method 오류 전용 ExceptionHandler + */ + @ExceptionHandler(AccessDeniedException.class) + public ResponseEntity accessDeniedException() { + return convert(GlobalErrorCode.INVALID_USER); + } + + /** + * 내부 서버 오류 전용 ExceptionHandler + */ + @ExceptionHandler(RuntimeException.class) + public ResponseEntity handleAnyException(RuntimeException e, HttpServletRequest request) { + log.warn(e.getMessage()); + log.warn(request.toString()); + return convert(GlobalErrorCode.INTERNAL_SERVER_ERROR); + } + + private ResponseEntity convert(ErrorCode code) { + return ResponseEntity + .status(code.getStatus()) + .body(ErrorResponse.from(code)); + } + + private ResponseEntity convert(ErrorCode code, String message) { + return ResponseEntity + .status(code.getStatus()) + .body(ErrorResponse.of(code, message)); + } + + private void logging(ErrorCode code) { + log.warn("{} | {} | {}", code.getStatus(), code.getErrorCode(), code.getMessage()); + } +} diff --git a/src/main/java/dgu/choco_express/exception/UserErrorCode.java b/src/main/java/dgu/choco_express/exception/UserErrorCode.java new file mode 100644 index 0000000..72579a3 --- /dev/null +++ b/src/main/java/dgu/choco_express/exception/UserErrorCode.java @@ -0,0 +1,16 @@ +package dgu.choco_express.exception; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; + +@Getter +@RequiredArgsConstructor +public enum UserErrorCode implements ErrorCode { + NOT_FOUND_USER(HttpStatus.NOT_FOUND, "USER_001", "존재하지 않는 사용자입니다."), + ; + + private final HttpStatus status; + private final String errorCode; + private final String message; +} diff --git a/src/main/java/dgu/choco_express/interceptor/post/ResponseInterceptor.java b/src/main/java/dgu/choco_express/interceptor/post/ResponseInterceptor.java new file mode 100644 index 0000000..2de80e6 --- /dev/null +++ b/src/main/java/dgu/choco_express/interceptor/post/ResponseInterceptor.java @@ -0,0 +1,37 @@ +package dgu.choco_express.interceptor.post; + +import dgu.choco_express.dto.common.ResponseDto; +import dgu.choco_express.exception.ErrorResponse; +import lombok.NonNull; +import org.springframework.core.MethodParameter; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +@RestControllerAdvice( + basePackages = "dgu.choco_express" +) +public class ResponseInterceptor implements ResponseBodyAdvice { + @Override + public boolean supports(MethodParameter returnType, @NonNull Class converterType) { + return !(returnType.getParameterType() == ResponseDto.class) + && MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType); + } + + @Override + public Object beforeBodyWrite( + Object body, + MethodParameter returnType, + MediaType selectedContentType, + Class selectedConverterType, + ServerHttpRequest request, + ServerHttpResponse response + ) { + if(body instanceof ErrorResponse) + return ResponseDto.fail((ErrorResponse)body); + return ResponseDto.success(body); + } +} diff --git a/src/main/java/dgu/choco_express/interceptor/pre/UserIdArgumentResolver.java b/src/main/java/dgu/choco_express/interceptor/pre/UserIdArgumentResolver.java new file mode 100644 index 0000000..86e9f26 --- /dev/null +++ b/src/main/java/dgu/choco_express/interceptor/pre/UserIdArgumentResolver.java @@ -0,0 +1,35 @@ +package dgu.choco_express.interceptor.pre; + +import dgu.choco_express.annotation.UserId; +import dgu.choco_express.exception.CommonException; +import dgu.choco_express.exception.GlobalErrorCode; +import org.springframework.core.MethodParameter; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +@Component +public class UserIdArgumentResolver implements HandlerMethodArgumentResolver { + @Override + public boolean supportsParameter(MethodParameter parameter) { + return parameter.getParameterType().equals(Long.class) + && parameter.hasParameterAnnotation(UserId.class); + } + + @Override + public Object resolveArgument( + MethodParameter parameter, + ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, + WebDataBinderFactory binderFactory + ) throws Exception { + final Object userId = webRequest.getAttribute("USER_ID", WebRequest.SCOPE_REQUEST); + if (userId == null){ + throw CommonException.type(GlobalErrorCode.INVALID_HEADER_VALUE); + } + return Long.valueOf(userId.toString()); + } +} diff --git a/src/main/java/dgu/choco_express/interceptor/pre/UserIdInterceptor.java b/src/main/java/dgu/choco_express/interceptor/pre/UserIdInterceptor.java new file mode 100644 index 0000000..80d1a0b --- /dev/null +++ b/src/main/java/dgu/choco_express/interceptor/pre/UserIdInterceptor.java @@ -0,0 +1,21 @@ +package dgu.choco_express.interceptor.pre; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.servlet.HandlerInterceptor; + +public class UserIdInterceptor implements HandlerInterceptor { + @Override + public boolean preHandle( + HttpServletRequest request, + HttpServletResponse response, + Object handler + ) throws Exception { + final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + request.setAttribute("USER_ID", authentication.getName()); + + return HandlerInterceptor.super.preHandle(request, response, handler); + } +} diff --git a/src/main/java/dgu/choco_express/repository/RefreshTokenRepository.java b/src/main/java/dgu/choco_express/repository/RefreshTokenRepository.java new file mode 100644 index 0000000..aa76d2d --- /dev/null +++ b/src/main/java/dgu/choco_express/repository/RefreshTokenRepository.java @@ -0,0 +1,7 @@ +package dgu.choco_express.repository; + +import dgu.choco_express.domain.refreshToken.RefreshToken; +import org.springframework.data.repository.CrudRepository; + +public interface RefreshTokenRepository extends CrudRepository { +} diff --git a/src/main/java/dgu/choco_express/repository/UserRepository.java b/src/main/java/dgu/choco_express/repository/UserRepository.java new file mode 100644 index 0000000..30a1e2d --- /dev/null +++ b/src/main/java/dgu/choco_express/repository/UserRepository.java @@ -0,0 +1,21 @@ +package dgu.choco_express.repository; + +import dgu.choco_express.domain.user.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + // @Query + @Query("select u.id as id, u.role as role from User u where u.serialId = :serialId") + Optional findUserSecurityFromBySerialId(@Param("serialId") String serialId); + + @Query("select u.id as id, u.role as role from User u where u.id = :id") + Optional findUserSecurityFromById(@Param("id") Long id); + + // query method + Optional findBySerialId(String serialId); + Optional findById(Long id); +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/repository/UserSecurityForm.java b/src/main/java/dgu/choco_express/repository/UserSecurityForm.java new file mode 100644 index 0000000..1e23b37 --- /dev/null +++ b/src/main/java/dgu/choco_express/repository/UserSecurityForm.java @@ -0,0 +1,23 @@ +package dgu.choco_express.repository; + +import dgu.choco_express.domain.user.ERole; +import dgu.choco_express.domain.user.User; + +public interface UserSecurityForm { + Long getId(); + ERole getRole(); + + static UserSecurityForm invoke(User user){ + return new UserSecurityForm() { + @Override + public Long getId() { + return user.getId(); + } + + @Override + public ERole getRole() { + return user.getRole(); + } + }; + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/config/SecurityConfig.java b/src/main/java/dgu/choco_express/security/config/SecurityConfig.java new file mode 100644 index 0000000..3568bf9 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/config/SecurityConfig.java @@ -0,0 +1,76 @@ +package dgu.choco_express.security.config; + +import dgu.choco_express.constant.Constants; +import dgu.choco_express.security.filter.JwtAuthenticationFilter; +import dgu.choco_express.security.filter.JwtExceptionFilter; +import dgu.choco_express.security.handler.exception.CustomAccessDeniedHandler; +import dgu.choco_express.security.handler.exception.CustomAuthenticationEntryPointHandler; +import dgu.choco_express.security.handler.login.Oauth2FailureHandler; +import dgu.choco_express.security.handler.login.Oauth2SuccessHandler; +import dgu.choco_express.security.handler.logout.CustomLogoutProcessHandler; +import dgu.choco_express.security.handler.logout.CustomLogoutResultHandler; +import dgu.choco_express.security.provider.JwtAuthenticationManager; +import dgu.choco_express.security.service.CustomOauth2UserDetailService; +import dgu.choco_express.util.JwtUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.logout.LogoutFilter; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + private final Oauth2SuccessHandler oauth2SuccessHandler; + private final Oauth2FailureHandler oauth2FailureHandler; + private final CustomOauth2UserDetailService customOauth2UserDetailService; + private final CustomLogoutProcessHandler customLogoutProcessHandler; + private final CustomLogoutResultHandler customLogoutResultHandler; + private final CustomAccessDeniedHandler customAccessDeniedHandler; + private final CustomAuthenticationEntryPointHandler customAuthenticationEntryPointHandler; + private final JwtUtil jwtUtil; + private final JwtAuthenticationManager jwtAuthenticationManager; + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + return http + .csrf(AbstractHttpConfigurer::disable) + .httpBasic(AbstractHttpConfigurer::disable) + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) + ) + .authorizeHttpRequests(request -> + request + .requestMatchers(Constants.NO_NEED_AUTH.toArray(String[]::new)).permitAll() + .requestMatchers("/api/**").hasAnyRole("USER") + .anyRequest().authenticated() + ) + .formLogin(AbstractHttpConfigurer::disable) + .oauth2Login(oauth2 -> oauth2 + .successHandler(oauth2SuccessHandler) + .failureHandler(oauth2FailureHandler) + .userInfoEndpoint(it -> it.userService(customOauth2UserDetailService)) + ) + .logout(logout -> logout + .logoutUrl("/api/auth/logout") + .addLogoutHandler(customLogoutProcessHandler) + .logoutSuccessHandler(customLogoutResultHandler) + ) + .exceptionHandling(exception -> exception + .accessDeniedHandler(customAccessDeniedHandler) + .authenticationEntryPoint(customAuthenticationEntryPointHandler) + ) + .addFilterBefore( + new JwtAuthenticationFilter(jwtUtil, jwtAuthenticationManager), LogoutFilter.class + ) + .addFilterBefore( + new JwtExceptionFilter(), JwtAuthenticationFilter.class + ) + .getOrBuild(); + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/filter/JwtAuthenticationFilter.java b/src/main/java/dgu/choco_express/security/filter/JwtAuthenticationFilter.java new file mode 100644 index 0000000..9074466 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/filter/JwtAuthenticationFilter.java @@ -0,0 +1,75 @@ +package dgu.choco_express.security.filter; + +import dgu.choco_express.constant.Constants; +import dgu.choco_express.domain.user.ERole; +import dgu.choco_express.exception.CommonException; +import dgu.choco_express.exception.GlobalErrorCode; +import dgu.choco_express.security.info.JwtUserInfo; +import dgu.choco_express.security.provider.JwtAuthenticationManager; +import dgu.choco_express.util.HeaderUtil; +import dgu.choco_express.util.JwtUtil; +import io.jsonwebtoken.Claims; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + private final JwtUtil jwtUtil; + private final JwtAuthenticationManager jwtAuthenticationManager; + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException{ + return Constants.NO_NEED_AUTH.contains(request.getRequestURI()); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + String token = HeaderUtil.refineHeader(request, Constants.PREFIX_AUTH, Constants.PREFIX_BEARER) + .orElseThrow(() -> CommonException.type(GlobalErrorCode.INVALID_HEADER_VALUE)); + + Claims claims = jwtUtil.validateToken(token); + log.info("claim: getUserId() = {}", claims.get(Constants.CLAIM_USER_ID, Long.class)); + + // 클레임에서 사용자 정보 추출 + JwtUserInfo jwtUserInfo = new JwtUserInfo( + claims.get(Constants.CLAIM_USER_ID, Long.class), + ERole.valueOf(claims.get(Constants.CLAIM_USER_ROLE, String.class)) + ); + + // 인증 받지 않은 인증용 객체 생성 + UsernamePasswordAuthenticationToken unAuthenticatedToken = + new UsernamePasswordAuthenticationToken(jwtUserInfo, null, null); + + // 인증 받은 후의 인증 객체 생성 + UsernamePasswordAuthenticationToken authenticatedToken = + (UsernamePasswordAuthenticationToken) jwtAuthenticationManager.authenticate(unAuthenticatedToken); + log.info("인증 성공"); + + // 사용자의 IP 등 세부 정보 인증 정보에 추가 + authenticatedToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(authenticatedToken); + SecurityContextHolder.setContext(securityContext); + + filterChain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/filter/JwtExceptionFilter.java b/src/main/java/dgu/choco_express/security/filter/JwtExceptionFilter.java new file mode 100644 index 0000000..33332d7 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/filter/JwtExceptionFilter.java @@ -0,0 +1,68 @@ +package dgu.choco_express.security.filter; + +import dgu.choco_express.constant.Constants; +import dgu.choco_express.exception.CommonException; +import dgu.choco_express.exception.GlobalErrorCode; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.UnsupportedJwtException; +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.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Slf4j +public class JwtExceptionFilter extends OncePerRequestFilter { + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return Constants.NO_NEED_AUTH.contains(request.getRequestURI()); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + try { + filterChain.doFilter(request, response); + } catch (SecurityException e) { + log.error("FilterException throw SecurityException Exception : {}", e.getMessage()); + request.setAttribute("exception", GlobalErrorCode.INVALID_USER); + filterChain.doFilter(request, response); + } catch (MalformedJwtException e) { + log.error("FilterException throw MalformedJwtException Exception : {}", e.getMessage()); + request.setAttribute("exception", GlobalErrorCode.TOKEN_MALFORMED_ERROR); + filterChain.doFilter(request, response); + } catch (IllegalArgumentException e) { + log.error("FilterException throw IllegalArgumentException Exception : {}", e.getMessage()); + request.setAttribute("exception", GlobalErrorCode.TOKEN_TYPE_ERROR); + filterChain.doFilter(request, response); + } catch (ExpiredJwtException e) { + log.error("FilterException throw ExpiredJwtException Exception : {}", e.getMessage()); + request.setAttribute("exception", GlobalErrorCode.EXPIRED_TOKEN_ERROR); + filterChain.doFilter(request, response); + } catch (UnsupportedJwtException e) { + log.error("FilterException throw UnsupportedJwtException Exception : {}", e.getMessage()); + request.setAttribute("exception", GlobalErrorCode.TOKEN_UNSUPPORTED_ERROR); + filterChain.doFilter(request, response); + } catch (JwtException e) { + log.error("FilterException throw JwtException Exception : {}", e.getMessage()); + request.setAttribute("exception", GlobalErrorCode.TOKEN_UNKNOWN_ERROR); + filterChain.doFilter(request, response); + } catch (CommonException e) { + log.error("FilterException throw BaseException Exception : {}", e.getMessage()); + request.setAttribute("exception", e.getCode()); + filterChain.doFilter(request, response); + } catch (Exception e) { + log.error("FilterException throw Exception Exception : {}", e.getMessage()); + request.setAttribute("exception", GlobalErrorCode.INTERNAL_SERVER_ERROR); + filterChain.doFilter(request, response); + } + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/handler/exception/CustomAccessDeniedHandler.java b/src/main/java/dgu/choco_express/security/handler/exception/CustomAccessDeniedHandler.java new file mode 100644 index 0000000..9cd2eee --- /dev/null +++ b/src/main/java/dgu/choco_express/security/handler/exception/CustomAccessDeniedHandler.java @@ -0,0 +1,25 @@ +package dgu.choco_express.security.handler.exception; + +import dgu.choco_express.exception.GlobalErrorCode; +import dgu.choco_express.security.info.AuthenticationResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Slf4j +@Component +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + @Override + public void handle(HttpServletRequest request, + HttpServletResponse response, + AccessDeniedException accessDeniedException + ) throws IOException, ServletException { + AuthenticationResponse.makeFailureResponse(response, GlobalErrorCode.INVALID_USER); + } +} diff --git a/src/main/java/dgu/choco_express/security/handler/exception/CustomAuthenticationEntryPointHandler.java b/src/main/java/dgu/choco_express/security/handler/exception/CustomAuthenticationEntryPointHandler.java new file mode 100644 index 0000000..2dfbc58 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/handler/exception/CustomAuthenticationEntryPointHandler.java @@ -0,0 +1,29 @@ +package dgu.choco_express.security.handler.exception; + +import dgu.choco_express.exception.ErrorCode; +import dgu.choco_express.exception.GlobalErrorCode; +import dgu.choco_express.security.info.AuthenticationResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Slf4j +@Component +public class CustomAuthenticationEntryPointHandler implements AuthenticationEntryPoint { + @Override + public void commence(HttpServletRequest request, + HttpServletResponse response, + AuthenticationException authenticationException) throws IOException { + ErrorCode errorCode = (ErrorCode) request.getAttribute("exception"); + if (errorCode == null) { + AuthenticationResponse.makeFailureResponse(response, GlobalErrorCode.VALIDATION_ERROR); + return; + } + AuthenticationResponse.makeFailureResponse(response, errorCode); + } +} diff --git a/src/main/java/dgu/choco_express/security/handler/login/Oauth2FailureHandler.java b/src/main/java/dgu/choco_express/security/handler/login/Oauth2FailureHandler.java new file mode 100644 index 0000000..dc68671 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/handler/login/Oauth2FailureHandler.java @@ -0,0 +1,25 @@ +package dgu.choco_express.security.handler.login; + +import dgu.choco_express.exception.GlobalErrorCode; +import dgu.choco_express.security.info.AuthenticationResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class Oauth2FailureHandler implements AuthenticationFailureHandler { + + @Override + public void onAuthenticationFailure( + HttpServletRequest request, + HttpServletResponse response, + AuthenticationException exception + ) throws IOException, ServletException { + AuthenticationResponse.makeFailureResponse(response, GlobalErrorCode.INTERNAL_SERVER_ERROR); + } +} diff --git a/src/main/java/dgu/choco_express/security/handler/login/Oauth2SuccessHandler.java b/src/main/java/dgu/choco_express/security/handler/login/Oauth2SuccessHandler.java new file mode 100644 index 0000000..28ad514 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/handler/login/Oauth2SuccessHandler.java @@ -0,0 +1,47 @@ +package dgu.choco_express.security.handler.login; + +import dgu.choco_express.dto.jwt.response.JwtDto; +import dgu.choco_express.repository.UserRepository; +import dgu.choco_express.security.info.AuthenticationResponse; +import dgu.choco_express.security.info.UserPrincipal; +import dgu.choco_express.service.JwtService; +import dgu.choco_express.util.JwtUtil; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; + +@Component +@RequiredArgsConstructor +public class Oauth2SuccessHandler implements AuthenticationSuccessHandler { + + @Value("${server.domain}") + private String domain; + private final JwtUtil jwtUtil; + private final UserRepository userRepository; + private final JwtService jwtService; + + @Override + @Transactional + public void onAuthenticationSuccess( + HttpServletRequest request, + HttpServletResponse response, + Authentication authentication + ) throws IOException, ServletException { + UserPrincipal principal = (UserPrincipal) authentication.getPrincipal(); + JwtDto jwtDto = jwtUtil.generateTokens(principal.getUserId(), principal.getRole()); + + jwtService.updateRefreshToken(principal.getUserId(), jwtDto.refreshToken()); + + AuthenticationResponse.makeLoginSuccessResponse(response, domain, jwtDto, jwtUtil.getRefreshExpiration()); + + response.sendRedirect("https://" + domain); + } +} diff --git a/src/main/java/dgu/choco_express/security/handler/logout/CustomLogoutProcessHandler.java b/src/main/java/dgu/choco_express/security/handler/logout/CustomLogoutProcessHandler.java new file mode 100644 index 0000000..e390e5a --- /dev/null +++ b/src/main/java/dgu/choco_express/security/handler/logout/CustomLogoutProcessHandler.java @@ -0,0 +1,39 @@ +package dgu.choco_express.security.handler.logout; + +import dgu.choco_express.constant.Constants; +import dgu.choco_express.exception.CommonException; +import dgu.choco_express.exception.GlobalErrorCode; +import dgu.choco_express.service.JwtService; +import dgu.choco_express.util.HeaderUtil; +import dgu.choco_express.util.JwtUtil; +import io.jsonwebtoken.Claims; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutHandler; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Slf4j +@Component +@RequiredArgsConstructor +public class CustomLogoutProcessHandler implements LogoutHandler { + private final JwtService jwtTokenService; + private final JwtUtil jwtUtil; + + @Override + @Transactional + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + if (authentication == null) { + throw CommonException.type(GlobalErrorCode.UNAUTHORIZED); + } + + String accessToken = HeaderUtil.refineHeader(request, Constants.PREFIX_AUTH, Constants.PREFIX_BEARER) + .orElseThrow(() -> CommonException.type(GlobalErrorCode.INVALID_HEADER_VALUE)); + + Claims claims = jwtUtil.validateToken(accessToken); + jwtTokenService.deleteRefreshToken(claims.get(Constants.CLAIM_USER_ID, Long.class)); + } +} diff --git a/src/main/java/dgu/choco_express/security/handler/logout/CustomLogoutResultHandler.java b/src/main/java/dgu/choco_express/security/handler/logout/CustomLogoutResultHandler.java new file mode 100644 index 0000000..b748dd2 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/handler/logout/CustomLogoutResultHandler.java @@ -0,0 +1,25 @@ +package dgu.choco_express.security.handler.logout; + +import dgu.choco_express.exception.UserErrorCode; +import dgu.choco_express.security.info.AuthenticationResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Slf4j +@Component +public class CustomLogoutResultHandler implements LogoutSuccessHandler { + @Override + public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + if (authentication == null) { + log.info("인증 정보가 존재하지 않습니다. authentication is null."); + AuthenticationResponse.makeFailureResponse(response, UserErrorCode.NOT_FOUND_USER); + } + AuthenticationResponse.makeSuccessResponse(response); + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/info/AuthenticationResponse.java b/src/main/java/dgu/choco_express/security/info/AuthenticationResponse.java new file mode 100644 index 0000000..51bb707 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/info/AuthenticationResponse.java @@ -0,0 +1,67 @@ +package dgu.choco_express.security.info; + +import dgu.choco_express.constant.Constants; +import dgu.choco_express.dto.jwt.response.JwtDto; +import dgu.choco_express.exception.ErrorCode; +import dgu.choco_express.exception.GlobalErrorCode; +import dgu.choco_express.util.CookieUtil; +import jakarta.servlet.http.HttpServletResponse; +import net.minidev.json.JSONValue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class AuthenticationResponse { + + public static void makeLoginSuccessResponse( + HttpServletResponse response, + String domain, + JwtDto jwtDto, + Integer refreshExpiration + ) throws IOException { + CookieUtil.addCookie( + response, + domain, + Constants.ACCESS_COOKIE_NAME, + jwtDto.accessToken() + ); + CookieUtil.addSecureCookie( + response, + domain, + Constants.REFRESH_COOKIE_NAME, + jwtDto.refreshToken(), + refreshExpiration + ); + + makeSuccessResponse(response); + } + + public static void makeSuccessResponse(HttpServletResponse response) throws IOException { + + ErrorCode successCode = GlobalErrorCode.SUCCESS; + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + response.setStatus(successCode.getStatus().value()); + + Map body = new HashMap<>(); + body.put("errorCode", successCode.getErrorCode()); + body.put("message", successCode.getMessage()); + body.put("result", null); + + response.getWriter().write(JSONValue.toJSONString(body)); + } + + public static void makeFailureResponse(HttpServletResponse response, ErrorCode errorCode) throws IOException { + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + response.setStatus(errorCode.getStatus().value()); + + Map body= new HashMap<>(); + body.put("errorCode", errorCode.getErrorCode()); + body.put("message", errorCode.getMessage()); + body.put("result", null); + + response.getWriter().write(JSONValue.toJSONString(body)); + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/info/JwtUserInfo.java b/src/main/java/dgu/choco_express/security/info/JwtUserInfo.java new file mode 100644 index 0000000..367e442 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/info/JwtUserInfo.java @@ -0,0 +1,7 @@ +package dgu.choco_express.security.info; + + +import dgu.choco_express.domain.user.ERole; + +public record JwtUserInfo(Long userId, ERole role) { +} diff --git a/src/main/java/dgu/choco_express/security/info/KakaoOauth2UserInfo.java b/src/main/java/dgu/choco_express/security/info/KakaoOauth2UserInfo.java new file mode 100644 index 0000000..33561d6 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/info/KakaoOauth2UserInfo.java @@ -0,0 +1,22 @@ +package dgu.choco_express.security.info; + +import dgu.choco_express.security.info.factory.Oauth2UserInfo; + +import java.util.Map; + +public class KakaoOauth2UserInfo extends Oauth2UserInfo { + public KakaoOauth2UserInfo(Map attributes) { + super(attributes); + } + + @Override + public String getId() { + return attributes.get("id").toString(); + } + + @Override + public String getNickname() { + Map properties = (Map) attributes.get("properties"); + return properties.get("nickname").toString(); + } +} diff --git a/src/main/java/dgu/choco_express/security/info/UserPrincipal.java b/src/main/java/dgu/choco_express/security/info/UserPrincipal.java new file mode 100644 index 0000000..5ea9987 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/info/UserPrincipal.java @@ -0,0 +1,93 @@ +package dgu.choco_express.security.info; + +import dgu.choco_express.domain.user.ERole; +import dgu.choco_express.repository.UserSecurityForm; +import lombok.Builder; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.core.user.OAuth2User; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; + +@Getter +@Builder +@RequiredArgsConstructor +public class UserPrincipal implements UserDetails, OAuth2User { + private final Long userId; + private final String password; + private final ERole role; + private final Map attributes; + private final Collection authorities; + + public static UserPrincipal create(UserSecurityForm securityForm) { + return UserPrincipal.builder() + .userId(securityForm.getId()) + .role(securityForm.getRole()) + .authorities(Collections.singleton(new SimpleGrantedAuthority(securityForm.getRole().getSecurityRole()))) + .build(); + } + + public static UserPrincipal create( + UserSecurityForm securityForm, + Map attributes + ) { + return UserPrincipal.builder() + .userId(securityForm.getId()) + .role(securityForm.getRole()) + .attributes(attributes) + .authorities(Collections.singleton( + new SimpleGrantedAuthority(securityForm.getRole().getSecurityRole())) + ) + .build(); + } + + @Override + public Map getAttributes() { + return attributes; + } + + @Override + public Collection getAuthorities() { + return this.authorities; + } + + @Override + public String getPassword() { + return null; + } + + @Override + public String getUsername() { + return this.userId.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; + } + + @Override + public String getName() { + return userId.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/info/factory/Oauth2UserInfo.java b/src/main/java/dgu/choco_express/security/info/factory/Oauth2UserInfo.java new file mode 100644 index 0000000..df889a8 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/info/factory/Oauth2UserInfo.java @@ -0,0 +1,14 @@ +package dgu.choco_express.security.info.factory; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import java.util.Map; + +@Getter +@RequiredArgsConstructor +public abstract class Oauth2UserInfo { + protected final Map attributes; + public abstract String getId(); + public abstract String getNickname(); +} diff --git a/src/main/java/dgu/choco_express/security/info/factory/Oauth2UserInfoFactory.java b/src/main/java/dgu/choco_express/security/info/factory/Oauth2UserInfoFactory.java new file mode 100644 index 0000000..f3ddf8a --- /dev/null +++ b/src/main/java/dgu/choco_express/security/info/factory/Oauth2UserInfoFactory.java @@ -0,0 +1,22 @@ +package dgu.choco_express.security.info.factory; + +import dgu.choco_express.domain.user.EProvider; +import dgu.choco_express.security.info.KakaoOauth2UserInfo; + +import java.util.Map; + +public class Oauth2UserInfoFactory { + + public static Oauth2UserInfo getOauth2UserInfo( + EProvider provider, + Map attributes + ) { + Oauth2UserInfo ret; + switch (provider) { + case KAKAO -> ret = new KakaoOauth2UserInfo(attributes); + default -> throw new IllegalAccessError("잘못된 제공자입니다."); + } + + return ret; + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/provider/JwtAuthenticationManager.java b/src/main/java/dgu/choco_express/security/provider/JwtAuthenticationManager.java new file mode 100644 index 0000000..de69f51 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/provider/JwtAuthenticationManager.java @@ -0,0 +1,21 @@ +package dgu.choco_express.security.provider; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthenticationManager implements AuthenticationManager { + private final JwtAuthenticationProvider jwtAuthenticationProvider; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + log.info("AuthenticationManager 진입"); + return jwtAuthenticationProvider.authenticate(authentication); + } +} diff --git a/src/main/java/dgu/choco_express/security/provider/JwtAuthenticationProvider.java b/src/main/java/dgu/choco_express/security/provider/JwtAuthenticationProvider.java new file mode 100644 index 0000000..b9ad778 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/provider/JwtAuthenticationProvider.java @@ -0,0 +1,52 @@ +package dgu.choco_express.security.provider; + +import dgu.choco_express.security.info.JwtUserInfo; +import dgu.choco_express.security.info.UserPrincipal; +import dgu.choco_express.security.service.CustomUserDetailService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class JwtAuthenticationProvider implements AuthenticationProvider { + private final CustomUserDetailService customUserDetailService; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + log.info("AuthenticationProvider 진입 성공"); + if (authentication.getPrincipal().getClass().equals(String.class)) { + log.info("로그인 로직 인증 과정"); + return authOfLogin(authentication); + } else { + log.info("로그인 한 사용자 검증 과정"); + return authOfAfterLogin((JwtUserInfo) authentication.getPrincipal()); + } + } + + private Authentication authOfLogin(Authentication authentication) { + // DB에 저장된 실제 데이터 + UserPrincipal userPrincipal = customUserDetailService + .loadUserByUsername(authentication.getPrincipal().toString()); + + // 비밀번호 검증 로직 +// if (!bCryptPasswordEncoder.matches(authentication.getCredentials().toString(), userPrincipal.getPassword())) +// throw new UsernameNotFoundException("비밀번호가 일치하지 않습니다 ! "); + return new UsernamePasswordAuthenticationToken(userPrincipal, null, userPrincipal.getAuthorities()); + } + + private Authentication authOfAfterLogin(JwtUserInfo userInfo) { + UserPrincipal userPrincipal = customUserDetailService.loadUserById(userInfo.userId()); + return new UsernamePasswordAuthenticationToken(userPrincipal, null, userPrincipal.getAuthorities()); + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } +} \ No newline at end of file diff --git a/src/main/java/dgu/choco_express/security/service/CustomOauth2UserDetailService.java b/src/main/java/dgu/choco_express/security/service/CustomOauth2UserDetailService.java new file mode 100644 index 0000000..020a230 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/service/CustomOauth2UserDetailService.java @@ -0,0 +1,58 @@ +package dgu.choco_express.security.service; + +import dgu.choco_express.domain.user.EProvider; +import dgu.choco_express.domain.user.ERole; +import dgu.choco_express.domain.user.User; +import dgu.choco_express.repository.UserRepository; +import dgu.choco_express.repository.UserSecurityForm; +import dgu.choco_express.security.info.UserPrincipal; +import dgu.choco_express.security.info.factory.Oauth2UserInfo; +import dgu.choco_express.security.info.factory.Oauth2UserInfoFactory; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CustomOauth2UserDetailService extends DefaultOAuth2UserService { + + private final UserRepository userRepository; + + @Override + public OAuth2User loadUser( + OAuth2UserRequest userRequest + ) throws OAuth2AuthenticationException { + // provider 가져오기 + EProvider provider = EProvider.valueOf( + userRequest.getClientRegistration().getRegistrationId().toUpperCase() + ); + log.info("oauth 제공자 정보 가져오기 성공, 제공자 = {}", provider); + // 사용자 정보 가져오기 + Oauth2UserInfo oauth2UserInfo = Oauth2UserInfoFactory + .getOauth2UserInfo(provider, super.loadUser(userRequest).getAttributes()); + log.info("oauth 사용자 정보 가져오기 성공"); + log.info("attributes = {}", oauth2UserInfo.getAttributes().toString()); + + UserSecurityForm securityForm = userRepository + .findUserSecurityFromBySerialId(oauth2UserInfo.getId()) + .orElseGet(() -> { + log.info("새로운 사용자 접근, 저장 로직 진입"); + User newUser = userRepository.save( + User.builder() + .serialId(oauth2UserInfo.getId()) + .name(oauth2UserInfo.getNickname()) + .provider(provider) + .role(ERole.USER) + .build() + ); + return UserSecurityForm.invoke(newUser); + }); + log.info("oauth2 사용자 조회 성공"); + return UserPrincipal.create(securityForm, oauth2UserInfo.getAttributes()); + } +} diff --git a/src/main/java/dgu/choco_express/security/service/CustomUserDetailService.java b/src/main/java/dgu/choco_express/security/service/CustomUserDetailService.java new file mode 100644 index 0000000..3f649e1 --- /dev/null +++ b/src/main/java/dgu/choco_express/security/service/CustomUserDetailService.java @@ -0,0 +1,36 @@ +package dgu.choco_express.security.service; + +import dgu.choco_express.exception.CommonException; +import dgu.choco_express.exception.UserErrorCode; +import dgu.choco_express.repository.UserRepository; +import dgu.choco_express.repository.UserSecurityForm; +import dgu.choco_express.security.info.UserPrincipal; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CustomUserDetailService implements UserDetailsService { + private final UserRepository userRepository; + + @Override + public UserPrincipal loadUserByUsername(String username) throws UsernameNotFoundException { + UserSecurityForm userSecurityForm = userRepository.findUserSecurityFromBySerialId(username) + .orElseThrow(() -> new UsernameNotFoundException("존재하지 않는 아이디입니다.")); + log.info(("아이디 기반 조회 성공")); + + return UserPrincipal.create(userSecurityForm); + } + + public UserPrincipal loadUserById(Long id) { + UserSecurityForm userSecurityForm = userRepository.findUserSecurityFromById(id) + .orElseThrow(() -> CommonException.type(UserErrorCode.NOT_FOUND_USER)); + log.info("user id 기반 조회 성공"); + + return UserPrincipal.create(userSecurityForm); + } +} diff --git a/src/main/java/dgu/choco_express/service/JwtService.java b/src/main/java/dgu/choco_express/service/JwtService.java new file mode 100644 index 0000000..69ffc99 --- /dev/null +++ b/src/main/java/dgu/choco_express/service/JwtService.java @@ -0,0 +1,30 @@ +package dgu.choco_express.service; + +import dgu.choco_express.domain.refreshToken.RefreshToken; +import dgu.choco_express.repository.RefreshTokenRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class JwtService { + private final RefreshTokenRepository refreshTokenRepository; + + @Transactional + public void updateRefreshToken(Long userId, String refreshToken) { + refreshTokenRepository.findById(userId) + .ifPresentOrElse( + existingToken -> { + refreshTokenRepository.deleteById(userId); + refreshTokenRepository.save(RefreshToken.issueRefreshToken(userId, refreshToken)); + }, + () -> refreshTokenRepository.save(RefreshToken.issueRefreshToken(userId, refreshToken)) + ); + } + + @Transactional + public void deleteRefreshToken(Long userId) { + refreshTokenRepository.deleteById(userId); + } +} diff --git a/src/main/java/dgu/choco_express/util/CookieUtil.java b/src/main/java/dgu/choco_express/util/CookieUtil.java new file mode 100644 index 0000000..f826af3 --- /dev/null +++ b/src/main/java/dgu/choco_express/util/CookieUtil.java @@ -0,0 +1,85 @@ +package dgu.choco_express.util; + +import dgu.choco_express.constant.Constants; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.ResponseCookie; + +public class CookieUtil { + + public static void addCookie( + HttpServletResponse response, + String domain, + String key, + String value + ) { + ResponseCookie cookie = ResponseCookie.from(key, value) + .path("/") + .domain(domain) + .httpOnly(false) + .secure(true) + .build(); + + response.addHeader("Set-Cookie", cookie.toString()); + } + + public static void logoutCookie( + HttpServletRequest request, + HttpServletResponse response, + String domain + ) { + Cookie[] cookies = request.getCookies(); + if (cookies == null) + return; + + for (Cookie cookie : cookies) { + boolean isAccessCookie = cookie.getName().equals(Constants.ACCESS_COOKIE_NAME); + boolean isRefreshCookie = cookie.getName().equals(Constants.REFRESH_COOKIE_NAME); + + if (isAccessCookie || isRefreshCookie) { + ResponseCookie tempCookie = ResponseCookie.from(cookie.getName(), cookie.getValue()) + .path("/") + .domain(domain) + .secure(true) + .maxAge(0) + .httpOnly(isRefreshCookie) + .build(); + response.addHeader("Set-Cookie", tempCookie.toString()); + } + } + } + + public static void addSecureCookie( + HttpServletResponse response, + String domain, + String key, + String value, + Integer maxAge + ) { + Cookie cookie = new Cookie(key, value); + cookie.setPath("/"); + cookie.setDomain(domain); + cookie.setSecure(true); + cookie.setHttpOnly(true); + cookie.setMaxAge(maxAge); + response.addCookie(cookie); + } + + public static void deleteCookie( + HttpServletRequest request, + HttpServletResponse response, + String name + ) { + Cookie[] cookies = request.getCookies(); + if (cookies == null) + return; + + for (Cookie cookie : cookies) + if (cookie.getName().equals(name)) { + cookie.setMaxAge(0); + cookie.setPath("/"); + response.addCookie(cookie); + } + } +} diff --git a/src/main/java/dgu/choco_express/util/HeaderUtil.java b/src/main/java/dgu/choco_express/util/HeaderUtil.java new file mode 100644 index 0000000..53d4624 --- /dev/null +++ b/src/main/java/dgu/choco_express/util/HeaderUtil.java @@ -0,0 +1,22 @@ +package dgu.choco_express.util; + +import dgu.choco_express.exception.CommonException; +import dgu.choco_express.exception.GlobalErrorCode; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.util.StringUtils; + +import java.util.Optional; + +public class HeaderUtil { + + public static Optional refineHeader( + HttpServletRequest request, + String headerName, + String prefix + ) { + String headerValue = request.getHeader(headerName); + if (!StringUtils.hasText(headerValue) || !headerValue.startsWith(prefix)) + throw CommonException.type(GlobalErrorCode.INVALID_HEADER_VALUE); + return Optional.of(headerValue.substring(prefix.length())); + } +} diff --git a/src/main/java/dgu/choco_express/util/JwtUtil.java b/src/main/java/dgu/choco_express/util/JwtUtil.java new file mode 100644 index 0000000..ebe1b7c --- /dev/null +++ b/src/main/java/dgu/choco_express/util/JwtUtil.java @@ -0,0 +1,70 @@ +package dgu.choco_express.util; + +import dgu.choco_express.constant.Constants; +import dgu.choco_express.domain.user.ERole; +import dgu.choco_express.dto.jwt.response.JwtDto; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Header; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import lombok.Getter; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.security.Key; +import java.util.Date; + +@Component +public class JwtUtil implements InitializingBean { + + @Value("${jwt.secret}") + private String secretKey; + + @Value("${jwt.access-token.expiration}") + @Getter + private Integer accessExpiration; + + @Value("${jwt.refresh-token.expiration}") + @Getter + private Integer refreshExpiration; + + private Key key; + + @Override + public void afterPropertiesSet() throws Exception { + byte[] keyBytes = Decoders.BASE64.decode(secretKey); + this.key = Keys.hmacShaKeyFor(keyBytes); + } + + public Claims validateToken(String token) { + return Jwts.parserBuilder() + .setSigningKey(key) + .build() + .parseClaimsJws(token) + .getBody(); + } + + public String generateToken(Long id, ERole role, Integer expiration) { + Claims claims = Jwts.claims(); + claims.put(Constants.CLAIM_USER_ID, id); + if (role != null) + claims.put(Constants.CLAIM_USER_ROLE, role); + + return Jwts.builder() + .setHeaderParam(Header.JWT_TYPE, Header.JWT_TYPE) + .setClaims(claims) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + expiration)) + .signWith(key) + .compact(); + } + + public JwtDto generateTokens(Long id, ERole role) { + return JwtDto.of( + generateToken(id, role, accessExpiration), + generateToken(id, role, refreshExpiration) + ); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..57e4391 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,13 @@ +spring: + profiles: + default: local +--- +spring: + config: + activate: + on-profile: local +--- +spring: + config: + activate: + on-profile: prod \ No newline at end of file diff --git a/src/test/java/dgu/choco_express/ChocoExpressApplicationTests.java b/src/test/java/dgu/choco_express/ChocoExpressApplicationTests.java new file mode 100644 index 0000000..4620deb --- /dev/null +++ b/src/test/java/dgu/choco_express/ChocoExpressApplicationTests.java @@ -0,0 +1,13 @@ +package dgu.choco_express; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ChocoExpressApplicationTests { + + @Test + void contextLoads() { + } + +}