diff --git a/spring-security/.gitattributes b/spring-security/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/spring-security/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/spring-security/.gitignore b/spring-security/.gitignore new file mode 100644 index 0000000..a93ec83 --- /dev/null +++ b/spring-security/.gitignore @@ -0,0 +1,38 @@ +HELP.md +.env +.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/ diff --git a/spring-security/README.md b/spring-security/README.md new file mode 100644 index 0000000..23c1c7e --- /dev/null +++ b/spring-security/README.md @@ -0,0 +1,92 @@ +# 과제명 + +JWT 인증 서버 + +## ⚙️ 실행 방법 + +1. MySQL 실행 후 데이터베이스 생성 + +```sql +CREATE DATABASE board_spring_db; +``` + +2. `application.properties`에 데이터베이스 정보 설정 + +```properties +spring.datasource.url=jdbc:mysql://localhost:3306/board_spring_db +spring.datasource.username=사용자명 +spring.datasource.password=비밀번호 +``` + +3. Spring Boot 프로젝트 실행 + +4. Postman을 이용하여 API 테스트 + +--- + +## 💡 작업 내용 + + +### JWT 인증 기능 구현 + +* 회원가입 기능 구현 +* 로그인 기능 구현 +* 로그인 성공 시 JWT 토큰 발급 +* Authorization Header를 통한 JWT 인증 +* Spring Security 적용 +* JwtAuthFilter를 이용한 사용자 인증 처리 + +### 예외 처리 + + +* 회원가입 시 사용자 중복 예외 처리 +* 로그인 시 사용자 미존재 예외 처리 +* 로그인 시 비밀번호 불일치 예외 처리 + + +--- + +## 📡 API 명세 + +### 인증 API + +| Method | URI | 설명 | +| ------ | -------------- | ------------ | +| POST | /auth/register | 회원가입 | +| POST | /auth/login | 로그인 및 JWT 발급 | + +### 게시글 API + +| Method | URI | 설명 | +| ------ | ----------- | --------- | +| POST | /posts | 게시글 생성 | +| GET | /posts | 게시글 목록 조회 | +| GET | /posts/{id} | 게시글 단건 조회 | +| PUT | /posts/{id} | 게시글 수정 | +| DELETE | /posts/{id} | 게시글 삭제 | + +--- + +## 🔐 JWT 인증 방식 + +1. 사용자가 회원가입을 진행한다. +2. 로그인 성공 시 JWT 토큰을 발급받는다. +3. 이후 요청 시 Authorization Header에 JWT 토큰을 포함한다. + +예시 + +```http +Authorization: Bearer eyJhbGciOiJIUzI1NiJ9... +``` + +4. JwtAuthFilter가 토큰을 검증한다. +5. 인증된 사용자만 게시글 API에 접근할 수 있다. + +--- + + + +## 🤔 느낀 점 / 어려웠던 점 + +* 기존 CRUD 게시판에 JWT 인증 기능을 추가하면서 Spring Security의 동작 원리를 이해할 수 있었습니다. +* JwtAuthFilter와 SecurityConfig를 직접 구현하며 인증과 인가 과정이 어떻게 이루어지는지 경험할 수 있었습니다. diff --git a/spring-security/build.gradle b/spring-security/build.gradle new file mode 100644 index 0000000..a6efc38 --- /dev/null +++ b/spring-security/build.gradle @@ -0,0 +1,44 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '4.0.6' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.project' +version = '0.0.1-SNAPSHOT' + +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-validation' + implementation 'org.springframework.boot:spring-boot-starter-webmvc' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + runtimeOnly 'com.mysql:mysql-connector-j' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test' + testImplementation 'org.springframework.boot:spring-boot-starter-validation-test' + testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' + testCompileOnly 'org.projectlombok:lombok' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testAnnotationProcessor 'org.projectlombok:lombok' + + implementation 'org.springframework.boot:spring-boot-starter-security' + + implementation 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/spring-security/gradle/wrapper/gradle-wrapper.jar b/spring-security/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 Binary files /dev/null and b/spring-security/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spring-security/gradle/wrapper/gradle-wrapper.properties b/spring-security/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df6a6ad --- /dev/null +++ b/spring-security/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/spring-security/gradlew b/spring-security/gradlew new file mode 100644 index 0000000..b9bb139 --- /dev/null +++ b/spring-security/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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 + + + +# 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" ) + + 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/spring-security/gradlew.bat b/spring-security/gradlew.bat new file mode 100644 index 0000000..24c62d5 --- /dev/null +++ b/spring-security/gradlew.bat @@ -0,0 +1,82 @@ +@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, and ensure extensions are enabled +setlocal EnableExtensions + +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 + +"%COMSPEC%" /c exit 1 + +: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 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/spring-security/images/Auth/errorPages/invalidPassword.png b/spring-security/images/Auth/errorPages/invalidPassword.png new file mode 100644 index 0000000..e1b8a08 Binary files /dev/null and b/spring-security/images/Auth/errorPages/invalidPassword.png differ diff --git a/spring-security/images/Auth/errorPages/userAlreadyExists.png b/spring-security/images/Auth/errorPages/userAlreadyExists.png new file mode 100644 index 0000000..9896606 Binary files /dev/null and b/spring-security/images/Auth/errorPages/userAlreadyExists.png differ diff --git a/spring-security/images/Auth/errorPages/userNotFound.png b/spring-security/images/Auth/errorPages/userNotFound.png new file mode 100644 index 0000000..4dc6446 Binary files /dev/null and b/spring-security/images/Auth/errorPages/userNotFound.png differ diff --git a/spring-security/images/Auth/login.png b/spring-security/images/Auth/login.png new file mode 100644 index 0000000..8383186 Binary files /dev/null and b/spring-security/images/Auth/login.png differ diff --git a/spring-security/images/Auth/posts.png b/spring-security/images/Auth/posts.png new file mode 100644 index 0000000..1c0fbdd Binary files /dev/null and b/spring-security/images/Auth/posts.png differ diff --git a/spring-security/images/Auth/register.png b/spring-security/images/Auth/register.png new file mode 100644 index 0000000..d675796 Binary files /dev/null and b/spring-security/images/Auth/register.png differ diff --git a/spring-security/images/CRUD/createPost.png b/spring-security/images/CRUD/createPost.png new file mode 100644 index 0000000..e6854dd Binary files /dev/null and b/spring-security/images/CRUD/createPost.png differ diff --git a/spring-security/images/CRUD/deletePost.png b/spring-security/images/CRUD/deletePost.png new file mode 100644 index 0000000..1a06440 Binary files /dev/null and b/spring-security/images/CRUD/deletePost.png differ diff --git a/spring-security/images/CRUD/errorPages/404NotFound/deletePost.png b/spring-security/images/CRUD/errorPages/404NotFound/deletePost.png new file mode 100644 index 0000000..67e9033 Binary files /dev/null and b/spring-security/images/CRUD/errorPages/404NotFound/deletePost.png differ diff --git a/spring-security/images/CRUD/errorPages/404NotFound/getPost.png b/spring-security/images/CRUD/errorPages/404NotFound/getPost.png new file mode 100644 index 0000000..a158c29 Binary files /dev/null and b/spring-security/images/CRUD/errorPages/404NotFound/getPost.png differ diff --git a/spring-security/images/CRUD/errorPages/404NotFound/updatePost.png b/spring-security/images/CRUD/errorPages/404NotFound/updatePost.png new file mode 100644 index 0000000..e7f3156 Binary files /dev/null and b/spring-security/images/CRUD/errorPages/404NotFound/updatePost.png differ diff --git a/spring-security/images/CRUD/errorPages/409Conflict/createPost.png b/spring-security/images/CRUD/errorPages/409Conflict/createPost.png new file mode 100644 index 0000000..2270992 Binary files /dev/null and b/spring-security/images/CRUD/errorPages/409Conflict/createPost.png differ diff --git a/spring-security/images/CRUD/getAllPosts.png b/spring-security/images/CRUD/getAllPosts.png new file mode 100644 index 0000000..b7a7c0f Binary files /dev/null and b/spring-security/images/CRUD/getAllPosts.png differ diff --git a/spring-security/images/CRUD/getPost.png b/spring-security/images/CRUD/getPost.png new file mode 100644 index 0000000..59ee001 Binary files /dev/null and b/spring-security/images/CRUD/getPost.png differ diff --git a/spring-security/images/CRUD/updatePost.png b/spring-security/images/CRUD/updatePost.png new file mode 100644 index 0000000..e5ea528 Binary files /dev/null and b/spring-security/images/CRUD/updatePost.png differ diff --git a/spring-security/images/DB/createPost.png b/spring-security/images/DB/createPost.png new file mode 100644 index 0000000..9b87bed Binary files /dev/null and b/spring-security/images/DB/createPost.png differ diff --git a/spring-security/images/DB/deletePost.png b/spring-security/images/DB/deletePost.png new file mode 100644 index 0000000..bf3e609 Binary files /dev/null and b/spring-security/images/DB/deletePost.png differ diff --git a/spring-security/images/DB/getAllPosts.png b/spring-security/images/DB/getAllPosts.png new file mode 100644 index 0000000..d7cc97c Binary files /dev/null and b/spring-security/images/DB/getAllPosts.png differ diff --git a/spring-security/images/DB/updatePost.png b/spring-security/images/DB/updatePost.png new file mode 100644 index 0000000..0f9f094 Binary files /dev/null and b/spring-security/images/DB/updatePost.png differ diff --git a/spring-security/settings.gradle b/spring-security/settings.gradle new file mode 100644 index 0000000..4c6d456 --- /dev/null +++ b/spring-security/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'boardDB' diff --git a/spring-security/src/main/java/com/project/boardDB/BoardDbApplication.java b/spring-security/src/main/java/com/project/boardDB/BoardDbApplication.java new file mode 100644 index 0000000..3feed82 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/BoardDbApplication.java @@ -0,0 +1,13 @@ +package com.project.boardDB; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BoardDbApplication { + + public static void main(String[] args) { + SpringApplication.run(BoardDbApplication.class, args); + } + +} diff --git a/spring-security/src/main/java/com/project/boardDB/config/AuditingConfig.java b/spring-security/src/main/java/com/project/boardDB/config/AuditingConfig.java new file mode 100644 index 0000000..6f0f2a3 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/config/AuditingConfig.java @@ -0,0 +1,12 @@ +package com.project.boardDB.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +// 설정 클래스 +@Configuration + +// JPA Auditing 기능 활성화 +@EnableJpaAuditing +public class AuditingConfig { +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/config/JwtUtil.java b/spring-security/src/main/java/com/project/boardDB/config/JwtUtil.java new file mode 100644 index 0000000..7009f73 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/config/JwtUtil.java @@ -0,0 +1,40 @@ +package com.project.boardDB.config; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.springframework.stereotype.Component; + +import java.nio.charset.StandardCharsets; +import java.util.Date; + +@Component +public class JwtUtil { + + // JWT에 사용할 비밀키 + private final String secretKey = "mySecretKeyForJwtTokenMySecretKeyForJwtToken"; + + // JWT 만료 시간 (1시간) + private static final long EXPIRATION_TIME = 60 * 60 * 1000L; + + // JWT 생성 + public String createToken(String username) { + return Jwts.builder() + .setSubject(username) + .setIssuedAt(new Date()) + .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) + .signWith(Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8))) + .compact(); + } + + // JWT에서 사용자 이름 추출 + public String getUsername(String token) { + Claims claims = Jwts.parserBuilder() + .setSigningKey(Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8))) + .build() + .parseClaimsJws(token) + .getBody(); + + return claims.getSubject(); + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/config/SecurityConfig.java b/spring-security/src/main/java/com/project/boardDB/config/SecurityConfig.java new file mode 100644 index 0000000..819307b --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/config/SecurityConfig.java @@ -0,0 +1,41 @@ +package com.project.boardDB.config; + +import com.project.boardDB.filter.JwtAuthFilter; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + + private final JwtAuthFilter jwtAuthFilter; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + return http + .csrf(csrf -> csrf.disable()) + .formLogin(form -> form.disable()) + .httpBasic(basic -> basic.disable()) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/auth/register", "/auth/login").permitAll() + .anyRequest().authenticated()) + .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) + .build(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/controller/AuthController.java b/spring-security/src/main/java/com/project/boardDB/controller/AuthController.java new file mode 100644 index 0000000..4435ba6 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/controller/AuthController.java @@ -0,0 +1,34 @@ +package com.project.boardDB.controller; + +import com.project.boardDB.dto.AuthRequest; +import com.project.boardDB.dto.LoginResponse; +import com.project.boardDB.dto.RegisterResponse; +import com.project.boardDB.service.AuthService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/auth") +@RequiredArgsConstructor +public class AuthController { + + private final AuthService authService; + + @PostMapping("/register") + public ResponseEntity register(@RequestBody AuthRequest request) { + RegisterResponse response = authService.register(request); + + return ResponseEntity + .status(HttpStatus.CREATED) + .body(response); + } + + @PostMapping("/login") + public ResponseEntity login(@RequestBody AuthRequest request) { + LoginResponse response = authService.login(request); + + return ResponseEntity.ok(response); + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/controller/PostController.java b/spring-security/src/main/java/com/project/boardDB/controller/PostController.java new file mode 100644 index 0000000..0ec71ec --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/controller/PostController.java @@ -0,0 +1,61 @@ +package com.project.boardDB.controller; + +import com.project.boardDB.dto.PostRequest; +import com.project.boardDB.dto.PostResponse; +import com.project.boardDB.service.PostService; +import lombok.RequiredArgsConstructor; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/posts") +@RequiredArgsConstructor +public class PostController { + + private final PostService postService; + + // 게시글 생성 + @PostMapping + public ResponseEntity createPost(@RequestBody PostRequest request) { + // 게시글 생성 + PostResponse response = postService.createPost(request); + // 게시글 생성 성공시 201 반환 + return ResponseEntity.status(HttpStatus.CREATED).body(response); + } + + // 게시글 전체 조회 + @GetMapping + public ResponseEntity> getAllPosts( + // 기본값: 10개씩 조회, id기준 내림차순 정렬 + @PageableDefault(size = 10, sort = "id", direction = Sort.Direction.DESC) + Pageable pageable + ) { + return ResponseEntity.ok(postService.getAllPosts(pageable)); + } + + // 게시글 단건 조회 + @GetMapping("/{id}") + public ResponseEntity getPost(@PathVariable Long id) { + return ResponseEntity.ok(postService.getPost(id)); + } + + // 게시글 수정 + @PutMapping("/{id}") + public ResponseEntity updatePost(@PathVariable Long id, @RequestBody PostRequest request) { + return ResponseEntity.ok(postService.updatePost(id, request)); + } + + // 게시글 삭제 + @DeleteMapping("/{id}") + public ResponseEntity deletePost(@PathVariable Long id) { + postService.deletePost(id); + // 게시글 삭제 성공 시 204 반환 + return ResponseEntity.noContent().build(); + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/dto/AuthRequest.java b/spring-security/src/main/java/com/project/boardDB/dto/AuthRequest.java new file mode 100644 index 0000000..f06ce4e --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/dto/AuthRequest.java @@ -0,0 +1,7 @@ +package com.project.boardDB.dto; + +public record AuthRequest( + String username, + String password +) { +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/dto/ErrorResponse.java b/spring-security/src/main/java/com/project/boardDB/dto/ErrorResponse.java new file mode 100644 index 0000000..b60c031 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/dto/ErrorResponse.java @@ -0,0 +1,31 @@ +package com.project.boardDB.dto; + +// 에러 응답 DTO +// record: 데이터를 저장하고 전달하기 위한 불변 객체 +public record ErrorResponse( + String message, + int status + + /* 원래 이거임 + public final class ErrorResponse { + + private final String message; + private final int status; + + public ErrorResponse(String message, int status) { + this.message = message; + this.status = status; + } + + public String message() { + return message; + } + + public int status() { + return status; + } +}*/ + +){ + +} diff --git a/spring-security/src/main/java/com/project/boardDB/dto/LoginResponse.java b/spring-security/src/main/java/com/project/boardDB/dto/LoginResponse.java new file mode 100644 index 0000000..ac5723a --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/dto/LoginResponse.java @@ -0,0 +1,6 @@ +package com.project.boardDB.dto; + +public record LoginResponse( + String token +) { +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/dto/PostRequest.java b/spring-security/src/main/java/com/project/boardDB/dto/PostRequest.java new file mode 100644 index 0000000..6593d69 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/dto/PostRequest.java @@ -0,0 +1,6 @@ +package com.project.boardDB.dto; + +public record PostRequest ( + String title, + String content +){} diff --git a/spring-security/src/main/java/com/project/boardDB/dto/PostResponse.java b/spring-security/src/main/java/com/project/boardDB/dto/PostResponse.java new file mode 100644 index 0000000..25d551c --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/dto/PostResponse.java @@ -0,0 +1,12 @@ +package com.project.boardDB.dto; + +import java.time.LocalDateTime; + +public record PostResponse( + Long id, + String title, + String content, + LocalDateTime createdAt + +) { +} diff --git a/spring-security/src/main/java/com/project/boardDB/dto/RegisterResponse.java b/spring-security/src/main/java/com/project/boardDB/dto/RegisterResponse.java new file mode 100644 index 0000000..a728539 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/dto/RegisterResponse.java @@ -0,0 +1,7 @@ +package com.project.boardDB.dto; + +public record RegisterResponse( + Long id, + String username +) { +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/entity/BaseEntity.java b/spring-security/src/main/java/com/project/boardDB/entity/BaseEntity.java new file mode 100644 index 0000000..71995a7 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/entity/BaseEntity.java @@ -0,0 +1,29 @@ +package com.project.boardDB.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Getter + +// 공통 필드를 여러 엔티티에서 상속받아 사용할 수 있도록 설정 +// BaseEntity 자체는 테이블로 생성되지 않음 +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) // 이 엔티티의 저장, 수정을 누가 언제 어떻게 한건지 알수있는 리스너를 등록 +public class BaseEntity { + + // 생성 시간 + @CreatedDate + @Column(nullable = false, updatable = false) + private LocalDateTime createdAt; + + // 수정 시간 + @LastModifiedDate + private LocalDateTime modifiedAt; +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/entity/Post.java b/spring-security/src/main/java/com/project/boardDB/entity/Post.java new file mode 100644 index 0000000..4f47a60 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/entity/Post.java @@ -0,0 +1,30 @@ +package com.project.boardDB.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Builder +@Getter +public class Post extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, unique = true, length = 100) + private String title; + + @Column(nullable = false) + private String content; + + public void update(String title, String content) { + this.title = title; + this.content = content; + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/entity/User.java b/spring-security/src/main/java/com/project/boardDB/entity/User.java new file mode 100644 index 0000000..114b834 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/entity/User.java @@ -0,0 +1,27 @@ +package com.project.boardDB.entity; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor +@Table(name = "users") +public class User extends BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false, unique = true, length = 50) + private String username; + + @Column(nullable = false) + private String password; + + public User(String username, String password) { + this.username = username; + this.password = password; + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/exception/DuplicateTitleException.java b/spring-security/src/main/java/com/project/boardDB/exception/DuplicateTitleException.java new file mode 100644 index 0000000..a1eb7a6 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/exception/DuplicateTitleException.java @@ -0,0 +1,8 @@ +package com.project.boardDB.exception; + +public class DuplicateTitleException extends RuntimeException { + public DuplicateTitleException() { + super("이미 존재하는 제목입니다."); + + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/exception/GlobalExceptionHandler.java b/spring-security/src/main/java/com/project/boardDB/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..3a91d46 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/exception/GlobalExceptionHandler.java @@ -0,0 +1,54 @@ +package com.project.boardDB.exception; + +import com.project.boardDB.dto.ErrorResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +// 전역 예외 처리 클래스 +// Controller에서 발생한 예외를 한 곳에서 처리 +@RestControllerAdvice +public class GlobalExceptionHandler { + // 게시글을 찾을 수 없을 때 발생하는 예외 처리 + @ExceptionHandler(PostNotFoundException.class) + public ResponseEntity handlePostNotFoundException(PostNotFoundException e) { + return ResponseEntity + .status(HttpStatus.NOT_FOUND) + .body(new ErrorResponse( + e.getMessage(), + HttpStatus.NOT_FOUND.value())); + } + // 제목이 중복될 때 발생하는 예외 처리 + @ExceptionHandler(DuplicateTitleException.class) + public ResponseEntity handleDuplicateTitleException(DuplicateTitleException e) { + return ResponseEntity + .status(HttpStatus.CONFLICT) + .body(new ErrorResponse( + e.getMessage(), + HttpStatus.CONFLICT.value())); + } + @ExceptionHandler(UserAlreadyExistsException.class) + public ResponseEntity handleUserAlreadyExistsException(UserAlreadyExistsException e) { + return ResponseEntity + .status(HttpStatus.CONFLICT) + .body(new ErrorResponse( + e.getMessage(), + HttpStatus.CONFLICT.value())); + } + @ExceptionHandler(UserNotFoundException.class) + public ResponseEntity handleUserNotFoundException(UserNotFoundException e) { + return ResponseEntity + .status(HttpStatus.NOT_FOUND) + .body(new ErrorResponse( + e.getMessage(), + HttpStatus.NOT_FOUND.value())); + } + + @ExceptionHandler(InvalidPasswordException.class) + public ResponseEntity handleInvalidPasswordException(InvalidPasswordException e) { + return ResponseEntity + .status(HttpStatus.UNAUTHORIZED) + .body(new ErrorResponse(e.getMessage(), HttpStatus.UNAUTHORIZED.value())); + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/exception/InvalidPasswordException.java b/spring-security/src/main/java/com/project/boardDB/exception/InvalidPasswordException.java new file mode 100644 index 0000000..8e73f38 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/exception/InvalidPasswordException.java @@ -0,0 +1,8 @@ +package com.project.boardDB.exception; + +public class InvalidPasswordException extends RuntimeException { + + public InvalidPasswordException() { + super("비밀번호가 일치하지 않습니다."); + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/exception/PostNotFoundException.java b/spring-security/src/main/java/com/project/boardDB/exception/PostNotFoundException.java new file mode 100644 index 0000000..706cff5 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/exception/PostNotFoundException.java @@ -0,0 +1,7 @@ +package com.project.boardDB.exception; + +public class PostNotFoundException extends RuntimeException { + public PostNotFoundException() { + super("게시글을 찾을 수 없습니다."); + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/exception/UserAlreadyExistsException.java b/spring-security/src/main/java/com/project/boardDB/exception/UserAlreadyExistsException.java new file mode 100644 index 0000000..466d15e --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/exception/UserAlreadyExistsException.java @@ -0,0 +1,8 @@ +package com.project.boardDB.exception; + +public class UserAlreadyExistsException extends RuntimeException { + + public UserAlreadyExistsException() { + super("이미 존재하는 사용자입니다."); + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/exception/UserNotFoundException.java b/spring-security/src/main/java/com/project/boardDB/exception/UserNotFoundException.java new file mode 100644 index 0000000..abea9d8 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/exception/UserNotFoundException.java @@ -0,0 +1,8 @@ +package com.project.boardDB.exception; + +public class UserNotFoundException extends RuntimeException { + + public UserNotFoundException() { + super("사용자를 찾을 수 없습니다."); + } +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/filter/JwtAuthFilter.java b/spring-security/src/main/java/com/project/boardDB/filter/JwtAuthFilter.java new file mode 100644 index 0000000..557c1a7 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/filter/JwtAuthFilter.java @@ -0,0 +1,49 @@ +package com.project.boardDB.filter; + +import com.project.boardDB.config.JwtUtil; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.Collections; + +@Component +@RequiredArgsConstructor +public class JwtAuthFilter extends OncePerRequestFilter { + + private final JwtUtil jwtUtil; + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + String authHeader = request.getHeader("Authorization"); + + if (authHeader != null && authHeader.startsWith("Bearer ")) { + String token = authHeader.substring(7); + String username = jwtUtil.getUsername(token); + + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken( + username, + null, + Collections.emptyList()); + + SecurityContextHolder.getContext() + .setAuthentication(authentication); + } + + filterChain.doFilter(request, response); + } + + +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/repository/PostRepository.java b/spring-security/src/main/java/com/project/boardDB/repository/PostRepository.java new file mode 100644 index 0000000..16ee84e --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/repository/PostRepository.java @@ -0,0 +1,12 @@ +package com.project.boardDB.repository; + +import com.project.boardDB.entity.Post; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PostRepository extends JpaRepository { + + // 제목 중복 확인 + boolean existsByTitle(String title); +} diff --git a/spring-security/src/main/java/com/project/boardDB/repository/UserRepository.java b/spring-security/src/main/java/com/project/boardDB/repository/UserRepository.java new file mode 100644 index 0000000..5bdb6f3 --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/repository/UserRepository.java @@ -0,0 +1,13 @@ +package com.project.boardDB.repository; + +import com.project.boardDB.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + + Optional findByUsername(String username); + + boolean existsByUsername(String username); +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/service/AuthService.java b/spring-security/src/main/java/com/project/boardDB/service/AuthService.java new file mode 100644 index 0000000..b4db3ca --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/service/AuthService.java @@ -0,0 +1,80 @@ +package com.project.boardDB.service; + +import com.project.boardDB.config.JwtUtil; +import com.project.boardDB.dto.AuthRequest; +import com.project.boardDB.dto.LoginResponse; +import com.project.boardDB.dto.RegisterResponse; +import com.project.boardDB.entity.User; +import com.project.boardDB.exception.InvalidPasswordException; +import com.project.boardDB.exception.UserAlreadyExistsException; +import com.project.boardDB.exception.UserNotFoundException; +import com.project.boardDB.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class AuthService { + + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final JwtUtil jwtUtil; + + // 회원가입 + @Transactional + public RegisterResponse register(AuthRequest request) { + + // 아이디 중복 확인 + if (userRepository.existsByUsername(request.username())) { + throw new UserAlreadyExistsException(); + } + + // 비밀번호 암호화 + String encodedPassword = passwordEncoder.encode(request.password()); + + // 회원 생성 + User user = new User(request.username(), encodedPassword); + + // DB 저장 + User savedUser = userRepository.save(user); + + // DTO 변환 후 반환 + return changeToRegisterResponse(savedUser); + } + + // 로그인 + public LoginResponse login(AuthRequest request) { + + // 회원 조회 + User user = userRepository.findByUsername(request.username()) + .orElseThrow(UserNotFoundException::new); + + // 비밀번호 확인 + if (!passwordEncoder.matches(request.password(), user.getPassword())) { + throw new InvalidPasswordException(); + } + + // JWT 토큰 생성 + String token = jwtUtil.createToken(user.getUsername()); + + // DTO 변환 후 반환 + return changeToLoginResponse(token); + } + + // Entity -> DTO 변환 + private RegisterResponse changeToRegisterResponse(User user) { + return new RegisterResponse( + user.getId(), + user.getUsername() + ); + } + + // Token -> DTO 변환 + private LoginResponse changeToLoginResponse(String token) { + return new LoginResponse(token); + } + +} \ No newline at end of file diff --git a/spring-security/src/main/java/com/project/boardDB/service/PostService.java b/spring-security/src/main/java/com/project/boardDB/service/PostService.java new file mode 100644 index 0000000..2f9edbc --- /dev/null +++ b/spring-security/src/main/java/com/project/boardDB/service/PostService.java @@ -0,0 +1,106 @@ +package com.project.boardDB.service; + +import com.project.boardDB.dto.PostRequest; +import com.project.boardDB.dto.PostResponse; +import com.project.boardDB.entity.Post; +import com.project.boardDB.exception.DuplicateTitleException; +import com.project.boardDB.exception.PostNotFoundException; +import com.project.boardDB.repository.PostRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class PostService { + + private final PostRepository postRepository; + + // 게시글 생성 + @Transactional + public PostResponse createPost(PostRequest request) { + + // 제목 중복 확인 + if (postRepository.existsByTitle(request.title())) { + throw new DuplicateTitleException(); + } + + // 게시글 객체 생성 + Post post = Post.builder() + .title(request.title()) + .content(request.content()) + .build(); + + // DB 저장 + Post savedPost = postRepository.save(post); + + // DTO 변환 후 반환 + return changeToResponse(savedPost); + } + + // 게시글 전체 조회 (페이징 적용) + public Page getAllPosts(Pageable pageable) { + + // 페이지 정보와 함께 게시글 조회 + Page postPage = postRepository.findAll(pageable); + // Entity -> DTO 변환 + return postPage.map(post -> changeToResponse(post)); + } + + // 게시글 단건 조회 + public PostResponse getPost(Long id) { + + // 게시글 조회 + Post post = postRepository.findById(id) + .orElseThrow(() -> new PostNotFoundException()); + // DTO 변환 후 반환 + return changeToResponse(post); + } + + // 게시글 수정 + @Transactional + public PostResponse updatePost(Long id, PostRequest request) { + + // 수정할 게시글 조회 + Post post = postRepository.findById(id).orElseThrow(() -> new PostNotFoundException()); + + // 제목이 변경된 경우에만 중복 검사 + if (postRepository.existsByTitle(request.title()) && !post.getTitle().equals(request.title())) { + throw new DuplicateTitleException(); + } + + // 게시글 수정 + post.update(request.title(), request.content()); + // DTO 변환 후 반환 + return changeToResponse(post); + } + + // 게시글 삭제 + @Transactional + public void deletePost(Long id) { + + // 삭제할 게시글 조회 + Post post = postRepository.findById(id).orElseThrow(() -> new PostNotFoundException()); + + // 게시글 삭제 + postRepository.delete(post); + } + + // Entity -> DTO 변환 + private PostResponse changeToResponse(Post post) { + + return new PostResponse( + post.getId(), + post.getTitle(), + post.getContent(), + post.getCreatedAt() + ); + } + + + + +} \ No newline at end of file diff --git a/spring-security/src/main/resources/application.properties b/spring-security/src/main/resources/application.properties new file mode 100644 index 0000000..3dbf310 --- /dev/null +++ b/spring-security/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.application.name=boardDB + +# import .env.properties file +spring.config.import=optional:file:.env[.properties] + +# Database Settings +spring.datasource.url=${DATABASE_URL} +spring.datasource.username=${DATABASE_USERNAME} +spring.datasource.password=${DATABASE_PASSWORD} +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +# JPA + Hibernate Settings +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect diff --git a/spring-security/src/test/java/com/project/boardDB/BoardDbApplicationTests.java b/spring-security/src/test/java/com/project/boardDB/BoardDbApplicationTests.java new file mode 100644 index 0000000..5528a2e --- /dev/null +++ b/spring-security/src/test/java/com/project/boardDB/BoardDbApplicationTests.java @@ -0,0 +1,13 @@ +package com.project.boardDB; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class BoardDbApplicationTests { + + @Test + void contextLoads() { + } + +}