add project
This commit is contained in:
3
.gitattributes
vendored
Normal file
3
.gitattributes
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
40
.gitignore
vendored
Normal file
40
.gitignore
vendored
Normal file
@@ -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/
|
||||
|
||||
### Kotlin ###
|
||||
.kotlin
|
||||
23
Dockerfile
Normal file
23
Dockerfile
Normal file
@@ -0,0 +1,23 @@
|
||||
# 1단계: 빌드 스테이지
|
||||
FROM eclipse-temurin:21-jdk-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
# Gradle 빌드 (실행 가능한 bootJar만 생성하도록 함)
|
||||
RUN ./gradlew clean bootJar -x test
|
||||
|
||||
# 2단계: 실행 스테이지
|
||||
FROM eclipse-temurin:21-jre-alpine
|
||||
WORKDIR /app
|
||||
|
||||
# 보안을 위해 비루트 사용자 생성
|
||||
RUN addgroup -S spring && adduser -S spring -G spring
|
||||
|
||||
# 중요: 파일을 복사할 때 소유권을 spring 사용자에게 부여합니다.
|
||||
# 경로를 /app/app.jar로 명시하거나, WORKDIR 내의 상대 경로를 사용합니다.
|
||||
COPY --from=build --chown=spring:spring /app/build/libs/*.jar app.jar
|
||||
|
||||
# 사용자 전환
|
||||
USER spring:spring
|
||||
|
||||
# 실행 경로 수정: /app.jar가 아니라 app.jar (현재 위치) 또는 /app/app.jar를 사용해야 합니다.
|
||||
ENTRYPOINT ["java", "-jar", "-Dspring.profiles.active=prod", "app.jar"]
|
||||
55
build.gradle.kts
Normal file
55
build.gradle.kts
Normal file
@@ -0,0 +1,55 @@
|
||||
plugins {
|
||||
kotlin("jvm") version "1.9.25"
|
||||
kotlin("plugin.spring") version "1.9.25"
|
||||
id("org.springframework.boot") version "3.5.9"
|
||||
id("io.spring.dependency-management") version "1.1.7"
|
||||
kotlin("plugin.jpa") version "1.9.25"
|
||||
}
|
||||
|
||||
group = "me.wypark"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
description = "blog-backend"
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-web")
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-redis")
|
||||
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||
developmentOnly("org.springframework.boot:spring-boot-devtools")
|
||||
runtimeOnly("org.postgresql:postgresql")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
|
||||
testImplementation("org.springframework.security:spring-security-test")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
implementation("io.jsonwebtoken:jjwt-api:0.12.3")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.3")
|
||||
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.12.3")
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
freeCompilerArgs.addAll("-Xjsr305=strict")
|
||||
}
|
||||
}
|
||||
|
||||
allOpen {
|
||||
annotation("jakarta.persistence.Entity")
|
||||
annotation("jakarta.persistence.MappedSuperclass")
|
||||
annotation("jakarta.persistence.Embeddable")
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
53
docker-compose.yml
Normal file
53
docker-compose.yml
Normal file
@@ -0,0 +1,53 @@
|
||||
services:
|
||||
# 백엔드 애플리케이션
|
||||
blog-api:
|
||||
build: .
|
||||
container_name: blog-api
|
||||
restart: always
|
||||
environment:
|
||||
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/blog_db
|
||||
- SPRING_DATASOURCE_USERNAME=wypark
|
||||
- SPRING_DATASOURCE_PASSWORD=your_password
|
||||
- SPRING_DATA_REDIS_HOST=redis
|
||||
- SPRING_DATA_REDIS_PORT=6379
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- blog-net
|
||||
|
||||
# 데이터베이스 (PostgreSQL 17 추천)
|
||||
db:
|
||||
image: postgres:17-alpine
|
||||
container_name: blog-db
|
||||
restart: always
|
||||
environment:
|
||||
POSTGRES_USER: wypark
|
||||
POSTGRES_PASSWORD: your_password
|
||||
POSTGRES_DB: blog_db
|
||||
volumes:
|
||||
- ./postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U wypark -d blog_db"]
|
||||
interval: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- blog-net
|
||||
|
||||
# 캐시 서버 (Redis 7)
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: blog-redis
|
||||
restart: always
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- blog-net
|
||||
|
||||
networks:
|
||||
blog-net:
|
||||
driver: bridge
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
251
gradlew
vendored
Normal file
251
gradlew
vendored
Normal file
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
94
gradlew.bat
vendored
Normal file
94
gradlew.bat
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
settings.gradle.kts
Normal file
1
settings.gradle.kts
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = "blog-backend"
|
||||
@@ -0,0 +1,11 @@
|
||||
package me.wypark.blogbackend
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.runApplication
|
||||
|
||||
@SpringBootApplication
|
||||
class BlogBackendApplication
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
runApplication<BlogBackendApplication>(*args)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package me.wypark.blogbackend.api.dto
|
||||
|
||||
data class TokenDto(
|
||||
val grantType: String = "Bearer",
|
||||
val accessToken: String,
|
||||
val refreshToken: String,
|
||||
val accessTokenExpiresIn: Long
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
package me.wypark.blogbackend.core.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
|
||||
class CorsConfig {
|
||||
@Bean
|
||||
fun corsFilter(): CorsFilter {
|
||||
val source = UrlBasedCorsConfigurationSource()
|
||||
val config = CorsConfiguration()
|
||||
|
||||
config.allowCredentials = true // 쿠키/토큰 허용
|
||||
config.addAllowedOriginPattern("*") // 개발용 (배포 시 프론트 도메인으로 변경 추천)
|
||||
config.addAllowedHeader("*")
|
||||
config.addAllowedMethod("*") // GET, POST, PUT, DELETE 등 모두 허용
|
||||
|
||||
source.registerCorsConfiguration("/api/**", config)
|
||||
return CorsFilter(source)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package me.wypark.blogbackend.core.config
|
||||
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
|
||||
|
||||
@Configuration
|
||||
@EnableJpaAuditing // 엔티티의 생성일/수정일 자동 주입 활성화
|
||||
class JpaConfig
|
||||
@@ -0,0 +1,14 @@
|
||||
package me.wypark.blogbackend.core.config
|
||||
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
|
||||
@Configuration
|
||||
class PasswordConfig {
|
||||
@Bean
|
||||
fun passwordEncoder(): PasswordEncoder {
|
||||
return BCryptPasswordEncoder()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package me.wypark.blogbackend.core.config
|
||||
|
||||
import me.wypark.blogbackend.core.config.jwt.JwtAuthenticationFilter
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.http.HttpMethod
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
|
||||
import org.springframework.security.config.http.SessionCreationPolicy
|
||||
import org.springframework.security.web.SecurityFilterChain
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
|
||||
import org.springframework.web.filter.CorsFilter
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
class SecurityConfig(
|
||||
private val corsFilter: CorsFilter,
|
||||
private val jwtAuthenticationFilter: JwtAuthenticationFilter // 주입 추가
|
||||
) {
|
||||
|
||||
@Bean
|
||||
fun filterChain(http: HttpSecurity): SecurityFilterChain {
|
||||
http
|
||||
.csrf { it.disable() }
|
||||
.httpBasic { it.disable() }
|
||||
.formLogin { it.disable() }
|
||||
.addFilter(corsFilter)
|
||||
.sessionManagement {
|
||||
it.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
}
|
||||
.authorizeHttpRequests { auth ->
|
||||
auth.requestMatchers("/api/auth/**").permitAll()
|
||||
auth.requestMatchers(HttpMethod.GET, "/api/posts/**", "/api/categories/**", "/api/tags/**").permitAll()
|
||||
auth.requestMatchers(HttpMethod.POST, "/api/comments/**").permitAll() // 비회원 댓글 허용
|
||||
auth.requestMatchers("/api/admin/**").hasRole("ADMIN")
|
||||
auth.anyRequest().authenticated()
|
||||
}
|
||||
// 필터 등록: UsernamePasswordAuthenticationFilter 앞에 JwtFilter를 실행
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java)
|
||||
|
||||
return http.build()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package me.wypark.blogbackend.core.config.jwt
|
||||
|
||||
import jakarta.servlet.FilterChain
|
||||
import jakarta.servlet.http.HttpServletRequest
|
||||
import jakarta.servlet.http.HttpServletResponse
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
import org.springframework.util.StringUtils
|
||||
import org.springframework.web.filter.OncePerRequestFilter
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
@Component
|
||||
class JwtAuthenticationFilter(
|
||||
private val jwtProvider: JwtProvider
|
||||
) : OncePerRequestFilter() {
|
||||
|
||||
override fun doFilterInternal(
|
||||
request: HttpServletRequest,
|
||||
response: HttpServletResponse,
|
||||
filterChain: FilterChain
|
||||
) {
|
||||
// 1. Request Header에서 토큰 추출
|
||||
val token = resolveToken(request)
|
||||
|
||||
// 2. 토큰 유효성 검사
|
||||
// 토큰이 존재하고 유효하다면 인증 정보를 가져와 Context에 저장
|
||||
if (StringUtils.hasText(token) && jwtProvider.validateToken(token!!)) {
|
||||
val authentication = jwtProvider.getAuthentication(token)
|
||||
SecurityContextHolder.getContext().authentication = authentication
|
||||
}
|
||||
|
||||
// 3. 다음 필터로 진행
|
||||
filterChain.doFilter(request, response)
|
||||
}
|
||||
|
||||
// Request Header에서 토큰 정보 추출
|
||||
private fun resolveToken(request: HttpServletRequest): String? {
|
||||
val bearerToken = request.getHeader(AUTHORIZATION_HEADER)
|
||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER_PREFIX)) {
|
||||
return bearerToken.substring(7) // "Bearer " 이후의 문자열만 반환
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val AUTHORIZATION_HEADER = "Authorization"
|
||||
const val BEARER_PREFIX = "Bearer "
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package me.wypark.blogbackend.core.config.jwt
|
||||
|
||||
import io.jsonwebtoken.*
|
||||
import io.jsonwebtoken.io.Decoders
|
||||
import io.jsonwebtoken.security.Keys
|
||||
import me.wypark.blogbackend.api.dto.TokenDto
|
||||
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.stereotype.Component
|
||||
import java.util.*
|
||||
import javax.crypto.SecretKey
|
||||
|
||||
@Component
|
||||
class JwtProvider(
|
||||
@Value("\${jwt.secret}") secretKey: String,
|
||||
@Value("\${jwt.access-token-validity}") private val accessTokenValidity: Long,
|
||||
@Value("\${jwt.refresh-token-validity}") private val refreshTokenValidity: Long
|
||||
) {
|
||||
private val key: SecretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey))
|
||||
|
||||
// 1. 토큰 생성 (Access + Refresh 동시 발급)
|
||||
fun generateTokenDto(authentication: Authentication): TokenDto {
|
||||
val authorities = authentication.authorities.joinToString(",") { it.authority }
|
||||
val now = Date().time
|
||||
|
||||
// Access Token 생성
|
||||
val accessTokenExpiresIn = Date(now + accessTokenValidity)
|
||||
val accessToken = Jwts.builder()
|
||||
.subject(authentication.name) // email 또는 id
|
||||
.claim("auth", authorities) // 권한 정보 (ROLE_USER 등)
|
||||
.expiration(accessTokenExpiresIn)
|
||||
.signWith(key)
|
||||
.compact()
|
||||
|
||||
// Refresh Token 생성 (권한 정보 등은 제외하고 만료일만 설정)
|
||||
val refreshToken = Jwts.builder()
|
||||
.subject(authentication.name)
|
||||
.expiration(Date(now + refreshTokenValidity))
|
||||
.signWith(key)
|
||||
.compact()
|
||||
|
||||
return TokenDto(
|
||||
accessToken = accessToken,
|
||||
refreshToken = refreshToken,
|
||||
accessTokenExpiresIn = accessTokenExpiresIn.time
|
||||
)
|
||||
}
|
||||
|
||||
// 2. 토큰에서 인증 정보(Authentication) 추출
|
||||
fun getAuthentication(accessToken: String): Authentication {
|
||||
val claims = parseClaims(accessToken)
|
||||
|
||||
if (claims["auth"] == null) {
|
||||
throw RuntimeException("권한 정보가 없는 토큰입니다.")
|
||||
}
|
||||
|
||||
val authorities: Collection<GrantedAuthority> =
|
||||
claims["auth"].toString()
|
||||
.split(",")
|
||||
.map { SimpleGrantedAuthority(it) }
|
||||
|
||||
val principal = User(claims.subject, "", authorities)
|
||||
return UsernamePasswordAuthenticationToken(principal, "", authorities)
|
||||
}
|
||||
|
||||
// 3. 토큰 검증 (만료 여부, 위변조 여부 확인)
|
||||
fun validateToken(token: String): Boolean {
|
||||
try {
|
||||
Jwts.parser().verifyWith(key).build().parseSignedClaims(token)
|
||||
return true
|
||||
} catch (e: SecurityException) {
|
||||
// log.info("잘못된 JWT 서명입니다.")
|
||||
} catch (e: MalformedJwtException) {
|
||||
// log.info("잘못된 JWT 서명입니다.")
|
||||
} catch (e: ExpiredJwtException) {
|
||||
// log.info("만료된 JWT 토큰입니다.")
|
||||
} catch (e: UnsupportedJwtException) {
|
||||
// log.info("지원되지 않는 JWT 토큰입니다.")
|
||||
} catch (e: IllegalArgumentException) {
|
||||
// log.info("JWT 토큰이 잘못되었습니다.")
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun parseClaims(accessToken: String): Claims {
|
||||
return try {
|
||||
Jwts.parser().verifyWith(key).build().parseSignedClaims(accessToken).payload
|
||||
} catch (e: ExpiredJwtException) {
|
||||
e.claims
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package me.wypark.blogbackend.domain.auth
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.data.redis.core.RedisTemplate
|
||||
import org.springframework.stereotype.Repository
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
@Repository
|
||||
class RefreshTokenRepository(
|
||||
private val redisTemplate: RedisTemplate<String, String>,
|
||||
@Value("\${jwt.refresh-token-validity}") private val refreshTokenValidity: Long
|
||||
) {
|
||||
// 저장 (Key: Email, Value: RefreshToken)
|
||||
// RTR 핵심: 사용자가 로그인을 새로 하거나 토큰을 재발급 받을 때마다 덮어씌움
|
||||
fun save(email: String, refreshToken: String) {
|
||||
redisTemplate.opsForValue().set(
|
||||
"RT:$email",
|
||||
refreshToken,
|
||||
refreshTokenValidity,
|
||||
TimeUnit.MILLISECONDS
|
||||
)
|
||||
}
|
||||
|
||||
// 조회
|
||||
fun findByEmail(email: String): String? {
|
||||
return redisTemplate.opsForValue().get("RT:$email")
|
||||
}
|
||||
|
||||
// 삭제 (로그아웃 시)
|
||||
fun delete(email: String) {
|
||||
redisTemplate.delete("RT:$email")
|
||||
}
|
||||
}
|
||||
19
src/main/resources/application-prod.yml
Normal file
19
src/main/resources/application-prod.yml
Normal file
@@ -0,0 +1,19 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:postgresql://db:5432/blog_db
|
||||
username: wypark
|
||||
password: your_password
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
data:
|
||||
redis:
|
||||
host: redis
|
||||
port: 6379
|
||||
jwt:
|
||||
secret: "v3ryS3cr3tK3yF0rMyB10gPr0j3ctM4k3ItL0ng3rTh4n32Byt3s!!" # 32바이트 이상 필수
|
||||
access-token-validity: 1800000 # 30분 (ms)
|
||||
refresh-token-validity: 604800000 # 7일 (ms)
|
||||
5
src/main/resources/application.yml
Normal file
5
src/main/resources/application.yml
Normal file
@@ -0,0 +1,5 @@
|
||||
spring:
|
||||
application:
|
||||
name: blog-backend
|
||||
profiles:
|
||||
default: prod
|
||||
@@ -0,0 +1,13 @@
|
||||
package me.wypark.blogbackend
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.springframework.boot.test.context.SpringBootTest
|
||||
|
||||
@SpringBootTest
|
||||
class BlogBackendApplicationTests {
|
||||
|
||||
@Test
|
||||
fun contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user