diff --git a/springsecurity/.gitattributes b/springsecurity/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/springsecurity/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/springsecurity/.gitignore b/springsecurity/.gitignore new file mode 100644 index 0000000..eeff19a --- /dev/null +++ b/springsecurity/.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/ + +.env +.idea/ \ No newline at end of file diff --git a/springsecurity/Docs/Post/404NotFound.png b/springsecurity/Docs/Post/404NotFound.png new file mode 100644 index 0000000..058bfa7 Binary files /dev/null and b/springsecurity/Docs/Post/404NotFound.png differ diff --git a/springsecurity/Docs/Post/deletePost.png b/springsecurity/Docs/Post/deletePost.png new file mode 100644 index 0000000..473d6bb Binary files /dev/null and b/springsecurity/Docs/Post/deletePost.png differ diff --git a/springsecurity/Docs/Post/newPost.png b/springsecurity/Docs/Post/newPost.png new file mode 100644 index 0000000..85f528b Binary files /dev/null and b/springsecurity/Docs/Post/newPost.png differ diff --git a/springsecurity/Docs/Post/updatePost.png b/springsecurity/Docs/Post/updatePost.png new file mode 100644 index 0000000..eaa19e2 Binary files /dev/null and b/springsecurity/Docs/Post/updatePost.png differ diff --git a/springsecurity/Docs/UserDB.png b/springsecurity/Docs/UserDB.png new file mode 100644 index 0000000..369ee11 Binary files /dev/null and b/springsecurity/Docs/UserDB.png differ diff --git a/springsecurity/Docs/User_already_exist.png b/springsecurity/Docs/User_already_exist.png new file mode 100644 index 0000000..d5354ca Binary files /dev/null and b/springsecurity/Docs/User_already_exist.png differ diff --git a/springsecurity/Docs/login.png b/springsecurity/Docs/login.png new file mode 100644 index 0000000..6659bf5 Binary files /dev/null and b/springsecurity/Docs/login.png differ diff --git a/springsecurity/Docs/register.png b/springsecurity/Docs/register.png new file mode 100644 index 0000000..91c00c4 Binary files /dev/null and b/springsecurity/Docs/register.png differ diff --git a/springsecurity/Docs/token.png b/springsecurity/Docs/token.png new file mode 100644 index 0000000..ccc80b8 Binary files /dev/null and b/springsecurity/Docs/token.png differ diff --git a/springsecurity/README.md b/springsecurity/README.md new file mode 100644 index 0000000..0650a95 --- /dev/null +++ b/springsecurity/README.md @@ -0,0 +1,43 @@ +# 과제명 +JWT 인증 서버 + +## ⚙️ 실행 방법 +1. mysql 생성 후 SCHEMAS 생성 +2. .env 에 DB정보 입력 +3. SpringsecurityApplication 실행 + +## 💡 작업 내용 +- 회원가입 - POST /auth/register +- 로그인 - POST /auth/login → JWT 토큰 수령 +- GET /posts (protected) → Authorization: Bearer {token} + +# API 명세 + +| Method | URI | 설명 | +|--------|---------------|------| +| POST | /post | 게시글 생성 | +| GET | /post | 게시글 목록 조회 | +| GET | /post/{id} | 게시글 단건 조회 | +| PUT | /post/{id} | 게시글 수정 | +| DELETE | /post/{id} | 게시글 삭제 | +| POST | auth/register | 회원가입| +| POST | auth/login | JWT 토큰 수령 | + + + + + +# API 성공 세부 사항 +- 200-1: 게시물 등록 성공 +- 200-2: 게시물 단건 조회 선공 +- 200-3: 게시물 수정 조회 선공 +- 200-4: 게시물 삭제 선공 +- 200-5: 게시물 전체 조회 선공 +- 200-6 : 로그인 성공 + +## 🤔 느낀 점 / 어려웠던 점 +- 전체적인 회원가입과 로그인의 구조에 대해 알게 되었습니다.. +- 하지만 refresh 토큰과 access 토큰을 사용해서 보안을 강화 하는법과 예외처리하는 법을 더욱 자세히 작성해야할거같습니다(시험끝나고 보안하겠습니다) +- spring security 가 Dispatcher Servlet 앞단에 어떻게 작동하는지에 대해 집중하여 학습해보았습니다. +- 헷갈리는 것도 많고 했지만 많은 자료들을 찾아보며 작성하였습니다. +- 예외처리가 많이 부족하게 되어있습니다... \ No newline at end of file diff --git a/springsecurity/build.gradle b/springsecurity/build.gradle new file mode 100644 index 0000000..b2ba997 --- /dev/null +++ b/springsecurity/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-security' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-starter-webmvc' + implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6' + 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-security-test' + testImplementation 'org.springframework.boot:spring-boot-starter-thymeleaf-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 'io.jsonwebtoken:jjwt-api:0.12.3' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.3' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.3' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/springsecurity/gradle/wrapper/gradle-wrapper.jar b/springsecurity/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 Binary files /dev/null and b/springsecurity/gradle/wrapper/gradle-wrapper.jar differ diff --git a/springsecurity/gradle/wrapper/gradle-wrapper.properties b/springsecurity/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..df6a6ad --- /dev/null +++ b/springsecurity/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/springsecurity/gradlew b/springsecurity/gradlew new file mode 100644 index 0000000..b9bb139 --- /dev/null +++ b/springsecurity/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/springsecurity/gradlew.bat b/springsecurity/gradlew.bat new file mode 100644 index 0000000..24c62d5 --- /dev/null +++ b/springsecurity/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/springsecurity/settings.gradle b/springsecurity/settings.gradle new file mode 100644 index 0000000..06971a6 --- /dev/null +++ b/springsecurity/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'springsecurity' diff --git a/springsecurity/src/main/java/com/project/springsecurity/Controller/AuthController.java b/springsecurity/src/main/java/com/project/springsecurity/Controller/AuthController.java new file mode 100644 index 0000000..d798cd7 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/Controller/AuthController.java @@ -0,0 +1,23 @@ +package com.project.springsecurity.Controller; + +import com.project.springsecurity.dto.JoinDto; +import com.project.springsecurity.global.RsData.RsData; +import com.project.springsecurity.service.JoinService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/auth") +@RequiredArgsConstructor +public class AuthController { + + private final JoinService joinService; + + @PostMapping("/register") + public ResponseEntity> joinProcess(@RequestBody JoinDto joinDto) { + joinService.joinProcess(joinDto); + RsData rsData = new RsData<>("201-6", "회원가입이 완료되었습니다"); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/Controller/PostController.java b/springsecurity/src/main/java/com/project/springsecurity/Controller/PostController.java new file mode 100644 index 0000000..ca32476 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/Controller/PostController.java @@ -0,0 +1,62 @@ +package com.project.springsecurity.Controller; + +import com.project.springsecurity.dto.PostNewRequest; +import com.project.springsecurity.dto.PostResponse; +import com.project.springsecurity.dto.PostUpdateRequest; +import com.project.springsecurity.global.RsData.RsData; +import com.project.springsecurity.service.PostService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/post") +@RequiredArgsConstructor +public class PostController { + private final PostService postService; + + // 게시물 등록 + @PostMapping + public ResponseEntity> newPost(@RequestBody PostNewRequest requestDto){ + PostResponse postResponse = postService.newPost(requestDto); + RsData rsData = new RsData<>("201-1","게시물이 등록되었습니다",postResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + + // 게시물 단건 조회 + @GetMapping("/{id}") + public ResponseEntity> onePost(@PathVariable Long id){ + PostResponse postResponse = postService.findOnePost(id); + RsData rsData = new RsData<>("200-2","한개의 게시물 조회가 완료되었습니다",postResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + //게시물 수정 + @PutMapping("/{id}") + public ResponseEntity> updatePost(@PathVariable Long id, @RequestBody PostUpdateRequest requestDto){ + PostResponse postResponse = postService.updatePost(requestDto,id); + RsData rsData = new RsData<>("200-3","게시물이 정상적으로 수정되었습니다",postResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + + // 게시물 삭제 + @DeleteMapping("/{id}") + public ResponseEntity> deletePost(@PathVariable Long id ){ + postService.deletePost(id); + + RsData rsData = new RsData<>("200-4", "게시물이 정상적으로 삭제되었습니다"); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + // 전체 조회하기 (페이징) + @GetMapping + public ResponseEntity>> getPost( + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int size) { + Page postResponse = postService.getPostWithPaging(page, size); + RsData> rsData = new RsData<>("200-5", (page + 1)+"페이지 조회가 완료되었습니다", postResponse); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } + +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/SpringsecurityApplication.java b/springsecurity/src/main/java/com/project/springsecurity/SpringsecurityApplication.java new file mode 100644 index 0000000..f220f35 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/SpringsecurityApplication.java @@ -0,0 +1,15 @@ +package com.project.springsecurity; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; + +@SpringBootApplication +@EnableJpaAuditing +public class SpringsecurityApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringsecurityApplication.class, args); + } + +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/config/JWTUtil.java b/springsecurity/src/main/java/com/project/springsecurity/config/JWTUtil.java new file mode 100644 index 0000000..dd13b1e --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/config/JWTUtil.java @@ -0,0 +1,47 @@ +package com.project.springsecurity.config; + +import io.jsonwebtoken.Jwts; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Date; + +@Component +public class JWTUtil { + + private SecretKey secretKey; + + public JWTUtil(@Value("${spring.jwt.secret}") String secret) { + + secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm()); + } + + public String getUsername(String token) { + + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); + } + + public String getRole(String token) { + + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); + } + + public Boolean isExpired(String token) { + + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); + } + + public String createJwt(String username, String role, Long expiredMs) { + + return Jwts.builder() + .claim("username", username) + .claim("role", role) + .issuedAt(new Date(System.currentTimeMillis())) + .expiration(new Date(System.currentTimeMillis() + expiredMs)) + .signWith(secretKey) + .compact(); + } +} \ No newline at end of file diff --git a/springsecurity/src/main/java/com/project/springsecurity/config/SecurityConfig.java b/springsecurity/src/main/java/com/project/springsecurity/config/SecurityConfig.java new file mode 100644 index 0000000..f12fd35 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/config/SecurityConfig.java @@ -0,0 +1,75 @@ +package com.project.springsecurity.config; + + +import com.project.springsecurity.jwt.JWTFilter; +import com.project.springsecurity.jwt.LoginFilter; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +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.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + private final AuthenticationConfiguration authenticationConfiguration; + private final JWTUtil jwtUtil; + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + + return new BCryptPasswordEncoder(); + } + + @Bean + public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { + + return configuration.getAuthenticationManager(); + } + + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + //csrf disable + http + .csrf((auth) -> auth.disable()); + + //From 로그인 방식 disable + http + .formLogin((auth) -> auth.disable()); + + //http basic 인증 방식 disable + http + .httpBasic((auth) -> auth.disable()); + + //경로별 인가 작업 + http + .authorizeHttpRequests((auth) -> auth + .requestMatchers("/auth/register", "/auth/login").permitAll() + .requestMatchers("/post").hasRole("USER") + .anyRequest().authenticated()); + + http + .addFilterBefore(new JWTFilter(jwtUtil), LoginFilter.class); + + http + .addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration),jwtUtil), UsernamePasswordAuthenticationFilter.class); + + //세션 설정(사용안함) + http + .sessionManagement((session) -> session + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + + return http.build(); + } + + +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/dto/CustomUserDetails.java b/springsecurity/src/main/java/com/project/springsecurity/dto/CustomUserDetails.java new file mode 100644 index 0000000..41aa456 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/dto/CustomUserDetails.java @@ -0,0 +1,70 @@ +package com.project.springsecurity.dto; + +import com.project.springsecurity.entity.UserEntity; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import java.util.ArrayList; +import java.util.Collection; + + + +public class CustomUserDetails implements UserDetails { + private final UserEntity userEntity; + + public CustomUserDetails(UserEntity userEntity) { + this.userEntity = userEntity; + } + + @Override + public Collection getAuthorities() { + + Collection collection = new ArrayList<>(); + + collection.add(new GrantedAuthority() { + + @Override + public String getAuthority() { + + return userEntity.getRole(); + } + }); + + return collection; + } + + @Override + public String getPassword() { + + return userEntity.getPassword(); + } + + @Override + public String getUsername() { + + return userEntity.getUsername(); + } + + @Override + public boolean isAccountNonExpired() { + + return true; + } + + @Override + public boolean isAccountNonLocked() { + + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + + return true; + } + + @Override + public boolean isEnabled() { + + return true; + } +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/dto/JoinDto.java b/springsecurity/src/main/java/com/project/springsecurity/dto/JoinDto.java new file mode 100644 index 0000000..b10a0f6 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/dto/JoinDto.java @@ -0,0 +1,10 @@ +package com.project.springsecurity.dto; + + + +public record JoinDto( + String username, + String password + +) { +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/dto/LoginDto.java b/springsecurity/src/main/java/com/project/springsecurity/dto/LoginDto.java new file mode 100644 index 0000000..2e530e5 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/dto/LoginDto.java @@ -0,0 +1,10 @@ +package com.project.springsecurity.dto; + +import lombok.Getter; + + +public record LoginDto( + String username, + String password +) { +} \ No newline at end of file diff --git a/springsecurity/src/main/java/com/project/springsecurity/dto/PostNewRequest.java b/springsecurity/src/main/java/com/project/springsecurity/dto/PostNewRequest.java new file mode 100644 index 0000000..ca620ee --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/dto/PostNewRequest.java @@ -0,0 +1,7 @@ +package com.project.springsecurity.dto; + +public record PostNewRequest( + String title, + String content +) { +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/dto/PostResponse.java b/springsecurity/src/main/java/com/project/springsecurity/dto/PostResponse.java new file mode 100644 index 0000000..b90aa67 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/dto/PostResponse.java @@ -0,0 +1,14 @@ +package com.project.springsecurity.dto; + +import lombok.Builder; + +import java.time.LocalDateTime; + +@Builder +public record PostResponse( + Long id, + String title, + String content, + String username, + LocalDateTime createdAt +) {} \ No newline at end of file diff --git a/springsecurity/src/main/java/com/project/springsecurity/dto/PostUpdateRequest.java b/springsecurity/src/main/java/com/project/springsecurity/dto/PostUpdateRequest.java new file mode 100644 index 0000000..b401107 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/dto/PostUpdateRequest.java @@ -0,0 +1,7 @@ +package com.project.springsecurity.dto; + +public record PostUpdateRequest( + String title, + String content +) { +} \ No newline at end of file diff --git a/springsecurity/src/main/java/com/project/springsecurity/entity/Post.java b/springsecurity/src/main/java/com/project/springsecurity/entity/Post.java new file mode 100644 index 0000000..06a3b25 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/entity/Post.java @@ -0,0 +1,44 @@ +package com.project.springsecurity.entity; + +import com.project.springsecurity.global.BaseTimeEntity; +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Table(name = "board") +public class Post extends BaseTimeEntity { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "board_id") + private Long id; + + @Column(name = "title", length = 200, nullable = false) + private String title; + + @Column(name = "content", length = 500, nullable = false) + private String content; + + // String userName 제거 → UserEntity로 대체 + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private UserEntity user; + + + @Builder + public Post(String title, String content, UserEntity user) { + this.title = title; + this.content = content; + this.user = user; + } + + public void update(String title, String content) { + this.title = title; + this.content = content; + } +} + diff --git a/springsecurity/src/main/java/com/project/springsecurity/entity/UserEntity.java b/springsecurity/src/main/java/com/project/springsecurity/entity/UserEntity.java new file mode 100644 index 0000000..c330428 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/entity/UserEntity.java @@ -0,0 +1,33 @@ +package com.project.springsecurity.entity; + + +import jakarta.persistence.*; +import lombok.*; + + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Table(name = "user") +public class UserEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "username") + private String username; + + @Column(name = "password") + private String password; + + @Column(name = "role") + private String role; + + @Builder + public UserEntity(String username ,String password, String role ){ + this.username = username; + this.password = password; + this.role = role; + } +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/global/BaseTimeEntity.java b/springsecurity/src/main/java/com/project/springsecurity/global/BaseTimeEntity.java new file mode 100644 index 0000000..7e5739e --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/global/BaseTimeEntity.java @@ -0,0 +1,17 @@ +package com.project.springsecurity.global; + +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public class BaseTimeEntity { + @CreatedDate + private LocalDateTime createAt; +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/global/RsData/RsData.java b/springsecurity/src/main/java/com/project/springsecurity/global/RsData/RsData.java new file mode 100644 index 0000000..01c90ee --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/global/RsData/RsData.java @@ -0,0 +1,14 @@ +package com.project.springsecurity.global.RsData; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public record RsData(String resultCode, @JsonIgnore int statusCode, String message, T data) { + + public RsData(String resultCode, String message){ + this(resultCode,message,null); + } + + public RsData(String resultCode, String message, T data){ + this(resultCode,Integer.parseInt(resultCode.split("-", 2)[0]),message,data ); + } +} \ No newline at end of file diff --git a/springsecurity/src/main/java/com/project/springsecurity/global/exception/GlobalExceptionHandler.java b/springsecurity/src/main/java/com/project/springsecurity/global/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..fe07c7e --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/global/exception/GlobalExceptionHandler.java @@ -0,0 +1,34 @@ +package com.project.springsecurity.global.exception; + +import com.project.springsecurity.global.RsData.RsData; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.NoSuchElementException; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity> handleIllegalArgumentException(IllegalArgumentException e) { + + RsData rsData = new RsData<>("404-1", e.getMessage()); // 메시지 그대로 사용 + + return ResponseEntity + .status(rsData.statusCode()) + .body(rsData); + } +// 중복 회원 + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity> handleIllegalStateException(IllegalStateException e) { + RsData rsData = new RsData<>("409-1", e.getMessage()); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } +// 찾을 수 없음 + @ExceptionHandler(NoSuchElementException.class) + public ResponseEntity> handleNoSuchElementException(NoSuchElementException e) { + RsData rsData = new RsData<>("404-1", e.getMessage()); + return ResponseEntity.status(rsData.statusCode()).body(rsData); + } +} \ No newline at end of file diff --git a/springsecurity/src/main/java/com/project/springsecurity/jwt/JWTFilter.java b/springsecurity/src/main/java/com/project/springsecurity/jwt/JWTFilter.java new file mode 100644 index 0000000..fa27c21 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/jwt/JWTFilter.java @@ -0,0 +1,61 @@ +package com.project.springsecurity.jwt; + +import com.project.springsecurity.config.JWTUtil; +import com.project.springsecurity.dto.CustomUserDetails; +import com.project.springsecurity.entity.UserEntity; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class JWTFilter extends OncePerRequestFilter { + + private final JWTUtil jwtUtil; + + public JWTFilter(JWTUtil jwtUtil) { + this.jwtUtil = jwtUtil; + } + + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + + + String authorization= request.getHeader("Authorization"); + + + if (authorization == null || !authorization.startsWith("Bearer ")) { + filterChain.doFilter(request, response); + + return; + } + + String token = authorization.split(" ")[1]; + + if (jwtUtil.isExpired(token)) { + filterChain.doFilter(request, response); + return; + } + + String username = jwtUtil.getUsername(token); + String role = jwtUtil.getRole(token); + + UserEntity userEntity = UserEntity.builder().username(username).password("temppassword").role(role) + .build(); + + CustomUserDetails customUserDetails = new CustomUserDetails(userEntity); + + //스프링 시큐리티 인증 토큰 생성 + Authentication authToken = new UsernamePasswordAuthenticationToken(customUserDetails, null, customUserDetails.getAuthorities()); + //세션에 사용자 등록 + SecurityContextHolder.getContext().setAuthentication(authToken); + + filterChain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/springsecurity/src/main/java/com/project/springsecurity/jwt/LoginFilter.java b/springsecurity/src/main/java/com/project/springsecurity/jwt/LoginFilter.java new file mode 100644 index 0000000..0632f4f --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/jwt/LoginFilter.java @@ -0,0 +1,77 @@ +package com.project.springsecurity.jwt; + + +import com.project.springsecurity.config.JWTUtil; +import com.project.springsecurity.dto.CustomUserDetails; +import com.project.springsecurity.dto.LoginDto; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.Authentication; + +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.util.StreamUtils; +import tools.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + + + +public class LoginFilter extends UsernamePasswordAuthenticationFilter { + private final AuthenticationManager authenticationManager; + private final JWTUtil jwtUtil; + + public LoginFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil) { + this.authenticationManager = authenticationManager; + this.jwtUtil = jwtUtil; + super.setFilterProcessesUrl("/auth/login"); + } + + + @Override + public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { + + try { + + ObjectMapper objectMapper = new ObjectMapper(); + ServletInputStream inputStream = request.getInputStream(); + String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); + + LoginDto loginDTO = objectMapper.readValue(messageBody, LoginDto.class); + + String username = loginDTO.username(); + String password = loginDTO.password(); + + UsernamePasswordAuthenticationToken authToken = + new UsernamePasswordAuthenticationToken(username, password); + + return authenticationManager.authenticate(authToken); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) { + CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); + String username = customUserDetails.getUsername(); + String role = authentication.getAuthorities().iterator().next().getAuthority(); + String token = jwtUtil.createJwt(username, role, 60*10*1000L); + + response.addHeader("Authorization", "Bearer " + token); + + } + + + @Override + protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) { + response.setStatus(401); + + } + +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/repository/PostRepository.java b/springsecurity/src/main/java/com/project/springsecurity/repository/PostRepository.java new file mode 100644 index 0000000..b0090bb --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/repository/PostRepository.java @@ -0,0 +1,11 @@ +package com.project.springsecurity.repository; + +import com.project.springsecurity.entity.Post; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PostRepository extends JpaRepository { + @Override + Page findAll(Pageable pageable); +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/repository/UserRepository.java b/springsecurity/src/main/java/com/project/springsecurity/repository/UserRepository.java new file mode 100644 index 0000000..3565f73 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/repository/UserRepository.java @@ -0,0 +1,13 @@ +package com.project.springsecurity.repository; + +import com.project.springsecurity.entity.UserEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + Boolean existsByUsername(String username); + Optional findByUsername(String username); + + +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/service/CustomUserDetailsService.java b/springsecurity/src/main/java/com/project/springsecurity/service/CustomUserDetailsService.java new file mode 100644 index 0000000..0f9ee79 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/service/CustomUserDetailsService.java @@ -0,0 +1,23 @@ +package com.project.springsecurity.service; + +import com.project.springsecurity.dto.CustomUserDetails; +import com.project.springsecurity.entity.UserEntity; +import com.project.springsecurity.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class CustomUserDetailsService implements UserDetailsService { + private final UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + return userRepository.findByUsername(username) + .map(CustomUserDetails::new) + .orElseThrow(() -> new UsernameNotFoundException("유저를 찾을 수 없습니다.")); + } +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/service/JoinService.java b/springsecurity/src/main/java/com/project/springsecurity/service/JoinService.java new file mode 100644 index 0000000..33faad4 --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/service/JoinService.java @@ -0,0 +1,39 @@ +package com.project.springsecurity.service; + +import com.project.springsecurity.dto.JoinDto; +import com.project.springsecurity.entity.UserEntity; +import com.project.springsecurity.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional +public class JoinService { + private final UserRepository userRepository; + private final BCryptPasswordEncoder bCryptPasswordEncoder; + + public void joinProcess(JoinDto joinDto){ + String name = joinDto.username(); + String password = joinDto.password(); + + + Boolean isExist = userRepository.existsByUsername(name); + + if(isExist){ + throw new IllegalStateException("이미 존재하는 아이디입니다."); + } + + UserEntity user = UserEntity.builder(). + username(name). + password(bCryptPasswordEncoder.encode(password)). + role("ROLE_USER").build(); + + userRepository.save(user); + + + + } +} diff --git a/springsecurity/src/main/java/com/project/springsecurity/service/PostService.java b/springsecurity/src/main/java/com/project/springsecurity/service/PostService.java new file mode 100644 index 0000000..7f933fd --- /dev/null +++ b/springsecurity/src/main/java/com/project/springsecurity/service/PostService.java @@ -0,0 +1,108 @@ +package com.project.springsecurity.service; + + +import com.project.springsecurity.dto.PostNewRequest; +import com.project.springsecurity.dto.PostResponse; +import com.project.springsecurity.dto.PostUpdateRequest; +import com.project.springsecurity.entity.Post; +import com.project.springsecurity.entity.UserEntity; +import com.project.springsecurity.repository.PostRepository; +import com.project.springsecurity.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.NoSuchElementException; + +@Transactional(readOnly = true) +@Service +@RequiredArgsConstructor +public class PostService { + + private final PostRepository postRepository; + private final UserRepository userRepository; + + private UserEntity getUser(){ + String username = SecurityContextHolder.getContext().getAuthentication().getName(); + return userRepository.findByUsername(username).orElseThrow(()->new NoSuchElementException("유저를 찾을 수 없습니다.")); + + } + // 게시물 생성 + @Transactional + public PostResponse newPost(PostNewRequest request){ + UserEntity user = getUser(); + + Post post = Post.builder() + .title(request.title()) + .content(request.content()) + .user(user) // userName -> user + .build(); + + Post savePost = postRepository.save(post); + return PostResponse.builder(). + id(savePost.getId()). + title(savePost.getTitle()). + content(savePost.getContent()). + username(post.getUser().getUsername()). + createdAt(savePost.getCreateAt()) + .build(); + } + + // 게시물 수정 + @Transactional + public PostResponse updatePost(PostUpdateRequest request, Long id) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new NoSuchElementException("게시글을 찾을 수 없습니다.")); + post.update(request.title(), request.content()); + return PostResponse.builder(). + id(post.getId()). + title(post.getTitle()). + content(post.getContent()). + username(post.getUser().getUsername()). + createdAt(post.getCreateAt()) + .build(); + } + + // 단건 조회 + public PostResponse findOnePost(Long id) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("게시글을 찾을 수 없습니다.")); + return PostResponse.builder(). + id(post.getId()). + title(post.getTitle()). + content(post.getContent()). + username(post.getUser().getUsername()). + createdAt(post.getCreateAt()) + .build(); + } + + // 단건 삭제 + @Transactional + public void deletePost(Long id) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("게시글을 찾을 수 없습니다.")); + postRepository.delete(post); + } + + //페이지 전체 조회 + public Page getPostWithPaging(int page, int size){ + Pageable pageable = PageRequest.of(page, size, Sort.by("createAt").descending()); + return postRepository.findAll(pageable) + .map(post -> PostResponse.builder(). + id(post.getId()). + title(post.getTitle()). + content(post.getContent()). + username(post.getUser().getUsername()). + createdAt(post.getCreateAt()) + .build()); + + + + +} +} \ No newline at end of file diff --git a/springsecurity/src/main/resources/application.properties b/springsecurity/src/main/resources/application.properties new file mode 100644 index 0000000..80e336e --- /dev/null +++ b/springsecurity/src/main/resources/application.properties @@ -0,0 +1,19 @@ +spring.application.name=springsecurity + +spring.config.import=optional:file:.env[.properties] + +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.datasource.url=${DB_URL} +spring.datasource.username=${DB_USERNAME} +spring.datasource.password=${DB_PASSWORD} + + + +spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect +spring.jpa.open-in-view=false +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto= update + + +spring.jwt.secret=${SECURIT_KEY} \ No newline at end of file diff --git a/springsecurity/src/test/java/com/project/springsecurity/SpringsecurityApplicationTests.java b/springsecurity/src/test/java/com/project/springsecurity/SpringsecurityApplicationTests.java new file mode 100644 index 0000000..e95d6a9 --- /dev/null +++ b/springsecurity/src/test/java/com/project/springsecurity/SpringsecurityApplicationTests.java @@ -0,0 +1,13 @@ +package com.project.springsecurity; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringsecurityApplicationTests { + + @Test + void contextLoads() { + } + +}