diff --git a/.github/ISSUE_TEMPLATE/feature-issue-template.md b/.github/ISSUE_TEMPLATE/feature-issue-template.md
new file mode 100644
index 0000000..b18663b
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature-issue-template.md
@@ -0,0 +1,16 @@
+---
+name: Feature issue template
+about: 이슈 템플릿
+title: "[Feature] "
+labels: feature
+assignees: ''
+
+---
+
+## 🔨 Describe
+-
+
+## ✅ Tasks
+- [ ]
+
+## ▪ Etc
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..c4b352c
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,6 @@
+## #️⃣연관된 이슈
+- close #
+
+## 📝작업 내용
+-
+## 💬리뷰 요구사항
diff --git a/.github/workflows/docker-ci.yml b/.github/workflows/docker-ci.yml
new file mode 100644
index 0000000..3b96c42
--- /dev/null
+++ b/.github/workflows/docker-ci.yml
@@ -0,0 +1,108 @@
+name: Java CI with Gradle
+
+# 동작 조건 설정 : main 브랜치에 push가 발생할 경우 동작한다.
+on:
+ push:
+ branches: [ "deploy" ]
+
+permissions:
+ contents: read
+
+jobs:
+ # Spring Boot 애플리케이션을 빌드하여 도커허브에 푸시하는 과정
+ build-docker-image:
+ runs-on: ubuntu-latest
+
+ steps:
+ - name: checkout
+ uses: actions/checkout@v3
+
+ # 1. Java 세팅
+ - name: Set up JDK 11
+ uses: actions/setup-java@v4
+ with:
+ java-version: '11'
+ distribution: 'temurin'
+
+ - name: make application.properties
+ run: |
+ cd ./src/main/resources
+ touch ./application.properties
+
+ # GitHub-Actions 에서 설정한 값을 application.properties 파일에 쓰기
+ echo "${{ secrets.APPLICATION_PROPERTIES }}" >> ./application.properties
+ shell: bash
+
+ # 환경 변수 설정 (Firebase)
+ # - name: create-json
+ # id: create-json
+ # uses: jsdaniell/create-json@v1.2.2
+ # with:
+ # name: ${{ secrets.FIREBASE_JSON_FILENAME }}
+ # json: ${{ secrets.FIREBASE_JSON }}
+ # dir: 'src/main/resources'
+
+
+ # 2. Spring Boot 애플리케이션 빌드
+ - name: Build with Gradle
+ run: |
+ chmod +x ./gradlew
+ ./gradlew bootJar -x test
+
+ # 3. Docker 이미지 빌드
+ - name: docker image build
+ run: docker build -t ${{ secrets.DOCKERHUB_USERNAME }}/github-actions-demo .
+
+ # 4. DockerHub 로그인
+ - name: docker login
+ uses: docker/login-action@v2
+ with:
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
+
+ # 5. Docker Hub 이미지 푸시
+ - name: docker Hub push
+ run: docker push ${{ secrets.DOCKERHUB_USERNAME }}/drugbox-grad
+
+
+ # Deploy Images with Docker compose
+ - name: executing remote ssh commands using password
+ uses: appleboy/ssh-action@master
+ env:
+ APP: "drugbox-grad "
+ COMPOSE: "/home/ubuntu/compose/docker-compose.yml"
+ with:
+ username: ubuntu
+ host: ${{ secrets.EC2_HOST }}
+ key: ${{ secrets.EC2_PRIVATE_KEY }}
+ port: ${{ secrets.EC2_SSH_PORT }}
+ envs: APP, COMPOSE
+ script_stop: true
+ script: |
+ sudo docker-compose -f $COMPOSE down
+ sudo docker pull ${{ secrets.DOCKER_REPO }}/drugbox-grad
+ sudo docker-compose -f $COMPOSE up -d
+
+
+ # 위 과정에서 푸시한 이미지를 ec2에서 풀받아서 실행시키는 과정
+ run-docker-image-on-ec2:
+ # build-docker-image (위)과정이 완료되어야 실행됩니다.
+ needs: build-docker-image
+ runs-on: self-hosted
+
+ steps:
+ # 1. 최신 이미지를 풀받습니다
+ - name: docker pull
+ run: sudo docker pull ${{ secrets.DOCKERHUB_USERNAME }}/drugbox-grad
+
+ # 2. 기존의 컨테이너를 중지시킵니다
+ - name: docker stop container
+ run: sudo docker stop $(sudo docker ps -q) 2>/dev/null || true
+
+ # 3. 최신 이미지를 컨테이너화하여 실행시킵니다
+ - name: docker run new container
+ run: sudo docker run --name drugbox-grad --rm -d -p 8080:8080 ${{ secrets.DOCKERHUB_USERNAME }}/drugbox-grad
+
+ # 4. 미사용 이미지를 정리합니다
+ - name: delete old docker image
+ run: sudo docker system prune -f
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..87baa6d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,40 @@
+HELP.md
+.gradle
+build/
+!gradle/wrapper/gradle-wrapper.jar
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+bin/
+!**/src/main/**/bin/
+!**/src/test/**/bin/
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+out/
+!**/src/main/**/out/
+!**/src/test/**/out/
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+
+### VS Code ###
+.vscode/
+
+### classpath ###
+application.properties
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..f745838
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,9 @@
+FROM openjdk:11
+
+WORKDIR /usr/src/app
+
+ARG JAR_PATH=./build/libs
+
+COPY ${JAR_PATH}/demo-0.0.1-SNAPSHOT.jar ${JAR_PATH}/demo-0.0.1-SNAPSHOT.jar
+
+CMD ["java","-jar","./build/libs/DrugBox-0.0.1-SNAPSHOT.jar"]
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..519b1c8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,7 @@
+# Drugbox - Backend
+Our project is a service that assists in the management of various pharmaceuticals within households and helps properly dispose of expired medications.
+
+We provide guidelines for managing the inventory and expiration dates of over-the-counter and prescription medicines, as well as instructions on how to dispose of waste pharmaceuticals according to prescribed methods.
+
+By utilizing this service, we aim to address various issues caused by improper disposal methods and, ultimately, reduce unnecessary consumption of pharmaceuticals to promote the well-being and health of individuals and the environment.
+
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..e893429
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,75 @@
+plugins {
+ id 'java'
+ id 'org.springframework.boot' version '2.7.5'
+ id 'io.spring.dependency-management' version '1.1.4'
+}
+
+group = 'com'
+version = '0.0.1-SNAPSHOT'
+
+java {
+ sourceCompatibility = '11'
+}
+
+configurations {
+ compileOnly {
+ extendsFrom annotationProcessor
+ }
+}
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation 'org.springframework.boot:spring-boot-starter-web'
+ implementation 'org.springframework.boot:spring-boot-starter-validation'
+ implementation 'org.springframework.boot:spring-boot-starter-security'
+ implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
+
+ // data
+ implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
+ implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
+ runtimeOnly 'com.mysql:mysql-connector-j'
+
+ // lombok
+ compileOnly 'org.projectlombok:lombok'
+ annotationProcessor 'org.projectlombok:lombok'
+
+ // test
+ testImplementation 'org.springframework.boot:spring-boot-starter-test'
+ testImplementation("org.junit.vintage:junit-vintage-engine") {
+ exclude group: "org.hamcrest", module: "hamcrest-core"
+ }
+
+ // Swagger
+ implementation 'io.springfox:springfox-boot-starter:3.0.0'
+
+ // Google Cloud Platform (GCP)
+ implementation 'org.springframework.cloud:spring-cloud-gcp-starter:1.2.5.RELEASE'
+ implementation 'com.google.api-client:google-api-client:1.32.1'
+ implementation 'com.google.oauth-client:google-oauth-client:1.32.1'
+ implementation 'com.google.oauth-client:google-oauth-client-jetty:1.32.1'
+
+ // AWS S3
+ implementation platform('software.amazon.awssdk:bom:2.20.56')
+ implementation 'software.amazon.awssdk:s3'
+
+ // json
+ implementation 'com.googlecode.json-simple:json-simple:1.1.1'
+
+ // csv
+ implementation 'com.opencsv:opencsv:5.5'
+
+ // jwt
+ implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2'
+ runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2'
+ runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2'
+
+ //redis
+ implementation 'org.springframework.boot:spring-boot-starter-data-redis'
+}
+
+tasks.named('test') {
+ useJUnitPlatform()
+}
diff --git a/dump.rdb b/dump.rdb
new file mode 100644
index 0000000..ae475fe
Binary files /dev/null and b/dump.rdb differ
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..d64cd49
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..1af9e09
--- /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.5-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100644
index 0000000..1aa94a4
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,249 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..93e3f59
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,92 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 0000000..fd23a12
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'DrugBox'
diff --git a/src/main/java/com/drugbox/DrugBoxApplication.java b/src/main/java/com/drugbox/DrugBoxApplication.java
new file mode 100644
index 0000000..0d327a8
--- /dev/null
+++ b/src/main/java/com/drugbox/DrugBoxApplication.java
@@ -0,0 +1,15 @@
+package com.drugbox;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+
+@EnableJpaAuditing
+@SpringBootApplication
+public class DrugBoxApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(DrugBoxApplication.class, args);
+ }
+
+}
diff --git a/src/main/java/com/drugbox/common/Util/GeocodingUtil.java b/src/main/java/com/drugbox/common/Util/GeocodingUtil.java
new file mode 100644
index 0000000..1d00988
--- /dev/null
+++ b/src/main/java/com/drugbox/common/Util/GeocodingUtil.java
@@ -0,0 +1,67 @@
+package com.drugbox.common.Util;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.Map;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+
+@Component
+public class GeocodingUtil {
+
+ @Value("${application.spring.cloud.gcp.geocodingAPI}")
+ private String API_KEY;
+
+ public Map getCoordsByAddress(String completeAddress) {
+
+ try {
+ String surl = "https://maps.googleapis.com/maps/api/geocode/json?address="+ URLEncoder.encode(completeAddress, "UTF-8")+
+ "&key="+URLEncoder.encode(API_KEY, "UTF-8");
+ URL url = new URL(surl);
+ InputStream is = url.openConnection().getInputStream();
+ BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
+
+ StringBuilder responseStrBuilder = new StringBuilder();
+ String inputStr;
+ while ((inputStr = streamReader.readLine()) != null) {
+ responseStrBuilder.append(inputStr);
+ }
+
+ JSONParser parser = new JSONParser();
+ JSONObject jo = (JSONObject) parser.parse(responseStrBuilder.toString());
+ JSONArray results = (JSONArray) jo.get("results");
+ String status = jo.get("status").toString();
+ Map ret = new HashMap();
+ if(status.equals("OK")) {
+ JSONObject jsonObject = (JSONObject) results.get(0);
+ JSONObject geometry = (JSONObject) jsonObject.get("geometry");
+ JSONObject location = (JSONObject) geometry.get("location");
+ String lat = location.get("lat").toString();
+ String lng = location.get("lng").toString();
+ ret.put("lat", lat);
+ ret.put("lng", lng);
+
+ return ret;
+ }
+ System.out.println("Address:" + completeAddress);
+ System.out.println(responseStrBuilder);
+ ret.put("lat", "0");
+ ret.put("lng", "0");
+
+ return ret;
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+}
diff --git a/src/main/java/com/drugbox/common/Util/RedisUtil.java b/src/main/java/com/drugbox/common/Util/RedisUtil.java
new file mode 100644
index 0000000..373a230
--- /dev/null
+++ b/src/main/java/com/drugbox/common/Util/RedisUtil.java
@@ -0,0 +1,37 @@
+package com.drugbox.common.Util;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.stereotype.Component;
+
+import java.time.Duration;
+
+@Component
+@RequiredArgsConstructor
+public class RedisUtil {
+
+ private final StringRedisTemplate stringRedisTemplate;
+
+
+ public String getData(String key) {
+ ValueOperations valueOperations = stringRedisTemplate.opsForValue();
+ return valueOperations.get(key);
+ }
+
+
+ public void setData(String key, String value) {
+ ValueOperations valueOperations = stringRedisTemplate.opsForValue();
+ valueOperations.set(key, value);
+ }
+
+ public void setDataExpire(String key, String value, long duration) {
+ ValueOperations valueOperations = stringRedisTemplate.opsForValue();
+ Duration expireDuration = Duration.ofSeconds(duration);
+ valueOperations.set(key, value, expireDuration);
+ }
+
+ public void deleteData(String key) {
+ stringRedisTemplate.delete(key);
+ }
+}
diff --git a/src/main/java/com/drugbox/common/auth/CustomUserDetailsService.java b/src/main/java/com/drugbox/common/auth/CustomUserDetailsService.java
new file mode 100644
index 0000000..b9ecd9a
--- /dev/null
+++ b/src/main/java/com/drugbox/common/auth/CustomUserDetailsService.java
@@ -0,0 +1,40 @@
+package com.drugbox.common.auth;
+
+import com.drugbox.repository.UserRepository;
+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.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.stereotype.Service;
+
+import javax.transaction.Transactional;
+import java.util.Collections;
+
+@Service
+@Transactional
+@RequiredArgsConstructor
+public class CustomUserDetailsService implements UserDetailsService {
+
+ private final UserRepository userRepository;
+
+ @Override
+ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+ return userRepository.findByEmail(username)
+ .map(this::createUserDetails)
+ .orElseThrow(() -> new UsernameNotFoundException(username + " -> 데이터베이스에서 찾을 수 없습니다."));
+ }
+
+ // DB 에 User 값이 존재한다면 UserDetails 객체로 만들어서 리턴
+ private UserDetails createUserDetails(com.drugbox.domain.User user) {
+ GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(user.getAuthority().toString());
+
+ return new org.springframework.security.core.userdetails.User(
+ String.valueOf(user.getId()),
+ user.getPassword(),
+ Collections.singleton(grantedAuthority)
+ );
+ }
+}
diff --git a/src/main/java/com/drugbox/common/auth/SecurityUtil.java b/src/main/java/com/drugbox/common/auth/SecurityUtil.java
new file mode 100644
index 0000000..71b279e
--- /dev/null
+++ b/src/main/java/com/drugbox/common/auth/SecurityUtil.java
@@ -0,0 +1,25 @@
+package com.drugbox.common.auth;
+
+import com.drugbox.common.exception.CustomException;
+import com.drugbox.common.exception.ErrorCode;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+@Slf4j
+public class SecurityUtil {
+
+ private SecurityUtil() { }
+
+ // SecurityContext 에 유저 정보가 저장되는 시점
+ // Request 가 들어올 때 JwtFilter 의 doFilter 에서 저장
+ public static Long getCurrentUserId() {
+ final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
+
+ if (authentication == null || authentication.getName() == null) {
+ throw new CustomException(ErrorCode.SECURITY_CONTEXT_NOT_FOUND);
+ }
+
+ return Long.parseLong(authentication.getName()); // userId
+ }
+}
diff --git a/src/main/java/com/drugbox/common/config/ClientConfig.java b/src/main/java/com/drugbox/common/config/ClientConfig.java
new file mode 100644
index 0000000..e3bf836
--- /dev/null
+++ b/src/main/java/com/drugbox/common/config/ClientConfig.java
@@ -0,0 +1,12 @@
+package com.drugbox.common.config;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.client.RestTemplate;
+
+@Configuration
+public class ClientConfig {
+ @Bean
+ public RestTemplate restTemplate() {
+ return new RestTemplate();
+ }
+}
diff --git a/src/main/java/com/drugbox/common/config/CorsConfig.java b/src/main/java/com/drugbox/common/config/CorsConfig.java
new file mode 100644
index 0000000..9c2e22a
--- /dev/null
+++ b/src/main/java/com/drugbox/common/config/CorsConfig.java
@@ -0,0 +1,26 @@
+package com.drugbox.common.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+
+@Configuration
+public class CorsConfig {
+
+ @Bean
+ public CorsFilter corsFilter() {
+
+ CorsConfiguration configuration = new CorsConfiguration();
+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+
+ configuration.setAllowCredentials(true); // 내 서버가 응답을 할 때 json을 자바스크립트에서 처리할 수 있게 할지를 설정하는 것
+ configuration.addAllowedOrigin("http://localhost:3000");
+ configuration.addAllowedHeader("*"); // 모든 header에 응답을 허용
+ configuration.addAllowedMethod("*"); // 모든 post, get, put, delete, patch 요청을 허용
+
+ source.registerCorsConfiguration("/**", configuration);
+ return new CorsFilter(source);
+ }
+}
diff --git a/src/main/java/com/drugbox/common/config/JwtSecurityConfig.java b/src/main/java/com/drugbox/common/config/JwtSecurityConfig.java
new file mode 100644
index 0000000..5a6563e
--- /dev/null
+++ b/src/main/java/com/drugbox/common/config/JwtSecurityConfig.java
@@ -0,0 +1,22 @@
+package com.drugbox.common.config;
+
+import com.drugbox.common.jwt.JwtFilter;
+import com.drugbox.common.jwt.TokenProvider;
+import lombok.RequiredArgsConstructor;
+import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.web.DefaultSecurityFilterChain;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+
+// 직접 만든 TokenProvider 와 JwtFilter 를 SecurityConfig 에 적용할 때 사용
+@RequiredArgsConstructor
+public class JwtSecurityConfig extends SecurityConfigurerAdapter {
+ private final TokenProvider tokenProvider;
+
+ // TokenProvider 를 주입받아서 JwtFilter 를 통해 Security 로직에 필터를 등록
+ @Override
+ public void configure(HttpSecurity http) {
+ JwtFilter customFilter = new JwtFilter(tokenProvider);
+ http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
+ }
+}
diff --git a/src/main/java/com/drugbox/common/config/RedisConfig.java b/src/main/java/com/drugbox/common/config/RedisConfig.java
new file mode 100644
index 0000000..25024b6
--- /dev/null
+++ b/src/main/java/com/drugbox/common/config/RedisConfig.java
@@ -0,0 +1,30 @@
+package com.drugbox.common.config;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+
+@Configuration
+public class RedisConfig {
+
+ @Value("${spring.data.redis.host}")
+ private String host;
+
+ @Value("${spring.data.redis.port}")
+ private int port;
+
+ @Bean
+ public RedisConnectionFactory redisConnectionFactory() {
+ return new LettuceConnectionFactory(host, port);
+ }
+
+ @Bean
+ public RedisTemplate, ?> redisTemplate() {
+ RedisTemplate, ?> redisTemplate = new RedisTemplate<>();
+ redisTemplate.setConnectionFactory(redisConnectionFactory());
+ return redisTemplate;
+ }
+}
diff --git a/src/main/java/com/drugbox/common/config/S3Config.java b/src/main/java/com/drugbox/common/config/S3Config.java
new file mode 100644
index 0000000..26ee2d9
--- /dev/null
+++ b/src/main/java/com/drugbox/common/config/S3Config.java
@@ -0,0 +1,44 @@
+package com.drugbox.common.config;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.AwsCredentials;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.s3.S3Client;
+
+import java.net.URISyntaxException;
+
+@Configuration
+public class S3Config {
+
+ private String accessKey;
+ private String secretKey;
+ private String region;
+
+ // @Value 어노테이션의 값들은 s3관련된 계정IAM의 accessKey, secretKey와 S3의 리전을 넣어주면된다.
+ public S3Config(@Value("${spring.cloud.aws.credentials.accessKey}")String accessKey,
+ @Value("${spring.cloud.aws.credentials.secretKey}") String secretKey) {
+
+ this.accessKey = accessKey;
+ this.secretKey = secretKey;
+ this.region = "ap-northeast-2";
+ }
+
+ @Bean
+ public AwsCredentials basicAWSCredentials() {
+ return AwsBasicCredentials.create(accessKey, secretKey);
+ }
+
+ @Bean
+ public S3Client s3Client(AwsCredentials awsCredentials) throws URISyntaxException {
+
+ return S3Client.builder()
+ .region(Region.of(region))
+ .credentialsProvider(StaticCredentialsProvider
+ .create(awsCredentials))
+ .build();
+ }
+}
diff --git a/src/main/java/com/drugbox/common/config/SecurityConfig.java b/src/main/java/com/drugbox/common/config/SecurityConfig.java
new file mode 100644
index 0000000..5323695
--- /dev/null
+++ b/src/main/java/com/drugbox/common/config/SecurityConfig.java
@@ -0,0 +1,84 @@
+package com.drugbox.common.config;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import com.drugbox.common.jwt.TokenProvider;
+import com.drugbox.common.jwt.JwtAuthenticationEntryPoint;
+import com.drugbox.common.jwt.JwtAccessDeniedHandler;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.web.SecurityFilterChain;
+
+import java.util.Arrays;
+import java.util.List;
+
+@Configuration
+@RequiredArgsConstructor
+public class SecurityConfig {
+
+ private final TokenProvider tokenProvider;
+ private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
+ private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
+ private final CorsConfig corsConfig;
+
+ @Bean
+ public PasswordEncoder passwordEncoder() {
+ return new BCryptPasswordEncoder();
+ }
+
+ // h2 database 테스트가 원활하도록 관련 API 들은 전부 무시
+ private static final String[] WHITE_LIST = {
+ "/h2-console/**", "/favicon.ico",
+ /* -- Swagger UI v2 */
+ "/v2/api-docs",
+ "/swagger-resources",
+ "/swagger-resources/**",
+ "/configuration/ui",
+ "/configuration/security",
+ "/swagger-ui.html",
+ "/webjars/**",
+ /* -- Swagger UI v3 (OpenAPI) */
+ "/v3/api-docs/**",
+ "/swagger-ui/**",
+ /* Auth */
+ "/auth/**"
+ };
+
+ @Bean
+ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
+
+ http
+ // CSRF 설정 Disable
+ .csrf().disable()
+ .sessionManagement() // 시큐리티는 기본적으로 세션을 사용
+ .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 여기서는 세션을 사용하지 않기 때문에 세션 설정을 Stateless 로 설정
+
+ .and()
+ // exception handling 할 때 우리가 만든 클래스를 추가
+ .exceptionHandling()
+ .authenticationEntryPoint(jwtAuthenticationEntryPoint)
+ .accessDeniedHandler(jwtAccessDeniedHandler)
+
+ .and()
+ .headers()
+ .frameOptions()
+ .sameOrigin()
+
+ // 로그인, 회원가입 API 는 토큰이 없는 상태에서 요청이 들어오기 때문에 permitAll 설정
+ .and()
+ .addFilter(corsConfig.corsFilter())
+ .authorizeRequests()
+ .antMatchers(WHITE_LIST).permitAll()
+ .anyRequest().authenticated() // 나머지 API 는 전부 인증 필요
+
+ // JwtFilter 를 addFilterBefore 로 등록했던 JwtSecurityConfig 클래스를 적용
+ .and()
+ .apply(new JwtSecurityConfig(tokenProvider));
+
+ return http.build();
+ }
+}
diff --git a/src/main/java/com/drugbox/common/config/SwaggerConfig.java b/src/main/java/com/drugbox/common/config/SwaggerConfig.java
new file mode 100644
index 0000000..5513f54
--- /dev/null
+++ b/src/main/java/com/drugbox/common/config/SwaggerConfig.java
@@ -0,0 +1,43 @@
+package com.drugbox.common.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.ApiKey;
+import springfox.documentation.service.AuthorizationScope;
+import springfox.documentation.service.SecurityReference;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spi.service.contexts.SecurityContext;
+import springfox.documentation.spring.web.plugins.Docket;
+
+import java.util.Arrays;
+import java.util.List;
+
+@Configuration
+public class SwaggerConfig {
+
+ public static final String AUTHORIZATION_HEADER = "Authorization";
+
+ @Bean
+ public Docket api() {
+ return new Docket(DocumentationType.SWAGGER_2).securityContexts(
+ Arrays.asList(securityContext())).securitySchemes(Arrays.asList(apiKey())).select()
+ .apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();
+ }
+
+ private ApiKey apiKey() {
+ return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
+ }
+
+ private SecurityContext securityContext() {
+ return SecurityContext.builder().securityReferences(defaultAuth()).build();
+ }
+
+ List defaultAuth() {
+ AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
+ AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
+ authorizationScopes[0] = authorizationScope;
+ return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
+ }
+}
diff --git a/src/main/java/com/drugbox/common/entity/BaseEntity.java b/src/main/java/com/drugbox/common/entity/BaseEntity.java
new file mode 100644
index 0000000..d3cf89a
--- /dev/null
+++ b/src/main/java/com/drugbox/common/entity/BaseEntity.java
@@ -0,0 +1,37 @@
+package com.drugbox.common.entity;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.experimental.SuperBuilder;
+import org.springframework.data.annotation.CreatedDate;
+import org.springframework.data.annotation.LastModifiedDate;
+import org.springframework.data.jpa.domain.support.AuditingEntityListener;
+
+import javax.persistence.*;
+import java.time.LocalDateTime;
+
+@Getter
+@MappedSuperclass
+@EntityListeners(AuditingEntityListener.class)
+@SuperBuilder
+@NoArgsConstructor
+public abstract class BaseEntity {
+
+ @Column(updatable = false)
+ @CreatedDate
+ private LocalDateTime createdDate;
+
+ @LastModifiedDate
+ private LocalDateTime modifiedDate;
+
+ @PrePersist
+ public void prePersist(){
+ LocalDateTime now = LocalDateTime.now();
+ createdDate = now;
+ modifiedDate = now;
+ }
+ @PreUpdate
+ public void preUpdate() {
+ modifiedDate = LocalDateTime.now();
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/drugbox/common/exception/CustomException.java b/src/main/java/com/drugbox/common/exception/CustomException.java
new file mode 100644
index 0000000..2be9f05
--- /dev/null
+++ b/src/main/java/com/drugbox/common/exception/CustomException.java
@@ -0,0 +1,21 @@
+package com.drugbox.common.exception;
+
+import lombok.Getter;
+
+@Getter
+public class CustomException extends RuntimeException {
+
+ private final ErrorCode errorCode;
+
+ public CustomException(ErrorCode errorCode) {
+
+ super(errorCode.getDetail());
+ this.errorCode = errorCode;
+ }
+
+ public CustomException(ErrorCode errorCode, String message) {
+
+ super(message);
+ this.errorCode = errorCode;
+ }
+}
diff --git a/src/main/java/com/drugbox/common/exception/CustomExceptionHandler.java b/src/main/java/com/drugbox/common/exception/CustomExceptionHandler.java
new file mode 100644
index 0000000..9bc1822
--- /dev/null
+++ b/src/main/java/com/drugbox/common/exception/CustomExceptionHandler.java
@@ -0,0 +1,50 @@
+package com.drugbox.common.exception;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.validation.BindException;
+import org.springframework.validation.FieldError;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+import javax.validation.ConstraintViolationException;
+import java.util.Objects;
+
+@Slf4j
+@RestControllerAdvice
+public class CustomExceptionHandler {
+
+ // 일반 에러
+ @ExceptionHandler
+ protected ResponseEntity handleCustomException(CustomException e) {
+
+ return ErrorResponse.toResponseEntity(e);
+ }
+
+ @ExceptionHandler(BindException.class)
+ protected ResponseEntity handleBindException(BindException e) {
+
+ FieldError fieldError = e.getFieldError();
+
+ if (Objects.isNull(fieldError)) {
+ return ErrorResponse.toResponseEntity(HttpStatus.BAD_REQUEST);
+ }
+
+ log.info(fieldError.toString());
+ return ErrorResponse.toResponseEntity(HttpStatus.BAD_REQUEST, fieldError);
+ }
+
+ @ExceptionHandler(SizeLimitExceededException.class)
+ public ResponseEntity handleSizeLimitExceededException(SizeLimitExceededException ex) {
+ log.info("SizeLimitExceededException :: " + ex.getLocalizedMessage());
+ return ErrorResponse.toResponseEntity(new CustomException(ErrorCode.IMAGE_SIZE_EXCEEDED));
+ }
+
+ @ExceptionHandler(ConstraintViolationException.class)
+ protected ResponseEntity handleBindException(ConstraintViolationException e) {
+ log.info("ConstraintViolationException :: " + e.getMessage());
+ return ErrorResponse.toResponseEntity(HttpStatus.BAD_REQUEST, "CONSTRAINT_VIOLATION", e.getMessage());
+ }
+}
diff --git a/src/main/java/com/drugbox/common/exception/ErrorCode.java b/src/main/java/com/drugbox/common/exception/ErrorCode.java
new file mode 100644
index 0000000..50bae75
--- /dev/null
+++ b/src/main/java/com/drugbox/common/exception/ErrorCode.java
@@ -0,0 +1,42 @@
+package com.drugbox.common.exception;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import org.springframework.http.HttpStatus;
+
+@Getter
+@AllArgsConstructor
+public enum ErrorCode {
+
+ // User 예외
+ NOT_FOUND_USER(HttpStatus.NOT_FOUND, "해당 유저를 찾을 수 없습니다."),
+ EXIST_USER_NICKNAME(HttpStatus.CONFLICT, "이미 존재하는 닉네임입니다."),
+ SECURITY_CONTEXT_NOT_FOUND(HttpStatus.NOT_FOUND, "Security Context 에 인증 정보가 없습니다."),
+ EXIST_USER(HttpStatus.CONFLICT, "이미 가입되어 있는 유저입니다."),
+ LOGOUTED_USER(HttpStatus.CONFLICT, "로그아웃 된 사용자입니다."),
+
+
+ // Token 예외
+ TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED, "토큰이 만료되었습니다."),
+ TOKEN_INVALID(HttpStatus.UNAUTHORIZED, "토큰이 유효하지 않습니다."),
+ NOT_FOUND_REFRESH_TOKEN(HttpStatus.NOT_FOUND, "Refresh Token을 찾을 수 없는 사용자입니다. 다시 로그인하세요."),
+ UNAUTHORIZED_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED, "Refresh Token이 유효하지 않습니다."),
+ ID_TOKEN_INVALID(HttpStatus.UNPROCESSABLE_ENTITY, "ID Token 값이 잘못되었습니다. OAUTH 로그인을 다시 시도해보세요."),
+ QUIT_ERROR(HttpStatus.BAD_REQUEST, "OAUTH 탈퇴 과정 중 에러가 발생했습니다."),
+
+ // Drugbox 예외
+ NOT_FOUND_DRUGBOX(HttpStatus.NOT_FOUND, "해당 drugbox를 찾을 수 없습니다."),
+ USER_ALREADY_DRUGBOX_MEMBER(HttpStatus.CONFLICT, "해당 유저가 이미 해당 구급상자 그룹에 속해있습니다."),
+
+ // Drug 예외
+ NOT_FOUND_DRUG(HttpStatus.NOT_FOUND, "해당 약 정보를 찾을 수 없습니다."),
+ NOT_FOUND_DRUGINFO(HttpStatus.NOT_FOUND, "해당 약 상세정보를 찾을 수 없습니다"),
+ DRUG_NOT_IN_DISPOSAL_LIST(HttpStatus.CONFLICT, "해당 약은 폐의약품 리스트에 없습니다."),
+
+ // 이미지 예외
+ IMAGE_SIZE_EXCEEDED(HttpStatus.BAD_REQUEST, "이미지 파일은 10MB이하여야 합니다."),
+ IMAGE_TYPE_INVALID(HttpStatus.BAD_REQUEST, "이미지 파일 타입이 유효하지 않습니다.");
+
+ private final HttpStatus httpStatus;
+ private final String detail;
+}
diff --git a/src/main/java/com/drugbox/common/exception/ErrorResponse.java b/src/main/java/com/drugbox/common/exception/ErrorResponse.java
new file mode 100644
index 0000000..c890cd6
--- /dev/null
+++ b/src/main/java/com/drugbox/common/exception/ErrorResponse.java
@@ -0,0 +1,83 @@
+package com.drugbox.common.exception;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.Builder;
+import lombok.Getter;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.validation.FieldError;
+
+import java.time.LocalDateTime;
+
+@Getter
+@Builder
+public class ErrorResponse {
+
+ @Builder.Default
+ private LocalDateTime timestamp = LocalDateTime.now();
+ private final int status;
+ private final String error;
+ private final String code;
+ private final String detail;
+
+ public static ResponseEntity toResponseEntity(CustomException e) {
+
+ ErrorCode errorCode = e.getErrorCode();
+
+ return ResponseEntity
+ .status(errorCode.getHttpStatus())
+ .body(
+ ErrorResponse.builder()
+ .status(errorCode.getHttpStatus().value()) // httpStatus 코드
+ .error(errorCode.getHttpStatus().name()) // httpStatus 이름
+ .code(errorCode.name()) // errorCode의 이름
+ .detail(errorCode.getDetail()) // errorCode 상세
+ .build()
+ );
+ }
+
+ public static ResponseEntity toResponseEntity(HttpStatus httpStatus, FieldError fieldError) {
+ return ResponseEntity
+ .status(httpStatus)
+ .body(
+ ErrorResponse.builder()
+ .status(httpStatus.value())//httpStatus 코드
+ .error(httpStatus.name())//httpStatus 이름
+ .code(fieldError.getCode())//errorCode 의 이름
+ .detail(fieldError.getDefaultMessage())//errorCode 상세
+ .build()
+ );
+ }
+
+ public static ResponseEntity toResponseEntity(HttpStatus httpStatus, String code, String message) {
+ return ResponseEntity
+ .status(httpStatus)
+ .body(
+ ErrorResponse.builder()
+ .status(httpStatus.value())//httpStatus 코드
+ .error(httpStatus.name())//httpStatus 이름
+ .code(code)//errorCode 의 이름
+ .detail(message)//errorCode 상세
+ .build()
+ );
+ }
+
+ public static ResponseEntity toResponseEntity(HttpStatus httpStatus) {
+ return ResponseEntity
+ .status(httpStatus)
+ .body(
+ ErrorResponse.builder()
+ .status(httpStatus.value())//httpStatus 코드
+ .error(httpStatus.name())//httpStatus 이름
+ .build()
+ );
+ }
+
+ public String convertToJson() throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ return mapper.writeValueAsString(this);
+ }
+
+ public void setDateNull(){ this.timestamp = null;}
+}
diff --git a/src/main/java/com/drugbox/common/jwt/JwtAccessDeniedHandler.java b/src/main/java/com/drugbox/common/jwt/JwtAccessDeniedHandler.java
new file mode 100644
index 0000000..a1a6279
--- /dev/null
+++ b/src/main/java/com/drugbox/common/jwt/JwtAccessDeniedHandler.java
@@ -0,0 +1,24 @@
+package com.drugbox.common.jwt;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.web.access.AccessDeniedHandler;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.ServletException;
+import java.io.IOException;
+
+@Component
+public class JwtAccessDeniedHandler implements AccessDeniedHandler {
+
+ @Override
+ public void handle(HttpServletRequest request, HttpServletResponse response,
+ AccessDeniedException accessDeniedException) throws IOException, ServletException {
+ // 필요한 권한이 없이 접근하려 할때 403
+ response.setContentType(MediaType.APPLICATION_JSON_VALUE);
+ response.setStatus(HttpStatus.FORBIDDEN.value());
+ }
+}
diff --git a/src/main/java/com/drugbox/common/jwt/JwtAuthenticationEntryPoint.java b/src/main/java/com/drugbox/common/jwt/JwtAuthenticationEntryPoint.java
new file mode 100644
index 0000000..19e13db
--- /dev/null
+++ b/src/main/java/com/drugbox/common/jwt/JwtAuthenticationEntryPoint.java
@@ -0,0 +1,23 @@
+package com.drugbox.common.jwt;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@Component
+public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
+
+ @Override
+ public void commence(HttpServletRequest request, HttpServletResponse response,
+ AuthenticationException authException) throws IOException {
+ // 유효한 자격증명을 제공하지 않고 접근하려 할때 401
+ response.setContentType(MediaType.APPLICATION_JSON_VALUE);
+ response.setStatus(HttpStatus.UNAUTHORIZED.value());
+ }
+}
diff --git a/src/main/java/com/drugbox/common/jwt/JwtFilter.java b/src/main/java/com/drugbox/common/jwt/JwtFilter.java
new file mode 100644
index 0000000..499f9e1
--- /dev/null
+++ b/src/main/java/com/drugbox/common/jwt/JwtFilter.java
@@ -0,0 +1,70 @@
+package com.drugbox.common.jwt;
+
+import com.drugbox.common.exception.CustomException;
+import com.drugbox.common.exception.ErrorResponse;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.filter.OncePerRequestFilter;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.util.StringUtils;
+
+import javax.servlet.FilterChain;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.ServletException;
+import java.io.IOException;
+
+@RequiredArgsConstructor
+public class JwtFilter extends OncePerRequestFilter {
+
+ public static final String AUTHORIZATION_HEADER = "Authorization";
+ public static final String BEARER_PREFIX = "Bearer ";
+
+ private final TokenProvider tokenProvider;
+
+ // 실제 필터링 로직은 doFilterInternal 에 들어감
+ // JWT 토큰의 인증 정보를 현재 쓰레드의 SecurityContext 에 저장하는 역할 수행
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
+ FilterChain filterChain) throws IOException, ServletException {
+ try{
+ // 1. Request Header 에서 토큰을 꺼냄
+ String jwt = resolveToken(request);
+
+ // 2. validateToken 으로 토큰 유효성 검사
+ // 정상 토큰이면 해당 토큰으로 Authentication 을 가져와서 SecurityContext 에 저장
+ if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
+ Authentication authentication = tokenProvider.getAuthentication(jwt);
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+ }
+
+ filterChain.doFilter(request, response);
+ } catch (CustomException ex){
+ setErrorResponse(response, ex);
+ }
+ }
+
+ // Request Header 에서 토큰 정보를 꺼내오기
+ private String resolveToken(HttpServletRequest request) {
+ String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
+ if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER_PREFIX)) {
+ return bearerToken.substring(7);
+ }
+ return null;
+ }
+
+ public void setErrorResponse(HttpServletResponse res, Throwable ex) throws IOException {
+ res.setStatus(HttpStatus.UNAUTHORIZED.value());
+ res.setContentType("application/json; charset=UTF-8");
+
+ ErrorResponse jwtExceptionResponse = ErrorResponse.builder()
+ .status(HttpStatus.UNAUTHORIZED.value())
+ .error(HttpStatus.UNAUTHORIZED.name())
+ .code("TOKEN")
+ .detail(ex.getMessage())
+ .build();
+ jwtExceptionResponse.setDateNull();
+ res.getWriter().write(jwtExceptionResponse.convertToJson());
+ }
+}
diff --git a/src/main/java/com/drugbox/common/jwt/TokenDto.java b/src/main/java/com/drugbox/common/jwt/TokenDto.java
new file mode 100644
index 0000000..6917358
--- /dev/null
+++ b/src/main/java/com/drugbox/common/jwt/TokenDto.java
@@ -0,0 +1,17 @@
+package com.drugbox.common.jwt;
+
+import lombok.*;
+
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+public class TokenDto {
+ private String grantType;
+ private String accessToken;
+ private String refreshToken;
+ private Long accessTokenExpiresIn;
+ private Long refreshTokenExpiresIn;
+ private Boolean isNewUser;
+}
diff --git a/src/main/java/com/drugbox/common/jwt/TokenProvider.java b/src/main/java/com/drugbox/common/jwt/TokenProvider.java
new file mode 100644
index 0000000..1d82ba1
--- /dev/null
+++ b/src/main/java/com/drugbox/common/jwt/TokenProvider.java
@@ -0,0 +1,256 @@
+package com.drugbox.common.jwt;
+
+import com.drugbox.common.exception.CustomException;
+import com.drugbox.common.exception.ErrorCode;
+import com.drugbox.common.Util.RedisUtil;
+import com.drugbox.common.oauth.dto.OAuthUserProfile;
+import com.google.api.client.http.javanet.NetHttpTransport;
+import com.google.api.client.json.jackson2.JacksonFactory;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+import io.jsonwebtoken.*;
+import io.jsonwebtoken.io.Decoders;
+import io.jsonwebtoken.security.Keys;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
+import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
+import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.util.Collections;
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+
+import java.security.Key;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+@Slf4j
+@Component
+public class TokenProvider {
+
+ private final RedisUtil redisUtil;
+
+ private static final String AUTHORITIES_KEY = "auth";
+ private static final String BEARER_TYPE = "Bearer";
+ @Value("${application.jwt.access_token.duration}")
+ private long ACCESS_TOKEN_EXPIRE_TIME;
+ @Value("${application.jwt.refresh_token.duration}")
+ private long REFRESH_TOKEN_EXPIRE_TIME;
+ @Value("${spring.security.oauth2.client.registration.google.client-id}")
+ private String CLIENT_ID;
+ private static final String GOOGLE_KEY_URL = "https://www.googleapis.com/oauth2/v3/certs";
+
+
+ private final Key key;
+
+ public TokenProvider(@Value("${application.jwt.secret}") String secretKey,
+ RedisUtil redisUtil) {
+ this.redisUtil = redisUtil;
+ byte[] keyBytes = Decoders.BASE64.decode(secretKey);
+ this.key = Keys.hmacShaKeyFor(keyBytes);
+ }
+
+ public TokenDto generateTokenDto(Authentication authentication) {
+ // 권한들 가져오기
+ String authorities = authentication.getAuthorities().stream()
+ .map(GrantedAuthority::getAuthority)
+ .collect(Collectors.joining(","));
+
+ long now = (new Date()).getTime();
+ Date accessTokenExpiresIn = new Date(now + ACCESS_TOKEN_EXPIRE_TIME);
+ Date refreshTokenExpiresIn = new Date(now + REFRESH_TOKEN_EXPIRE_TIME);
+
+ // Access Token 생성
+ String accessToken = Jwts.builder()
+ .setSubject(authentication.getName()) // payload "sub": "userId"
+ .claim(AUTHORITIES_KEY, authorities) // payload "auth": "ROLE_USER"
+ .setExpiration(accessTokenExpiresIn) // payload "exp": 1516239022 (예시)
+ .signWith(key, SignatureAlgorithm.HS512) // header "alg": "HS512"
+ .compact();
+
+ // Refresh Token 생성
+ String refreshToken = Jwts.builder()
+ .setSubject(authentication.getName())
+ .claim(AUTHORITIES_KEY, authorities)
+ .setExpiration(refreshTokenExpiresIn)
+ .signWith(key, SignatureAlgorithm.HS512)
+ .compact();
+
+ // redis에 refreshToken 저장
+ redisUtil.setDataExpire(authentication.getName(), refreshToken, refreshTokenExpiresIn.getTime());
+
+ return TokenDto.builder()
+ .grantType(BEARER_TYPE)
+ .accessToken(accessToken)
+ .accessTokenExpiresIn(accessTokenExpiresIn.getTime())
+ .refreshToken(refreshToken)
+ .refreshTokenExpiresIn(refreshTokenExpiresIn.getTime())
+ .build();
+ }
+
+ public TokenDto generateTokenDto(String userId) {
+ long now = (new Date()).getTime();
+ Date accessTokenExpiresIn = new Date(now + ACCESS_TOKEN_EXPIRE_TIME);
+ Date refreshTokenExpiresIn = new Date(now + REFRESH_TOKEN_EXPIRE_TIME);
+
+ // Access Token 생성
+ String accessToken = Jwts.builder()
+ .setSubject(userId) // payload "sub": "userId"
+ .claim(AUTHORITIES_KEY, "ROLE_USER") // payload "auth": "ROLE_USER"
+ .setExpiration(accessTokenExpiresIn) // payload "exp": 1516239022 (예시)
+ .signWith(key, SignatureAlgorithm.HS512) // header "alg": "HS512"
+ .compact();
+
+ // Refresh Token 생성
+ String refreshToken = Jwts.builder()
+ .setSubject(userId)
+ .claim(AUTHORITIES_KEY, "ROLE_USER")
+ .setExpiration(refreshTokenExpiresIn)
+ .signWith(key, SignatureAlgorithm.HS512)
+ .compact();
+
+ // redis에 refreshToken 저장
+ redisUtil.setDataExpire(userId, refreshToken, refreshTokenExpiresIn.getTime());
+
+ return TokenDto.builder()
+ .grantType(BEARER_TYPE)
+ .accessToken(accessToken)
+ .accessTokenExpiresIn(accessTokenExpiresIn.getTime())
+ .refreshToken(refreshToken)
+ .refreshTokenExpiresIn(refreshTokenExpiresIn.getTime())
+ .build();
+ }
+
+ public TokenDto generateAccessToken(Authentication authentication) {
+ // 권한들 가져오기
+ String authorities = authentication.getAuthorities().stream()
+ .map(GrantedAuthority::getAuthority)
+ .collect(Collectors.joining(","));
+
+ long now = (new Date()).getTime();
+ Date accessTokenExpiresIn = new Date(now + ACCESS_TOKEN_EXPIRE_TIME);
+
+ // Access Token 생성
+ String accessToken = Jwts.builder()
+ .setSubject(authentication.getName()) // payload "sub": "userId"
+ .claim(AUTHORITIES_KEY, authorities) // payload "auth": "ROLE_USER"
+ .setExpiration(accessTokenExpiresIn) // payload "exp": 1516239022 (예시)
+ .signWith(key, SignatureAlgorithm.HS512) // header "alg": "HS512"
+ .compact();
+
+ return TokenDto.builder()
+ .grantType(BEARER_TYPE)
+ .accessToken(accessToken)
+ .accessTokenExpiresIn(accessTokenExpiresIn.getTime())
+ .build();
+ }
+
+ public Authentication getAuthentication(String token) {
+ // 토큰 복호화
+ Claims claims = parseClaims(token);
+
+ if (claims.get(AUTHORITIES_KEY) == null) {
+ log.info("권한 정보가 없는 토큰입니다.");
+ throw new CustomException(ErrorCode.TOKEN_INVALID);
+ }
+
+ // 클레임에서 권한 정보 가져오기
+ Collection extends GrantedAuthority> authorities =
+ Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
+ .map(SimpleGrantedAuthority::new)
+ .collect(Collectors.toList());
+
+ // UserDetails 객체를 만들어서 Authentication 리턴
+ UserDetails principal = new User(claims.getSubject(), "", authorities);
+
+ return new UsernamePasswordAuthenticationToken(principal, "", authorities);
+ }
+
+ public boolean validateToken(String token) {
+ try {
+ Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
+ return true;
+ } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
+ log.info("잘못된 JWT 서명입니다.");
+ throw new CustomException(ErrorCode.TOKEN_INVALID);
+ } catch (ExpiredJwtException e) {
+ log.info("만료된 JWT 토큰입니다.");
+ throw new CustomException(ErrorCode.TOKEN_EXPIRED);
+ } catch (UnsupportedJwtException e) {
+ log.info("지원되지 않는 JWT 토큰입니다.");
+ throw new CustomException(ErrorCode.TOKEN_INVALID);
+ } catch (IllegalArgumentException e) {
+ log.info("JWT 토큰이 잘못되었습니다.");
+ throw new CustomException(ErrorCode.TOKEN_INVALID);
+ }
+ }
+
+ private Claims parseClaims(String accessToken) {
+ try {
+ return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(accessToken).getBody();
+ } catch (ExpiredJwtException e) {
+ return e.getClaims();
+ }
+ }
+
+ public String parseSubject(String accessToken) {
+ validateToken(accessToken);
+ try {
+ return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(accessToken).getBody().getSubject();
+ } catch (JwtException e){
+ log.info("유효하지 않은 JWT 토큰 입니다");
+ throw new CustomException(ErrorCode.TOKEN_INVALID);
+ }
+ }
+
+ public void deleteRefreshToken(String accessToken) {
+ String userId = parseSubject(accessToken);
+ String data = redisUtil.getData(userId);
+ if (data == null) {
+ throw new CustomException(ErrorCode.NOT_FOUND_REFRESH_TOKEN);
+ }
+ redisUtil.deleteData(userId);
+ }
+
+ public void findRefreshToken(String refreshToken){
+ String id = parseSubject(refreshToken);
+ String data = redisUtil.getData(id);
+ if (!data.equals(refreshToken)) {
+ log.info("Refresh Token Exception");
+ throw new CustomException(ErrorCode.UNAUTHORIZED_REFRESH_TOKEN);
+ }
+ }
+
+ public OAuthUserProfile parseIdToken(String idToken) {
+ try {
+ GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance())
+ .setAudience(Collections.singletonList(CLIENT_ID))
+ .build();
+
+ GoogleIdToken token = verifier.verify(idToken);
+ if (token != null) {
+ Payload payload = token.getPayload();
+ return OAuthUserProfile.builder()
+ .email(payload.getEmail())
+ .nickname(payload.get("name").toString())
+ .image(payload.get("picture").toString())
+ .oauthId(payload.getSubject())
+ .build();
+ }
+ throw new CustomException(ErrorCode.ID_TOKEN_INVALID);
+ } catch (GeneralSecurityException | IOException e) {
+ e.printStackTrace();
+ throw new CustomException(ErrorCode.ID_TOKEN_INVALID);
+ }
+ }
+}
diff --git a/src/main/java/com/drugbox/common/oauth/KeyResolver.java b/src/main/java/com/drugbox/common/oauth/KeyResolver.java
new file mode 100644
index 0000000..bd5704c
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/KeyResolver.java
@@ -0,0 +1,20 @@
+package com.drugbox.common.oauth;
+
+import io.jsonwebtoken.SigningKeyResolverAdapter;
+
+import java.net.URL;
+import java.security.Key;
+import java.security.PublicKey;
+import java.util.List;
+
+public class KeyResolver extends SigningKeyResolverAdapter {
+ private final List publicKeys;
+
+ public KeyResolver(List publicKeys) {
+ this.publicKeys = publicKeys;
+ }
+
+ public Key resolveSigningKey(io.jsonwebtoken.Header header, io.jsonwebtoken.Claims claims) {
+ return publicKeys.get(0); // 첫 번째 공개 키를 사용
+ }
+}
diff --git a/src/main/java/com/drugbox/common/oauth/OAuthApiClient.java b/src/main/java/com/drugbox/common/oauth/OAuthApiClient.java
new file mode 100644
index 0000000..5a85202
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/OAuthApiClient.java
@@ -0,0 +1,8 @@
+package com.drugbox.common.oauth;
+
+
+public interface OAuthApiClient {
+ OAuthProvider oAuthProvider(); // Client 의 타입 반환
+ OAuthInfoResponse requestAccessToken(OAuthLoginParams params); // Authorization Code 를 기반으로 인증 API 를 요청해서 Access Token 을 획득
+ void quit(String accessToken);
+}
diff --git a/src/main/java/com/drugbox/common/oauth/OAuthInfoResponse.java b/src/main/java/com/drugbox/common/oauth/OAuthInfoResponse.java
new file mode 100644
index 0000000..539fb9d
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/OAuthInfoResponse.java
@@ -0,0 +1,7 @@
+package com.drugbox.common.oauth;
+
+public interface OAuthInfoResponse {
+ OAuthProvider getOAuthProvider();
+ String getIdToken();
+ String getAccessToken();
+}
diff --git a/src/main/java/com/drugbox/common/oauth/OAuthLoginParams.java b/src/main/java/com/drugbox/common/oauth/OAuthLoginParams.java
new file mode 100644
index 0000000..81cdaea
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/OAuthLoginParams.java
@@ -0,0 +1,8 @@
+package com.drugbox.common.oauth;
+
+import org.springframework.util.MultiValueMap;
+
+public interface OAuthLoginParams {
+ OAuthProvider oAuthProvider();
+ MultiValueMap makeBody();
+}
diff --git a/src/main/java/com/drugbox/common/oauth/OAuthProvider.java b/src/main/java/com/drugbox/common/oauth/OAuthProvider.java
new file mode 100644
index 0000000..f3d7d20
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/OAuthProvider.java
@@ -0,0 +1,5 @@
+package com.drugbox.common.oauth;
+
+public enum OAuthProvider {
+ GOOGLE
+}
diff --git a/src/main/java/com/drugbox/common/oauth/RequestOAuthInfoService.java b/src/main/java/com/drugbox/common/oauth/RequestOAuthInfoService.java
new file mode 100644
index 0000000..3345a68
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/RequestOAuthInfoService.java
@@ -0,0 +1,30 @@
+package com.drugbox.common.oauth;
+
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+@Component
+public class RequestOAuthInfoService { // OAuthApiClient 를 사용하는 Service 클래스
+
+ private final Map clients;
+
+ public RequestOAuthInfoService(List clients) {
+ this.clients = clients.stream().collect(
+ Collectors.toUnmodifiableMap(OAuthApiClient::oAuthProvider, Function.identity())
+ );
+ }
+
+ public OAuthInfoResponse request(OAuthLoginParams params) {
+ OAuthApiClient client = clients.get(params.oAuthProvider());
+ return client.requestAccessToken(params);
+ }
+
+ public void quit(String accessToken, OAuthProvider oauthProvider){
+ OAuthApiClient client = clients.get(oauthProvider);
+ client.quit(accessToken);
+ }
+}
diff --git a/src/main/java/com/drugbox/common/oauth/dto/OAuthUserProfile.java b/src/main/java/com/drugbox/common/oauth/dto/OAuthUserProfile.java
new file mode 100644
index 0000000..f842ebe
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/dto/OAuthUserProfile.java
@@ -0,0 +1,14 @@
+package com.drugbox.common.oauth.dto;
+
+import lombok.*;
+
+@Getter
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+public class OAuthUserProfile {
+ private String email;
+ private String nickname;
+ private String image;
+ private String oauthId;
+}
diff --git a/src/main/java/com/drugbox/common/oauth/platform/google/GoogleApiClient.java b/src/main/java/com/drugbox/common/oauth/platform/google/GoogleApiClient.java
new file mode 100644
index 0000000..2083317
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/platform/google/GoogleApiClient.java
@@ -0,0 +1,83 @@
+package com.drugbox.common.oauth.platform.google;
+
+import com.drugbox.common.exception.CustomException;
+import com.drugbox.common.exception.ErrorCode;
+import com.drugbox.common.oauth.OAuthApiClient;
+import com.drugbox.common.oauth.OAuthLoginParams;
+import com.drugbox.common.oauth.OAuthProvider;
+import lombok.RequiredArgsConstructor;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.*;
+import org.springframework.stereotype.Component;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.client.RestTemplate;
+
+
+@Component
+@RequiredArgsConstructor
+public class GoogleApiClient implements OAuthApiClient { // 구글 로그인 토큰 받기 & 사용자 정보 가져오기
+
+ private static final String GRANT_TYPE = "authorization_code";
+
+ private String authUrl = "https://oauth2.googleapis.com";
+ private String apiUrl = "https://www.googleapis.com/drive/v2/files";
+
+ @Value("${spring.security.oauth2.client.registration.google.client-id}")
+ private String clientId;
+
+ @Value("${spring.security.oauth2.client.registration.google.client-secret}")
+ private String clientSecret;
+
+ @Value("${spring.security.oauth2.client.registration.google.redirect-uri}")
+ private String redirectUri;
+
+ private final RestTemplate restTemplate; // 외부 요청 후 미리 정의해둔 GoogleTokens, GoogleInfoResponse 로 응답값을 받는다
+
+ @Override
+ public OAuthProvider oAuthProvider() {
+ return OAuthProvider.GOOGLE;
+ }
+
+ @Override
+ public GoogleInfoResponse requestAccessToken(OAuthLoginParams params) {
+ String url = authUrl + "/token";
+
+ HttpHeaders httpHeaders = new HttpHeaders();
+ httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+
+ MultiValueMap body = params.makeBody();
+ body.add("grant_type", GRANT_TYPE);
+ body.add("client_id", clientId);
+ body.add("client_secret", clientSecret);
+ body.add("redirect_uri", redirectUri);
+
+ HttpEntity> request = new HttpEntity<>(body, httpHeaders);
+
+ GoogleTokens response = restTemplate.postForObject(url, request, GoogleTokens.class);
+
+ assert response != null;
+ System.out.println("\n==== access_token:"+response.getAccessToken());
+ System.out.println("==== socpe:"+response.getScope());
+ System.out.println("==== id_token:"+response.getIdToken());
+ System.out.println("==== token_type:"+response.getTokenType());
+
+ GoogleInfoResponse ret = new GoogleInfoResponse(response.getAccessToken(), response.getIdToken());
+ return ret;
+ }
+
+ @Override
+ public void quit(String accessToken){ // 구글에서 발급한 accessToken revoke 신청
+ String url = authUrl + "/revoke?token=" + accessToken;
+
+ HttpHeaders httpHeaders = new HttpHeaders();
+ httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+ MultiValueMap body = new LinkedMultiValueMap<>();
+ HttpEntity> request = new HttpEntity<>(body, httpHeaders);
+
+ ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, request,String.class);
+ if(response.getStatusCode() != HttpStatus.OK){
+ throw new CustomException(ErrorCode.QUIT_ERROR);
+ }
+ }
+}
diff --git a/src/main/java/com/drugbox/common/oauth/platform/google/GoogleInfoResponse.java b/src/main/java/com/drugbox/common/oauth/platform/google/GoogleInfoResponse.java
new file mode 100644
index 0000000..4fd9f2a
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/platform/google/GoogleInfoResponse.java
@@ -0,0 +1,32 @@
+package com.drugbox.common.oauth.platform.google;
+
+import com.drugbox.common.oauth.OAuthInfoResponse;
+import com.drugbox.common.oauth.OAuthProvider;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import lombok.Getter;
+
+@Getter
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class GoogleInfoResponse implements OAuthInfoResponse {
+
+ private String accessToken;
+ private String idToken;
+
+ public GoogleInfoResponse(String accessToken, String idToken) {
+ this.accessToken = accessToken;
+ this.idToken = idToken;
+ }
+
+
+ @Override
+ public OAuthProvider getOAuthProvider() {
+ return OAuthProvider.GOOGLE;
+ }
+
+ @Override
+ public String getIdToken(){ return idToken; }
+
+ @Override
+ public String getAccessToken(){ return accessToken; }
+}
diff --git a/src/main/java/com/drugbox/common/oauth/platform/google/GoogleLoginParams.java b/src/main/java/com/drugbox/common/oauth/platform/google/GoogleLoginParams.java
new file mode 100644
index 0000000..ab8f724
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/platform/google/GoogleLoginParams.java
@@ -0,0 +1,31 @@
+package com.drugbox.common.oauth.platform.google;
+
+import com.drugbox.common.oauth.OAuthLoginParams;
+import com.drugbox.common.oauth.OAuthProvider;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+@Getter
+@Builder
+@NoArgsConstructor
+public class GoogleLoginParams implements OAuthLoginParams {
+ private String authorizationCode;
+
+ public GoogleLoginParams(String authorizationCode) {
+ this.authorizationCode = authorizationCode;
+ }
+
+ @Override
+ public OAuthProvider oAuthProvider() {
+ return OAuthProvider.GOOGLE;
+ }
+
+ @Override
+ public MultiValueMap makeBody() {
+ MultiValueMap body = new LinkedMultiValueMap<>();
+ body.add("code", authorizationCode);
+ return body;
+ }
+}
diff --git a/src/main/java/com/drugbox/common/oauth/platform/google/GoogleTokens.java b/src/main/java/com/drugbox/common/oauth/platform/google/GoogleTokens.java
new file mode 100644
index 0000000..9da7cb1
--- /dev/null
+++ b/src/main/java/com/drugbox/common/oauth/platform/google/GoogleTokens.java
@@ -0,0 +1,27 @@
+package com.drugbox.common.oauth.platform.google;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
+@Getter
+@NoArgsConstructor
+public class GoogleTokens { // https://oauth2.googleapis.com/token 요청 결과값
+ @JsonProperty("access_token")
+ private String accessToken;
+
+ @JsonProperty("token_type")
+ private String tokenType;
+
+ @JsonProperty("refresh_token")
+ private String refreshToken;
+
+ @JsonProperty("expires_in")
+ private String expiresIn;
+
+ @JsonProperty("scope")
+ private String scope;
+
+ @JsonProperty("id_token")
+ private String idToken;
+}
diff --git a/src/main/java/com/drugbox/controller/AuthController.java b/src/main/java/com/drugbox/controller/AuthController.java
new file mode 100644
index 0000000..70489fb
--- /dev/null
+++ b/src/main/java/com/drugbox/controller/AuthController.java
@@ -0,0 +1,65 @@
+package com.drugbox.controller;
+
+import com.drugbox.common.jwt.TokenDto;
+import com.drugbox.common.oauth.platform.google.GoogleLoginParams;
+import com.drugbox.dto.request.UserLoginRequest;
+import com.drugbox.dto.response.IdResponse;
+import com.drugbox.service.AuthService;
+import io.swagger.models.Response;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.Map;
+
+@RestController
+@RequestMapping("/auth")
+@RequiredArgsConstructor
+public class AuthController {
+
+ private final AuthService authService;
+
+ @PostMapping("login/google")
+ public ResponseEntity googleLogin(@RequestBody GoogleLoginParams params){ // auth code
+ return ResponseEntity.ok(authService.googleLogin(params));
+ }
+
+ @GetMapping("/redirect/google") // 백엔드 자체 테스트용
+ public ResponseEntity googleRedirect(@RequestParam("code") String authCode){
+// return ResponseEntity.ok(authService.getGoogleAccessToken(authCode));
+ System.out.println("\n AuthCode:" + authCode); return null;
+ }
+
+ @PostMapping("/signup/pw")
+ public ResponseEntity signup(@RequestBody UserLoginRequest userLoginRequest) {
+ Long userId = authService.signup(userLoginRequest);
+ IdResponse response = IdResponse.builder()
+ .id(userId)
+ .build();
+ return ResponseEntity.ok(response);
+ }
+
+ @PostMapping("/login/pw")
+ public ResponseEntity login(@RequestBody UserLoginRequest userLoginRequest) {
+ return ResponseEntity.ok(authService.login(userLoginRequest));
+ }
+
+ // AccessToken 재발급
+ @PostMapping("/refresh")
+ public ResponseEntity refreshToken(@RequestBody Map refreshToken) {
+ return ResponseEntity.ok(authService.refreshToken(refreshToken.get("refreshToken")));
+ }
+
+ @PostMapping("/logout")
+ public ResponseEntity logout(@RequestBody Map accessToken){
+ authService.logout(accessToken.get("accessToken"));
+ return new ResponseEntity(HttpStatus.OK);
+ }
+
+ @PostMapping("/quit")
+ public ResponseEntity quit(@RequestBody Map accessToken){
+ authService.quit(accessToken.get("accessToken"));
+ return new ResponseEntity(HttpStatus.OK);
+ }
+}
diff --git a/src/main/java/com/drugbox/controller/UserController.java b/src/main/java/com/drugbox/controller/UserController.java
new file mode 100644
index 0000000..80a6074
--- /dev/null
+++ b/src/main/java/com/drugbox/controller/UserController.java
@@ -0,0 +1,54 @@
+package com.drugbox.controller;
+
+import com.drugbox.dto.response.UserDetailResponse;
+import com.drugbox.dto.response.UserEmailResponse;
+import com.drugbox.service.UserService;
+import com.drugbox.common.auth.SecurityUtil;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
+
+@RestController
+@RequiredArgsConstructor
+@Slf4j
+@RequestMapping("users")
+public class UserController {
+ private final UserService userService;
+
+ @GetMapping("/me")
+ public ResponseEntity findMemberInfoById() {
+ return ResponseEntity.ok(userService.findUserInfoById(SecurityUtil.getCurrentUserId()));
+ }
+
+ @GetMapping("/{email}")
+ public ResponseEntity findMemberInfoByEmail(@PathVariable String email) {
+ return ResponseEntity.ok(userService.findUserInfoByEmail(email));
+ }
+
+ @PostMapping("/reward")
+ public ResponseEntity giveUserRewardPoint(){
+ userService.giveUserRewardPoint(SecurityUtil.getCurrentUserId());
+ return new ResponseEntity(HttpStatus.OK);
+ }
+
+ @PatchMapping("/setting/name")
+ public ResponseEntity changeUserNickname(@RequestParam String nickname){
+ userService.changeUserNickname(SecurityUtil.getCurrentUserId(),nickname);
+ return new ResponseEntity(HttpStatus.OK);
+ }
+
+ @GetMapping("/setting/detail")
+ public ResponseEntity getUserDetail(){
+ UserDetailResponse response = userService.getUserDetail(SecurityUtil.getCurrentUserId());
+ return ResponseEntity.status(HttpStatus.OK).body(response);
+ }
+
+ @GetMapping("/setting/reward")
+ public ResponseEntity getUserRewardPoint(){
+ int response = userService.getUserRewardPoints(SecurityUtil.getCurrentUserId());
+ return ResponseEntity.status(HttpStatus.OK).body(response);
+ }
+}
diff --git a/src/main/java/com/drugbox/domain/Authority.java b/src/main/java/com/drugbox/domain/Authority.java
new file mode 100644
index 0000000..38fa01b
--- /dev/null
+++ b/src/main/java/com/drugbox/domain/Authority.java
@@ -0,0 +1,5 @@
+package com.drugbox.domain;
+
+public enum Authority {
+ ROLE_USER, ROLE_ADMIN
+}
diff --git a/src/main/java/com/drugbox/domain/User.java b/src/main/java/com/drugbox/domain/User.java
new file mode 100644
index 0000000..b1bec5b
--- /dev/null
+++ b/src/main/java/com/drugbox/domain/User.java
@@ -0,0 +1,49 @@
+package com.drugbox.domain;
+
+import com.drugbox.common.entity.BaseEntity;
+import com.drugbox.common.oauth.OAuthProvider;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.*;
+
+import static com.drugbox.domain.Authority.ROLE_USER;
+
+@Entity
+@Getter
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+public class User extends BaseEntity {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "user_id")
+ private Long id;
+
+ private String password;
+ @Enumerated(EnumType.STRING)
+ @Builder.Default
+ private Authority authority = ROLE_USER;
+ @Enumerated(EnumType.STRING)
+ private OAuthProvider oauthProvider;
+ private String providerAccessToken;
+ private String oauthId;
+
+
+ @Column(unique = true, length = 20)
+ private String nickname;
+ private String email;
+ private String image;
+ @Builder.Default
+ private int point = 0;
+
+ public void setProviderAccessToken(String token){ this.providerAccessToken = token; }
+ public void setImage(String image){ this.image = image; }
+ public void setNickname(String nickname) {
+ this.nickname = nickname;
+ }
+ public void add100Point(){ this.point += 100;}
+}
diff --git a/src/main/java/com/drugbox/dto/request/UserLoginRequest.java b/src/main/java/com/drugbox/dto/request/UserLoginRequest.java
new file mode 100644
index 0000000..7cb8e02
--- /dev/null
+++ b/src/main/java/com/drugbox/dto/request/UserLoginRequest.java
@@ -0,0 +1,30 @@
+package com.drugbox.dto.request;
+
+import com.drugbox.domain.Authority;
+import com.drugbox.domain.User;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.crypto.password.PasswordEncoder;
+
+@Getter
+@AllArgsConstructor
+@NoArgsConstructor
+public class UserLoginRequest {
+
+ private String email;
+ private String password;
+
+ public User toUser(PasswordEncoder passwordEncoder) {
+ return User.builder()
+ .email(email)
+ .password(passwordEncoder.encode(password))
+ .authority(Authority.ROLE_USER)
+ .build();
+ }
+
+ public UsernamePasswordAuthenticationToken toAuthentication() {
+ return new UsernamePasswordAuthenticationToken(email, password);
+ }
+}
diff --git a/src/main/java/com/drugbox/dto/response/IdResponse.java b/src/main/java/com/drugbox/dto/response/IdResponse.java
new file mode 100644
index 0000000..c88c9b2
--- /dev/null
+++ b/src/main/java/com/drugbox/dto/response/IdResponse.java
@@ -0,0 +1,10 @@
+package com.drugbox.dto.response;
+
+import lombok.Builder;
+import lombok.Getter;
+
+@Getter
+@Builder
+public class IdResponse {
+ private Long id;
+}
diff --git a/src/main/java/com/drugbox/dto/response/UserDetailResponse.java b/src/main/java/com/drugbox/dto/response/UserDetailResponse.java
new file mode 100644
index 0000000..69085e5
--- /dev/null
+++ b/src/main/java/com/drugbox/dto/response/UserDetailResponse.java
@@ -0,0 +1,11 @@
+package com.drugbox.dto.response;
+
+import lombok.Builder;
+import lombok.Getter;
+
+@Getter
+@Builder
+public class UserDetailResponse {
+ private String nickname;
+ private String email;
+}
diff --git a/src/main/java/com/drugbox/dto/response/UserEmailResponse.java b/src/main/java/com/drugbox/dto/response/UserEmailResponse.java
new file mode 100644
index 0000000..20ace9b
--- /dev/null
+++ b/src/main/java/com/drugbox/dto/response/UserEmailResponse.java
@@ -0,0 +1,17 @@
+package com.drugbox.dto.response;
+
+import com.drugbox.domain.User;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+
+@Getter
+@AllArgsConstructor
+@NoArgsConstructor
+public class UserEmailResponse {
+ private String email;
+
+ public static UserEmailResponse of(User user) {
+ return new UserEmailResponse(user.getEmail());
+ }
+}
diff --git a/src/main/java/com/drugbox/dto/response/UserResponse.java b/src/main/java/com/drugbox/dto/response/UserResponse.java
new file mode 100644
index 0000000..963401b
--- /dev/null
+++ b/src/main/java/com/drugbox/dto/response/UserResponse.java
@@ -0,0 +1,11 @@
+package com.drugbox.dto.response;
+
+import lombok.Builder;
+import lombok.Getter;
+
+@Getter
+@Builder
+public class UserResponse {
+ private String nickname;
+ private Long userId;
+}
diff --git a/src/main/java/com/drugbox/repository/UserRepository.java b/src/main/java/com/drugbox/repository/UserRepository.java
new file mode 100644
index 0000000..37b8a37
--- /dev/null
+++ b/src/main/java/com/drugbox/repository/UserRepository.java
@@ -0,0 +1,15 @@
+package com.drugbox.repository;
+
+import com.drugbox.domain.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 {
+ Optional findByNickname(String nickname);
+ Optional findByEmail(String email);
+ User findByOauthId(String oauthId);
+ boolean existsByEmail(String email);
+}
diff --git a/src/main/java/com/drugbox/service/AuthService.java b/src/main/java/com/drugbox/service/AuthService.java
new file mode 100644
index 0000000..d2ad8c0
--- /dev/null
+++ b/src/main/java/com/drugbox/service/AuthService.java
@@ -0,0 +1,143 @@
+package com.drugbox.service;
+
+import com.drugbox.common.exception.CustomException;
+import com.drugbox.common.exception.ErrorCode;
+import com.drugbox.common.jwt.TokenDto;
+import com.drugbox.common.jwt.TokenProvider;
+import com.drugbox.common.oauth.OAuthInfoResponse;
+import com.drugbox.common.oauth.OAuthLoginParams;
+import com.drugbox.common.oauth.OAuthProvider;
+import com.drugbox.common.oauth.RequestOAuthInfoService;
+import com.drugbox.common.oauth.dto.OAuthUserProfile;
+import com.drugbox.common.oauth.platform.google.GoogleLoginParams;
+import com.drugbox.domain.User;
+import com.drugbox.dto.request.UserLoginRequest;
+import com.drugbox.repository.UserRepository;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Service;
+
+import javax.persistence.EntityManager;
+import javax.transaction.Transactional;
+import java.util.HashMap;
+import java.util.Map;
+
+@Service
+@Slf4j
+@Transactional
+@RequiredArgsConstructor
+public class AuthService {
+
+ private final AuthenticationManagerBuilder authenticationManagerBuilder;
+ private final UserRepository userRepository;
+ private final PasswordEncoder passwordEncoder;
+ private final TokenProvider tokenProvider;
+ private final RequestOAuthInfoService requestOAuthInfoService;
+ private final EntityManager em;
+
+ public TokenDto googleLogin(OAuthLoginParams params){
+ OAuthInfoResponse oAuthInfoResponse = requestOAuthInfoService.request(params);
+ Map idAndIsNew = findOrCreateUser(oAuthInfoResponse);
+ Long userId = (Long) idAndIsNew.get("userId");
+ Boolean isNewUser = (Boolean) idAndIsNew.get("isNewUser");
+ TokenDto token = tokenProvider.generateTokenDto(userId.toString());
+ token.setIsNewUser(isNewUser);
+ return token;
+ }
+
+ private Map findOrCreateUser(OAuthInfoResponse oAuthInfoResponse) {
+ OAuthUserProfile profile = tokenProvider.parseIdToken(oAuthInfoResponse.getIdToken());
+
+ Map idAndIfNew = new HashMap<>();
+ Boolean isNewUser = false;
+ User user = userRepository.findByOauthId(profile.getOauthId());
+ if (user == null){
+ user = newUser(profile, oAuthInfoResponse.getOAuthProvider());
+ isNewUser = true;
+ }
+ user.setProviderAccessToken(oAuthInfoResponse.getAccessToken());
+ userRepository.save(user);
+
+ Long userId = user.getId();
+ idAndIfNew.put("userId", userId);
+ idAndIfNew.put("isNewUser", isNewUser);
+ return idAndIfNew;
+ }
+
+ private User newUser(OAuthUserProfile profile, OAuthProvider provider) {
+ User user = User.builder()
+ .email(profile.getEmail())
+ .nickname(profile.getNickname())
+ .image(profile.getImage())
+ .oauthProvider(provider)
+ .oauthId(profile.getOauthId())
+ .build();
+ return userRepository.save(user);
+ }
+
+ public TokenDto getGoogleAccessToken(String authCode){
+ System.out.println("\n==== Auth Code:"+authCode+"\n");
+ GoogleLoginParams params = new GoogleLoginParams(authCode);
+ return googleLogin(params);
+ }
+
+ public Long signup(UserLoginRequest request) {
+ if (userRepository.existsByEmail(request.getEmail())) {
+ throw new CustomException(ErrorCode.EXIST_USER);
+ }
+ User user = request.toUser(passwordEncoder);
+ return userRepository.save(user).getId();
+ }
+
+ public TokenDto login(UserLoginRequest request) {
+ // 1. Login ID/PW 를 기반으로 AuthenticationToken 생성
+ UsernamePasswordAuthenticationToken authenticationToken = request.toAuthentication();
+
+ // 2. 실제로 검증 (사용자 비밀번호 체크) 이 이루어지는 부분
+ // authenticate 메서드가 실행이 될 때 CustomUserDetailsService 에서 만들었던 loadUserByUsername 메서드가 실행됨
+ Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
+
+ // 3. 인증 정보를 기반으로 JWT 토큰 생성
+ // + Redis에 RefreshToken 저장
+ TokenDto tokenDto = tokenProvider.generateTokenDto(authentication);
+
+ // 4. 토큰 발급
+ return tokenDto;
+ }
+
+ public TokenDto refreshToken(String refreshToken) {
+ // 1. Refresh Token 검증
+ tokenProvider.validateToken(refreshToken);
+
+ // 2. Token 에서 User ID 가져오기
+ Authentication authentication = tokenProvider.getAuthentication(refreshToken);
+
+ // 3. Redis에 저장된 Refresh Token과 일치하는지 검사
+ tokenProvider.findRefreshToken(refreshToken);
+
+ // 4. 새로운 Access Token 생성
+ TokenDto tokenDto = tokenProvider.generateAccessToken(authentication);
+
+ // 토큰 발급
+ return tokenDto;
+ }
+
+ public void logout(String accessToken){
+ tokenProvider.deleteRefreshToken(accessToken);
+ }
+
+ public void quit(String accessToken){
+ String userId = tokenProvider.parseSubject(accessToken);
+ User user = userRepository.findById(Long.valueOf(userId))
+ .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER));
+ if(user.getOauthProvider() == OAuthProvider.GOOGLE){ // 연동 해제
+ requestOAuthInfoService.quit(user.getProviderAccessToken(), OAuthProvider.GOOGLE);
+ }
+ tokenProvider.deleteRefreshToken(accessToken);
+ userRepository.delete(user);
+ }
+}
diff --git a/src/main/java/com/drugbox/service/ImageService.java b/src/main/java/com/drugbox/service/ImageService.java
new file mode 100644
index 0000000..f0f548d
--- /dev/null
+++ b/src/main/java/com/drugbox/service/ImageService.java
@@ -0,0 +1,68 @@
+package com.drugbox.service;
+
+import com.drugbox.common.exception.CustomException;
+import com.drugbox.common.exception.ErrorCode;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.beans.factory.annotation.Value;
+import software.amazon.awssdk.core.sync.RequestBody;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.model.PutObjectRequest;
+import software.amazon.awssdk.utils.StringUtils;
+
+import javax.transaction.Transactional;
+import java.io.IOException;
+import java.util.UUID;
+
+@Service
+@RequiredArgsConstructor
+@Slf4j
+@Transactional
+public class ImageService {
+
+ @Value("${spring.cloud.aws.s3.bucket}")
+ private String bucketName;
+
+ private final S3Client s3Client;
+
+ public String uploadImage(MultipartFile image) throws IOException {
+ String uuid = UUID.randomUUID().toString(); // AWS S3 Storage에 저장될 파일 이름
+ String ext = image.getContentType(); // 불가: application/octet-stream(jfif파일), 가능: image/jpeg, image/png 등
+ if(!ext.contains("image")){
+ throw new CustomException(ErrorCode.IMAGE_TYPE_INVALID);
+ }
+
+ return this.putS3(image, uuid);
+ }
+
+ private RequestBody getFileRequestBody(MultipartFile file) throws IOException {
+ return RequestBody.fromInputStream(file.getInputStream(), file.getSize());
+ }
+
+ // 실제 업로드 하는 메소드
+ private String putS3(MultipartFile file, String uuid) throws IOException {
+ String ext = file.getContentType();
+ PutObjectRequest objectRequest =PutObjectRequest.builder()
+ .bucket(bucketName)
+ .key(uuid)
+ .contentType(ext)
+ .contentLength(file.getSize())
+ .build();
+
+ RequestBody rb = getFileRequestBody(file);
+ s3Client.putObject(objectRequest, rb);
+ return uuid;
+ }
+
+ public String processImage(String image) {
+ if (StringUtils.isBlank(image)) {
+ return null;
+ }
+ if (image.startsWith("https://")) { // 구글 프로필 이미지 처리
+ return image;
+ }
+ return "https://" + bucketName + ".s3.ap-northeast-2.amazonaws.com/" + image;
+ }
+}
diff --git a/src/main/java/com/drugbox/service/UserService.java b/src/main/java/com/drugbox/service/UserService.java
new file mode 100644
index 0000000..c3aa3f1
--- /dev/null
+++ b/src/main/java/com/drugbox/service/UserService.java
@@ -0,0 +1,72 @@
+package com.drugbox.service;
+
+import com.drugbox.common.exception.CustomException;
+import com.drugbox.common.exception.ErrorCode;
+import com.drugbox.domain.User;
+import com.drugbox.dto.response.UserDetailResponse;
+import com.drugbox.dto.response.UserEmailResponse;
+import com.drugbox.repository.UserRepository;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@RequiredArgsConstructor
+@Slf4j
+@Transactional
+public class UserService {
+
+ private final UserRepository userRepository;
+
+ public UserEmailResponse findUserInfoById(Long userId){
+ return userRepository.findById(userId)
+ .map(UserEmailResponse::of)
+ .orElseThrow(()-> new CustomException(ErrorCode.NOT_FOUND_USER));
+ }
+
+ public UserEmailResponse findUserInfoByEmail(String email){
+ return userRepository.findByEmail(email)
+ .map(UserEmailResponse::of)
+ .orElseThrow(()-> new CustomException(ErrorCode.NOT_FOUND_USER));
+ }
+
+ public void giveUserRewardPoint(Long userId){
+ User user = getUserOrThrow(userId);
+ user.add100Point();
+ }
+
+ // 유저 이름 변경
+ public void changeUserNickname(Long userId, String nickname){
+ User user = getUserOrThrow(userId);
+ checkNicknameAvailability(nickname);
+ user.setNickname(nickname);
+ userRepository.save(user);
+ }
+
+ // 리워드 포인트 확인
+ public int getUserRewardPoints(Long userId){
+ User user = getUserOrThrow(userId);
+ return user.getPoint();
+ }
+
+ // 유저 정보 조회
+ public UserDetailResponse getUserDetail(Long userId){
+ User user = getUserOrThrow(userId);
+ return UserDetailResponse.builder()
+ .nickname(user.getNickname())
+ .email(user.getEmail())
+ .build();
+ }
+
+ private User getUserOrThrow(Long userId) {
+ return userRepository.findById(userId)
+ .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER));
+ }
+
+ private void checkNicknameAvailability(String nickname){
+ if(userRepository.findByNickname(nickname).isPresent()){
+ throw new CustomException(ErrorCode.EXIST_USER_NICKNAME);
+ }
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
new file mode 100644
index 0000000..2b385ad
--- /dev/null
+++ b/src/main/resources/application.yml
@@ -0,0 +1,74 @@
+server:
+ port: 8080
+
+spring:
+ datasource:
+ driver-class-name: com.mysql.cj.jdbc.Driver
+ url: ${application.spring.datasource.url}
+ username: ${application.spring.datasource.username}
+ password: ${application.spring.datasource.password}
+ databaseAPI: ${application.spring.datasource.databaseAPI}
+
+ jpa:
+ generate-ddl: true
+ hibernate:
+ ddl-auto: create-drop
+ properties:
+ hibernate:
+ format_sql: true
+ database: mysql
+ database-platform: org.hibernate.dialect.MySQL8Dialect
+
+ mvc:
+ pathmatch:
+ matching-strategy: ant_path_matcher
+
+ cloud:
+ aws:
+ s3:
+ bucket: ${spring.cloud.ncp.s3.bucket}
+ credentials:
+ accessKey: ${spring.cloud.aws.credentials.access-key}
+ secretKey: ${spring.cloud.aws.credentials.secret-key}
+ region:
+ static: ap-northeast-2
+ auto: false
+ stack:
+ auto: false
+
+ security:
+ oauth2:
+ client:
+ registration:
+ google:
+ client-id: ${spring.security.oauth2.client.registration.google.client-id}
+ client-secret: ${spring.security.oauth2.client.registration.google.client-secret}
+ redirect-uri: http://localhost:8080/auth/redirect/google
+ authorization-grant-type: authorization_code
+ client-authentication-method: POST
+ client-name: Google
+ scope:
+ - profile
+ - email
+
+ data:
+ redis:
+ port: ${spring.data.redis.port}
+ host: ${spring.data.redis.host}
+
+ servlet:
+ multipart:
+ max-file-size: 10MB
+ max-request-size: 10MB
+
+ api:
+ url: ${application.spring.api.url}
+ key: ${application.spring.api.key}
+
+logging:
+ level:
+ com.drugbox.common: debug
+
+jwt:
+ secret: ${application.jwt.secret}
+ secret_refresh: ${application.jwt.secret_refresh}
\ No newline at end of file
diff --git a/src/test/java/com/drugbox/DrugBoxApplicationTests.java b/src/test/java/com/drugbox/DrugBoxApplicationTests.java
new file mode 100644
index 0000000..86bbfc6
--- /dev/null
+++ b/src/test/java/com/drugbox/DrugBoxApplicationTests.java
@@ -0,0 +1,13 @@
+package com.drugbox;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class DrugBoxApplicationTests {
+
+ @Test
+ void contextLoads() {
+ }
+
+}