Postgres && use env file
This commit is contained in:
42
.gitignore
vendored
Normal file
42
.gitignore
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
.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/
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.dev.env
|
||||
.prod.env
|
||||
.test.env
|
||||
35
README.md
Normal file
35
README.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Spring Boot && JWT Demo
|
||||
|
||||
Spring Boot를 이용한 간단한 JWT 예시 레포지토리
|
||||
|
||||
|
||||
# How to use authenticationManager Bean in 5.7.1
|
||||
|
||||
> 참고 : https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter
|
||||
|
||||
### Question
|
||||
Is there any example how can I expose the AuthenticationManager bean? Previously I could do this by extending WebSecurityConfigurerAdapter and then creating the following method in my security config:
|
||||
```
|
||||
@Override
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
```
|
||||
|
||||
### Answer
|
||||
The following solution solved the issue for me.
|
||||
```
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
|
||||
return authenticationConfiguration.getAuthenticationManager();
|
||||
}
|
||||
```
|
||||
|
||||
# TODO
|
||||
|
||||
|
||||
### Done ✓
|
||||
|
||||
- [x] Post on Blog
|
||||
- [x] Implement regenerate refresh token test code
|
||||
79
build.gradle
Normal file
79
build.gradle
Normal file
@@ -0,0 +1,79 @@
|
||||
plugins {
|
||||
id 'org.springframework.boot' version '2.6.7'
|
||||
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
|
||||
id 'java'
|
||||
}
|
||||
|
||||
group = 'com'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
sourceCompatibility = '11'
|
||||
|
||||
configurations {
|
||||
compileOnly {
|
||||
extendsFrom annotationProcessor
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
/*
|
||||
starter
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
|
||||
/*
|
||||
thymeleaf
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
|
||||
/*
|
||||
Data JPA
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
|
||||
/*
|
||||
Lombok
|
||||
*/
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
annotationProcessor 'org.projectlombok:lombok'
|
||||
|
||||
/*
|
||||
Postgresql JDBC Driver
|
||||
*/
|
||||
implementation 'org.postgresql:postgresql:42.4.0'
|
||||
|
||||
/*
|
||||
Log4jdbc-log4j2 - SQL문을 실행한 로그를 직관적으로 볼 수 있도록 해주는 라이브러리
|
||||
*/
|
||||
// https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4
|
||||
implementation 'org.bgee.log4jdbc-log4j2:log4jdbc-log4j2-jdbc4:1.16'
|
||||
|
||||
|
||||
/*
|
||||
Security
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security:2.7.0'
|
||||
|
||||
/*
|
||||
Validation
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
|
||||
/*
|
||||
Jwt (JSON Web Token Support For The JVM)
|
||||
*/
|
||||
implementation 'io.jsonwebtoken:jjwt:0.9.1'
|
||||
|
||||
/*
|
||||
Redis
|
||||
*/
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
234
gradlew
vendored
Normal file
234
gradlew
vendored
Normal file
@@ -0,0 +1,234 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# 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"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || 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
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# 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" "$@"
|
||||
89
gradlew.bat
vendored
Normal file
89
gradlew.bat
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
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%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = 'api'
|
||||
19
src/main/java/com/api/ApiApplication.java
Normal file
19
src/main/java/com/api/ApiApplication.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package com.api;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
|
||||
@SpringBootApplication
|
||||
/**
|
||||
* 스프링 부트의 Entry 포인트 클래스에
|
||||
* @EnableJpaAuditing 어노테이션을 적용하여 JPA Auditing을 활성화
|
||||
*/
|
||||
@EnableJpaAuditing
|
||||
public class ApiApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ApiApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
26
src/main/java/com/api/AppConfig.java
Normal file
26
src/main/java/com/api/AppConfig.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.api;
|
||||
|
||||
//@Configuration
|
||||
//public class AppConfig {
|
||||
// private final UserRepository userRepository;
|
||||
// private final PasswordEncoder bCryptPasswordEncoder;
|
||||
//
|
||||
// public AppConfig(UserRepository userRepository, PasswordEncoder bCryptPasswordEncoder) {
|
||||
// System.out.println("AppConfig");
|
||||
// System.out.println("userRepository = " + userRepository);
|
||||
// this.userRepository = userRepository;
|
||||
// this.bCryptPasswordEncoder = bCryptPasswordEncoder;
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public UserService userService() {
|
||||
// System.out.println("userService");
|
||||
// return new UserServiceImpl(userRepository, bCryptPasswordEncoder);
|
||||
// }
|
||||
//
|
||||
//// @Bean
|
||||
//// public BCryptPasswordEncoder passwordEncoder() {
|
||||
//// System.out.println("passwordEncoder");
|
||||
//// return new BCryptPasswordEncoder();
|
||||
//// }
|
||||
//}
|
||||
35
src/main/java/com/api/auth/AuthController.java
Normal file
35
src/main/java/com/api/auth/AuthController.java
Normal file
@@ -0,0 +1,35 @@
|
||||
package com.api.auth;
|
||||
|
||||
import com.api.auth.dtos.SignInReq;
|
||||
import com.api.auth.dtos.SignUpReq;
|
||||
import com.api.auth.dtos.SignUpRes;
|
||||
import com.api.jwt.dtos.RegenerateTokenDto;
|
||||
import com.api.jwt.dtos.TokenDto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/signUp")
|
||||
public SignUpRes signUp(@Validated SignUpReq signUpReq) {
|
||||
return authService.signUp(signUpReq);
|
||||
}
|
||||
|
||||
@PostMapping("/signIn")
|
||||
public ResponseEntity<TokenDto> signIn(@Validated SignInReq signInReq) {
|
||||
return authService.signIn(signInReq);
|
||||
}
|
||||
|
||||
@PostMapping("/regenerateToken")
|
||||
public ResponseEntity<TokenDto> regenerateToken(@Validated RegenerateTokenDto refreshTokenDto) {
|
||||
return authService.regenerateToken(refreshTokenDto);
|
||||
}
|
||||
}
|
||||
26
src/main/java/com/api/auth/AuthService.java
Normal file
26
src/main/java/com/api/auth/AuthService.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.api.auth;
|
||||
|
||||
import com.api.auth.dtos.SignInReq;
|
||||
import com.api.auth.dtos.SignUpReq;
|
||||
import com.api.auth.dtos.SignUpRes;
|
||||
import com.api.jwt.dtos.RegenerateTokenDto;
|
||||
import com.api.jwt.dtos.TokenDto;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
public interface AuthService {
|
||||
/**
|
||||
* 유저의 정보로 회원가입
|
||||
* @param signUpReq 가입할 유저의 정보 Dto
|
||||
* @return 가입된 유저 정보
|
||||
*/
|
||||
SignUpRes signUp(SignUpReq signUpReq);
|
||||
|
||||
/**
|
||||
* 유저 정보로 로그인
|
||||
* @param signInReq 유저의 이메일과 비밀번호
|
||||
* @return json web token
|
||||
*/
|
||||
ResponseEntity<TokenDto> signIn(SignInReq signInReq);
|
||||
|
||||
ResponseEntity<TokenDto> regenerateToken(RegenerateTokenDto refreshTokenDto);
|
||||
}
|
||||
132
src/main/java/com/api/auth/AuthServiceImpl.java
Normal file
132
src/main/java/com/api/auth/AuthServiceImpl.java
Normal file
@@ -0,0 +1,132 @@
|
||||
package com.api.auth;
|
||||
|
||||
import com.api.auth.dtos.SignInReq;
|
||||
import com.api.auth.dtos.SignUpReq;
|
||||
import com.api.auth.dtos.SignUpRes;
|
||||
import com.api.exception.CustomException;
|
||||
import com.api.user.domain.Users;
|
||||
import com.api.user.repository.UserRepository;
|
||||
import com.api.jwt.JwtTokenProvider;
|
||||
import com.api.jwt.dtos.RegenerateTokenDto;
|
||||
import com.api.jwt.dtos.TokenDto;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthServiceImpl implements AuthService {
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder bCryptPasswordEncoder;
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final AuthenticationManager authenticationManager;
|
||||
private final RedisTemplate<String, String> redisTemplate;
|
||||
|
||||
@Value("${jwt.token.refresh-token-expire-length}")
|
||||
private long refresh_token_expire_time;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public SignUpRes signUp(SignUpReq signUpReq){
|
||||
System.out.println("signUpReq = " + signUpReq.toString());
|
||||
|
||||
if(userRepository.existsByEmail(signUpReq.getEmail())) {
|
||||
return new SignUpRes(false, "Your Mail already Exist.");
|
||||
}
|
||||
Users newUser = signUpReq.toUserEntity();
|
||||
newUser.hashPassword(bCryptPasswordEncoder);
|
||||
|
||||
Users user = userRepository.save(newUser);
|
||||
if(!Objects.isNull(user)) {
|
||||
return new SignUpRes(true, null);
|
||||
}
|
||||
return new SignUpRes(false, "Fail to Sign Up");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<TokenDto> signIn(SignInReq signInReq) {
|
||||
try {
|
||||
Authentication authentication = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
signInReq.getEmail(),
|
||||
signInReq.getPassword()
|
||||
)
|
||||
);
|
||||
|
||||
String refresh_token = jwtTokenProvider.generateRefreshToken(authentication);
|
||||
|
||||
TokenDto tokenDto = new TokenDto(
|
||||
jwtTokenProvider.generateAccessToken(authentication),
|
||||
refresh_token
|
||||
);
|
||||
|
||||
// Redis에 저장 - 만료 시간 설정을 통해 자동 삭제 처리
|
||||
redisTemplate.opsForValue().set(
|
||||
authentication.getName(),
|
||||
refresh_token,
|
||||
refresh_token_expire_time,
|
||||
TimeUnit.MILLISECONDS
|
||||
);
|
||||
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
httpHeaders.add("Authorization", "Bearer " + tokenDto.getAccess_token());
|
||||
|
||||
return new ResponseEntity<>(tokenDto, httpHeaders, HttpStatus.OK);
|
||||
} catch (AuthenticationException e) {
|
||||
throw new CustomException("Invalid credentials supplied", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<TokenDto> regenerateToken(RegenerateTokenDto refreshTokenDto) {
|
||||
String refresh_token = refreshTokenDto.getRefresh_token();
|
||||
try {
|
||||
// Refresh Token 검증
|
||||
if (!jwtTokenProvider.validateRefreshToken(refresh_token)) {
|
||||
throw new CustomException("Invalid refresh token supplied", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// Access Token 에서 User email를 가져온다.
|
||||
Authentication authentication = jwtTokenProvider.getAuthenticationByRefreshToken(refresh_token);
|
||||
|
||||
// Redis에서 저장된 Refresh Token 값을 가져온다.
|
||||
String refreshToken = redisTemplate.opsForValue().get(authentication.getName());
|
||||
if(!refreshToken.equals(refresh_token)) {
|
||||
throw new CustomException("Refresh Token doesn't match.", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// 토큰 재발행
|
||||
String new_refresh_token = jwtTokenProvider.generateRefreshToken(authentication);
|
||||
TokenDto tokenDto = new TokenDto(
|
||||
jwtTokenProvider.generateAccessToken(authentication),
|
||||
new_refresh_token
|
||||
);
|
||||
|
||||
// RefreshToken Redis에 업데이트
|
||||
redisTemplate.opsForValue().set(
|
||||
authentication.getName(),
|
||||
new_refresh_token,
|
||||
refresh_token_expire_time,
|
||||
TimeUnit.MILLISECONDS
|
||||
);
|
||||
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
|
||||
return new ResponseEntity<>(tokenDto, httpHeaders, HttpStatus.OK);
|
||||
} catch (AuthenticationException e) {
|
||||
throw new CustomException("Invalid refresh token supplied", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
}
|
||||
24
src/main/java/com/api/auth/dtos/SignInReq.java
Normal file
24
src/main/java/com/api/auth/dtos/SignInReq.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package com.api.auth.dtos;
|
||||
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.ToString;
|
||||
|
||||
@Getter
|
||||
@ToString
|
||||
public class SignInReq {
|
||||
@NotEmpty(message = "Please enter your Email")
|
||||
@Email
|
||||
private String email;
|
||||
@NotEmpty(message = "Please enter your Password")
|
||||
private String password;
|
||||
|
||||
@Builder
|
||||
public SignInReq(String email, String password) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
|
||||
39
src/main/java/com/api/auth/dtos/SignUpReq.java
Normal file
39
src/main/java/com/api/auth/dtos/SignUpReq.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package com.api.auth.dtos;
|
||||
|
||||
import com.api.user.domain.Users;
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.ToString;
|
||||
|
||||
@Getter
|
||||
@ToString
|
||||
public class SignUpReq {
|
||||
@NotEmpty(message = "Please enter your Email")
|
||||
@Email
|
||||
private String email;
|
||||
@NotEmpty(message = "Please enter your Password")
|
||||
private String password;
|
||||
@NotEmpty(message = "Please enter your Name")
|
||||
private String name;
|
||||
|
||||
@Builder
|
||||
public SignUpReq(String email, String password, String name) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform to User Entity
|
||||
* @return User Entity
|
||||
*/
|
||||
public Users toUserEntity() {
|
||||
return Users.builder()
|
||||
.email(this.getEmail())
|
||||
.password(this.getPassword())
|
||||
.name(this.getName())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
12
src/main/java/com/api/auth/dtos/SignUpRes.java
Normal file
12
src/main/java/com/api/auth/dtos/SignUpRes.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.api.auth.dtos;
|
||||
|
||||
import com.api.common.dtos.CoreRes;
|
||||
import lombok.Getter;
|
||||
|
||||
|
||||
@Getter
|
||||
public class SignUpRes extends CoreRes {
|
||||
public SignUpRes(boolean ok, String error) {
|
||||
super(ok, error);
|
||||
}
|
||||
}
|
||||
44
src/main/java/com/api/common/domain/CoreEntity.java
Normal file
44
src/main/java/com/api/common/domain/CoreEntity.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package com.api.common.domain;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.EntityListeners;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.MappedSuperclass;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.data.annotation.CreatedDate;
|
||||
import org.springframework.data.annotation.LastModifiedDate;
|
||||
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
@Getter @Setter
|
||||
/**
|
||||
* JPA Entity 클래스들이 CoreEntity 추상 클래스를 상속할 경우
|
||||
* createDate, modifiedDate를 컬럼으로 인식하도록
|
||||
* MappedSuperclass 어노테이션을 추가
|
||||
*/
|
||||
@MappedSuperclass
|
||||
/**
|
||||
* Spring Data JPA에서 시간에 대해서 자동으로 값을 넣어주는 기능인
|
||||
* JPA Audit를 사용하기 위해 아래 줄을 통해
|
||||
* CoreEntity 클래스에 Auditing 기능을 포함
|
||||
*
|
||||
* 그리고
|
||||
* 스프링 부트의 Entry 포인트 클래스에
|
||||
* @EnableJpaAuditing 어노테이션을 적용하여 JPA Auditing을 활성화
|
||||
*/
|
||||
@EntityListeners({AuditingEntityListener.class})
|
||||
public class CoreEntity {
|
||||
@CreatedDate
|
||||
private LocalDate createdAt;
|
||||
|
||||
@LastModifiedDate
|
||||
private LocalDate updateAt;
|
||||
|
||||
@Id // 이 프로퍼티가 pk 역할을 한다는 것을 명시
|
||||
@Column(name = "id") // 객체 필드와 DB 테이블 컬럼을 맵핑
|
||||
@GeneratedValue(strategy= GenerationType.IDENTITY) // @GeneratedValue는 pk의 값을 위한 자동 생성 전략을 명시하는데 사용
|
||||
private Long id;
|
||||
}
|
||||
11
src/main/java/com/api/common/dtos/CoreRes.java
Normal file
11
src/main/java/com/api/common/dtos/CoreRes.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.api.common.dtos;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public class CoreRes {
|
||||
private boolean ok;
|
||||
private String error;
|
||||
}
|
||||
26
src/main/java/com/api/config/JwtSecurityConfig.java
Normal file
26
src/main/java/com/api/config/JwtSecurityConfig.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.api.config;
|
||||
|
||||
import com.api.jwt.JwtTokenFilter;
|
||||
import com.api.jwt.JwtTokenProvider;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
/**
|
||||
* SecurityConfigurerAdapter를 확장.
|
||||
* JwtTokenProvider를 주입받음.
|
||||
* JwtFilter를 통해 Security filterchain에 filter를 추가 등록
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
public class JwtSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) throws Exception {
|
||||
JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider);
|
||||
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
}
|
||||
|
||||
}
|
||||
42
src/main/java/com/api/config/RedisConfig.java
Normal file
42
src/main/java/com/api/config/RedisConfig.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package com.api.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
@Value("${redis.host}")
|
||||
private String redisHost;
|
||||
|
||||
@Value("${redis.port}")
|
||||
private int redisPort;
|
||||
|
||||
/*
|
||||
RedisTemplate을 이용한 방식
|
||||
|
||||
RedisConnectionFactory 인터페이스를 통해
|
||||
LettuceConnectionFactory를 생성하여 반환
|
||||
*/
|
||||
@Bean
|
||||
public RedisConnectionFactory redisConnectionFactory() {
|
||||
return new LettuceConnectionFactory(redisHost, redisPort);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, String> redisTemplate() {
|
||||
// redisTemplate를 받아와서 set, get, delete를 사용
|
||||
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
|
||||
// setKeySerializer, setValueSerializer 설정
|
||||
// redis-cli을 통해 직접 데이터를 조회 시 알아볼 수 없는 형태로 출력되는 것을 방지
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setValueSerializer(new StringRedisSerializer());
|
||||
redisTemplate.setConnectionFactory(redisConnectionFactory());
|
||||
|
||||
return redisTemplate;
|
||||
}
|
||||
}
|
||||
73
src/main/java/com/api/config/SecurityConfig.java
Normal file
73
src/main/java/com/api/config/SecurityConfig.java
Normal file
@@ -0,0 +1,73 @@
|
||||
package com.api.config;
|
||||
|
||||
import com.api.jwt.JwtAccessDeniedHandler;
|
||||
import com.api.jwt.JwtAuthenticationEntryPoint;
|
||||
import com.api.jwt.JwtTokenProvider;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
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;
|
||||
|
||||
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConfig {
|
||||
// 추가된 jwt 관련 친구들을 security config에 추가
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
|
||||
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
|
||||
@Bean
|
||||
public BCryptPasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(
|
||||
AuthenticationConfiguration authenticationConfiguration
|
||||
) throws Exception {
|
||||
return authenticationConfiguration.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
// Disable csrf to use token
|
||||
http
|
||||
.csrf().disable();
|
||||
|
||||
//
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers(
|
||||
"/",
|
||||
"/auth/signUp",
|
||||
"/user/userList",
|
||||
"/auth/signIn*",
|
||||
"/user/profile/view/**",
|
||||
"/auth/regenerateToken",
|
||||
"/favicon.ico"
|
||||
).permitAll()
|
||||
.anyRequest().authenticated();
|
||||
|
||||
// No session will be created or used by spring security
|
||||
http
|
||||
.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
|
||||
|
||||
// exception handling for jwt
|
||||
http
|
||||
.exceptionHandling()
|
||||
.accessDeniedHandler(jwtAccessDeniedHandler)
|
||||
.authenticationEntryPoint(jwtAuthenticationEntryPoint);
|
||||
|
||||
// Apply JWT
|
||||
http.apply(new JwtSecurityConfig(jwtTokenProvider));
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
33
src/main/java/com/api/config/UserDetailsServiceImpl.java
Normal file
33
src/main/java/com/api/config/UserDetailsServiceImpl.java
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.api.config;
|
||||
|
||||
import com.api.user.domain.Users;
|
||||
import com.api.exception.UserNotFoundException;
|
||||
import com.api.user.repository.UserRepository;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class UserDetailsServiceImpl implements UserDetailsService {
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String email) throws UserNotFoundException {
|
||||
System.out.println("email in loadUserByUsername = " + email);
|
||||
Users user = userRepository.findByEmail(email)
|
||||
.orElseThrow(UserNotFoundException::new);
|
||||
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
|
||||
|
||||
return new org
|
||||
.springframework
|
||||
.security
|
||||
.core
|
||||
.userdetails
|
||||
.User(user.getEmail(), user.getPassword(), grantedAuthorities);
|
||||
}
|
||||
}
|
||||
26
src/main/java/com/api/exception/CustomException.java
Normal file
26
src/main/java/com/api/exception/CustomException.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.api.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public class CustomException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final String message;
|
||||
private final HttpStatus httpStatus;
|
||||
|
||||
public CustomException(String message, HttpStatus httpStatus) {
|
||||
this.message = message;
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public HttpStatus getHttpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.api.exception;
|
||||
|
||||
public class UserNotFoundException extends RuntimeException {
|
||||
public UserNotFoundException() {
|
||||
super("Can't find User");
|
||||
}
|
||||
|
||||
}
|
||||
12
src/main/java/com/api/home/HomeController.java
Normal file
12
src/main/java/com/api/home/HomeController.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.api.home;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class HomeController {
|
||||
@GetMapping("/")
|
||||
public String home() {
|
||||
return "home";
|
||||
}
|
||||
}
|
||||
24
src/main/java/com/api/jwt/JwtAccessDeniedHandler.java
Normal file
24
src/main/java/com/api/jwt/JwtAccessDeniedHandler.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package com.api.jwt;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* AccessDeniedHandler
|
||||
*
|
||||
* AuthenticationEntryPoint와 달리 AccessDeniedHandler는
|
||||
* 유저 정보는 있으나, 엑세스 권한이 없는 경우 동작하는 친구이다.
|
||||
*/
|
||||
@Component
|
||||
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
}
|
||||
34
src/main/java/com/api/jwt/JwtAuthenticationEntryPoint.java
Normal file
34
src/main/java/com/api/jwt/JwtAuthenticationEntryPoint.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.api.jwt;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* AuthenticationEntryPoint
|
||||
*
|
||||
* 인증 과정에서 실패하거나 인증을 위한 헤더정보를 보내지 않은 경우
|
||||
* 401(UnAuthorized) 에러가 발생하게 된다.
|
||||
*
|
||||
* Spring Security에서 인증되지 않은 사용자에 대한 접근 처리는 AuthenticationEntryPoint가 담당하는데,
|
||||
* commence 메소드가 실행되어 처리된다.
|
||||
*/
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
@Override
|
||||
public void commence(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
AuthenticationException e
|
||||
) throws IOException {
|
||||
System.out.println(request.getRequestURI());
|
||||
log.error("UnAuthorized -- message : " + e.getMessage()); // 로그를 남기고
|
||||
response.sendRedirect("/auth/signIn"); // 로그인 페이지로 리다이렉트되도록 하였다.
|
||||
}
|
||||
}
|
||||
41
src/main/java/com/api/jwt/JwtTokenFilter.java
Normal file
41
src/main/java/com/api/jwt/JwtTokenFilter.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package com.api.jwt;
|
||||
|
||||
import com.api.exception.CustomException;
|
||||
import java.io.IOException;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
// Request 이전에 1회 작동할 필터
|
||||
public class JwtTokenFilter extends OncePerRequestFilter {
|
||||
private JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
|
||||
this.jwtTokenProvider = jwtTokenProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
String token = jwtTokenProvider.resolveToken(request);
|
||||
try {
|
||||
if (token != null && jwtTokenProvider.validateAccessToken(token)) {
|
||||
Authentication auth = jwtTokenProvider.getAuthenticationByAccessToken(token);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth); // 정상 토큰이면 SecurityContext에 저장
|
||||
}
|
||||
} catch (CustomException e) {
|
||||
SecurityContextHolder.clearContext();
|
||||
response.sendError(e.getHttpStatus().value(), e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
142
src/main/java/com/api/jwt/JwtTokenProvider.java
Normal file
142
src/main/java/com/api/jwt/JwtTokenProvider.java
Normal file
@@ -0,0 +1,142 @@
|
||||
package com.api.jwt;
|
||||
|
||||
import com.api.exception.CustomException;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import java.util.Date;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
// 유저 정보로 JWT 토큰을 만들거나 토큰을 바탕으로 유저 정보를 가져옴
|
||||
@Component
|
||||
public class JwtTokenProvider {
|
||||
@Value("${jwt.token.access-token-secret-key}")
|
||||
private String access_token_secret_key;
|
||||
|
||||
@Value("${jwt.token.refresh-token-secret-key}")
|
||||
private String refresh_token_secret_key;
|
||||
|
||||
@Value("${jwt.token.access-token-expire-length}")
|
||||
private long access_token_expire_time;
|
||||
|
||||
@Value("${jwt.token.refresh-token-expire-length}")
|
||||
private long refresh_token_expire_time;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
|
||||
/**
|
||||
* 적절한 설정을 통해 Access 토큰을 생성하여 반환
|
||||
* @param authentication
|
||||
* @return access token
|
||||
*/
|
||||
public String generateAccessToken(Authentication authentication) {
|
||||
Claims claims = Jwts.claims().setSubject(authentication.getName());
|
||||
// claims.put("auth", appUserRoles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));
|
||||
|
||||
Date now = new Date();
|
||||
Date expiresIn = new Date(now.getTime() + access_token_expire_time);
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiresIn)
|
||||
.signWith(SignatureAlgorithm.HS256, access_token_secret_key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* 적절한 설정을 통해 Refresh 토큰을 생성하여 반환
|
||||
* @param authentication
|
||||
* @return refresh token
|
||||
*/
|
||||
public String generateRefreshToken(Authentication authentication) {
|
||||
Claims claims = Jwts.claims().setSubject(authentication.getName());
|
||||
|
||||
Date now = new Date();
|
||||
Date expiresIn = new Date(now.getTime() + refresh_token_expire_time);
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiresIn)
|
||||
.signWith(SignatureAlgorithm.HS256, refresh_token_secret_key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* Access 토큰으로부터 클레임을 만들고, 이를 통해 User 객체를 생성하여 Authentication 객체를 반환
|
||||
* @param access_token
|
||||
* @return
|
||||
*/
|
||||
public Authentication getAuthenticationByAccessToken(String access_token) {
|
||||
String userPrincipal = Jwts.parser().setSigningKey(access_token_secret_key).parseClaimsJws(access_token).getBody().getSubject();
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(userPrincipal);
|
||||
|
||||
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh 토큰으로부터 클레임을 만들고, 이를 통해 User 객체를 생성하여 Authentication 객체를 반환
|
||||
* @param refresh_token
|
||||
* @return
|
||||
*/
|
||||
public Authentication getAuthenticationByRefreshToken(String refresh_token) {
|
||||
String userPrincipal = Jwts.parser().setSigningKey(refresh_token_secret_key).parseClaimsJws(refresh_token).getBody().getSubject();
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(userPrincipal);
|
||||
|
||||
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
|
||||
}
|
||||
|
||||
/**
|
||||
* http 헤더로부터 bearer 토큰을 가져옴.
|
||||
* @param req
|
||||
* @return
|
||||
*/
|
||||
public String resolveToken(HttpServletRequest req) {
|
||||
String bearerToken = req.getHeader("Authorization");
|
||||
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access 토큰을 검증
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public boolean validateAccessToken(String token) {
|
||||
try {
|
||||
Jwts.parser().setSigningKey(access_token_secret_key).parseClaimsJws(token);
|
||||
return true;
|
||||
} catch (JwtException e) {
|
||||
// MalformedJwtException | ExpiredJwtException | IllegalArgumentException
|
||||
throw new CustomException("Error on Access Token", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh 토큰을 검증
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public boolean validateRefreshToken(String token) {
|
||||
try {
|
||||
Jwts.parser().setSigningKey(refresh_token_secret_key).parseClaimsJws(token);
|
||||
return true;
|
||||
} catch (JwtException e) {
|
||||
// MalformedJwtException | ExpiredJwtException | IllegalArgumentException
|
||||
throw new CustomException("Error on Refresh Token", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
10
src/main/java/com/api/jwt/dtos/RegenerateTokenDto.java
Normal file
10
src/main/java/com/api/jwt/dtos/RegenerateTokenDto.java
Normal file
@@ -0,0 +1,10 @@
|
||||
package com.api.jwt.dtos;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
public class RegenerateTokenDto {
|
||||
private String refresh_token;
|
||||
}
|
||||
11
src/main/java/com/api/jwt/dtos/TokenDto.java
Normal file
11
src/main/java/com/api/jwt/dtos/TokenDto.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.api.jwt.dtos;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
public class TokenDto {
|
||||
private String access_token;
|
||||
private String refresh_token;
|
||||
}
|
||||
51
src/main/java/com/api/user/UserController.java
Normal file
51
src/main/java/com/api/user/UserController.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.api.user;
|
||||
|
||||
import com.api.exception.UserNotFoundException;
|
||||
import com.api.user.domain.Users;
|
||||
import com.api.user.dtos.ProfileDto.ProfileRes;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* User 관련 HTTP 요청 처리
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/user")
|
||||
@RequiredArgsConstructor
|
||||
public class UserController {
|
||||
private final UserService userService;
|
||||
|
||||
@GetMapping("/profile")
|
||||
public ProfileRes profile(@AuthenticationPrincipal UserDetails userDetails) throws UserNotFoundException {
|
||||
System.out.println("userDetails = " + userDetails);
|
||||
Users userDetail = userService.findByEmail(userDetails.getUsername())
|
||||
.orElseThrow(() -> new UserNotFoundException());
|
||||
|
||||
return ProfileRes.builder()
|
||||
.email(userDetail.getEmail())
|
||||
.name(userDetail.getName())
|
||||
.build();
|
||||
}
|
||||
|
||||
@GetMapping("/profile/view/{username}")
|
||||
public ProfileRes userProfile(@PathVariable String username) throws UserNotFoundException {
|
||||
Users user = userService.findByName(username)
|
||||
.orElseThrow(UserNotFoundException::new);
|
||||
|
||||
return ProfileRes.builder()
|
||||
.email(user.getEmail())
|
||||
.name(user.getName())
|
||||
.build();
|
||||
}
|
||||
|
||||
@GetMapping("/userList")
|
||||
public List<Users> showUserList() {
|
||||
return userService.findAll();
|
||||
}
|
||||
}
|
||||
41
src/main/java/com/api/user/UserService.java
Normal file
41
src/main/java/com/api/user/UserService.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package com.api.user;
|
||||
|
||||
import com.api.user.domain.Users;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserService {
|
||||
/**
|
||||
* 모든 유저 리스트를 반환
|
||||
* @return 유저 리스트
|
||||
*/
|
||||
List<Users> findAll();
|
||||
|
||||
/**
|
||||
* 이메일을 통해 유저 조회
|
||||
* @param email
|
||||
* @return 조회된 유저
|
||||
*/
|
||||
Optional<Users> findByEmail(String email);
|
||||
|
||||
/**
|
||||
* 이름을 통해 유저 조회
|
||||
* @param name
|
||||
* @return 조회된 유저
|
||||
*/
|
||||
Optional<Users> findByName(String name);
|
||||
|
||||
// /**
|
||||
// * Security Context에 존재하는 인증 정보를 통해 유저 정보 조회
|
||||
// * @return 조회된 유저
|
||||
// */
|
||||
// Optional<User> getMyInfo();
|
||||
|
||||
/**
|
||||
* 유저 정보 수정
|
||||
* @param user 수정활 User Entity
|
||||
* @param newInfo
|
||||
* @return 수정된 User
|
||||
*/
|
||||
Users updateUser(Users user, String newInfo);
|
||||
}
|
||||
36
src/main/java/com/api/user/UserServiceImpl.java
Normal file
36
src/main/java/com/api/user/UserServiceImpl.java
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.api.user;
|
||||
|
||||
import com.api.user.repository.UserRepository;
|
||||
import com.api.user.domain.Users;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class UserServiceImpl implements UserService {
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
public List<Users> findAll() {
|
||||
return userRepository.findAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Users> findByEmail(String email) {
|
||||
return userRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Users> findByName(String name) {
|
||||
return userRepository.findByName(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Users updateUser(Users user, String newInfo) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
8
src/main/java/com/api/user/domain/UserRole.java
Normal file
8
src/main/java/com/api/user/domain/UserRole.java
Normal file
@@ -0,0 +1,8 @@
|
||||
package com.api.user.domain;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public enum UserRole {
|
||||
ROLE_USER // Spring Security의 role 네이밍 규칙 : ROLE_권한이름
|
||||
}
|
||||
47
src/main/java/com/api/user/domain/Users.java
Normal file
47
src/main/java/com/api/user/domain/Users.java
Normal file
@@ -0,0 +1,47 @@
|
||||
package com.api.user.domain;
|
||||
|
||||
import com.api.common.domain.CoreEntity;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
// @Entity 어노테이션을 클래스에 선언하면 그 클래스는 JPA가 관리
|
||||
@Entity
|
||||
@Getter @Setter
|
||||
@NoArgsConstructor
|
||||
@ToString
|
||||
public class Users extends CoreEntity {
|
||||
@Column(nullable = false, unique = true)
|
||||
private String email;
|
||||
@Column(nullable = false)
|
||||
private String password;
|
||||
@Column(length = 10, nullable = false, unique = true)
|
||||
private String name;
|
||||
|
||||
// @Enumerated(EnumType.STRING)
|
||||
// private UserRole role;
|
||||
|
||||
@Builder
|
||||
public Users(String email, String password, String name /*UserRole role*/) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
// this.role = role;
|
||||
}
|
||||
|
||||
// https://reflectoring.io/spring-security-password-handling/
|
||||
/**
|
||||
* 비밀번호를 암호화
|
||||
* @param passwordEncoder 암호화 할 인코더 클래스
|
||||
* @return 변경된 유저 Entity
|
||||
*/
|
||||
public Users hashPassword(PasswordEncoder passwordEncoder) {
|
||||
this.password = passwordEncoder.encode(this.password);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
19
src/main/java/com/api/user/dtos/ProfileDto.java
Normal file
19
src/main/java/com/api/user/dtos/ProfileDto.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package com.api.user.dtos;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
public class ProfileDto {
|
||||
@Data
|
||||
@Builder
|
||||
public static class ProfileReq {
|
||||
private String name;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class ProfileRes {
|
||||
private String email;
|
||||
private String name;
|
||||
}
|
||||
}
|
||||
22
src/main/java/com/api/user/repository/UserRepository.java
Normal file
22
src/main/java/com/api/user/repository/UserRepository.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.api.user.repository;
|
||||
|
||||
import com.api.user.domain.Users;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface UserRepository extends JpaRepository<Users, Long> {
|
||||
|
||||
Optional<Users> findByEmail(String email);
|
||||
|
||||
Optional<Users> findByName(String name);
|
||||
|
||||
/**
|
||||
* 이메일 중복 여부를 확인
|
||||
*
|
||||
* @param email
|
||||
* @return true | false
|
||||
*/
|
||||
boolean existsByEmail(String email);
|
||||
}
|
||||
29
src/main/resources/application.yml
Normal file
29
src/main/resources/application.yml
Normal file
@@ -0,0 +1,29 @@
|
||||
server:
|
||||
port: 3000
|
||||
spring:
|
||||
config:
|
||||
import: optional:file:.dev.env[.properties]
|
||||
# Database
|
||||
datasource:
|
||||
driver-class-name: org.postgresql.Driver
|
||||
url: jdbc:postgresql://localhost:5432/${DB_NAME}
|
||||
username: postgres
|
||||
password: ${DB_PW}
|
||||
# jpa properties
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
show-sql: true
|
||||
database: postgresql
|
||||
database-platform: org.hibernate.dialect.PostgreSQLDialect
|
||||
open-in-view: false
|
||||
generate-ddl: true
|
||||
jwt:
|
||||
token:
|
||||
access-token-secret-key: ${ACCESS_TOKEN_SECRET_KEY}
|
||||
access-token-expire-length: 300000
|
||||
refresh-token-secret-key: ${REFRESH_TOKEN_SECRET_KEY}
|
||||
refresh-token-expire-length: 6000000
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
13
src/test/java/com/api/ApiApplicationTests.java
Normal file
13
src/test/java/com/api/ApiApplicationTests.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.api;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class ApiApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
118
src/test/java/com/api/auth/service/AuthServiceTest.java
Normal file
118
src/test/java/com/api/auth/service/AuthServiceTest.java
Normal file
@@ -0,0 +1,118 @@
|
||||
package com.api.auth.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.api.auth.AuthService;
|
||||
import com.api.auth.dtos.SignInReq;
|
||||
import com.api.auth.dtos.SignUpReq;
|
||||
import com.api.auth.dtos.SignUpRes;
|
||||
import com.api.exception.UserNotFoundException;
|
||||
import com.api.jwt.dtos.RegenerateTokenDto;
|
||||
import com.api.jwt.dtos.TokenDto;
|
||||
import com.api.user.UserService;
|
||||
import com.api.user.domain.Users;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
@DisplayName("Auth Service Test")
|
||||
class AuthServiceTest {
|
||||
private static final String EMAIL = "test@email.com";
|
||||
private static final String PASSWORD = "12345";
|
||||
private static final String NAME = "김정호";
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private AuthService authService;
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 회원가입")
|
||||
void signUp() {
|
||||
// given
|
||||
SignUpReq user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
|
||||
// when
|
||||
SignUpRes signUpRes = authService.signUp(user);
|
||||
|
||||
// then
|
||||
Assertions.assertThat(signUpRes.isOk()).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("유저 로그인")
|
||||
void signIn() {
|
||||
// given
|
||||
SignUpReq user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
authService.signUp(user);
|
||||
|
||||
// when
|
||||
ResponseEntity<TokenDto> response = authService.signIn(createSignInRequest());
|
||||
|
||||
// then
|
||||
assertThat(response.getBody().getAccess_token()).isNotEmpty();
|
||||
assertThat(response.getBody().getRefresh_token()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("비밀번호는 암호화되어야 한다.")
|
||||
void hashPassword() {
|
||||
// given
|
||||
SignUpReq user = createSignUpRequest();
|
||||
|
||||
// when
|
||||
authService.signUp(user);
|
||||
|
||||
// then
|
||||
Users createdUser = userService.findByEmail(EMAIL)
|
||||
.orElseThrow(UserNotFoundException::new);
|
||||
System.out.println("newUser pw = " + createdUser.getPassword());
|
||||
|
||||
assertThat(createdUser.getPassword()).isNotEqualTo(PASSWORD);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("토큰 재발행")
|
||||
void regenerateToken() {
|
||||
// given
|
||||
SignUpReq user = createSignUpRequest();
|
||||
System.out.println("user = " + user.toString());
|
||||
authService.signUp(user);
|
||||
|
||||
// when
|
||||
ResponseEntity<TokenDto> response = authService.signIn(createSignInRequest());
|
||||
String prevAccessToken = response.getBody().getAccess_token();
|
||||
|
||||
RegenerateTokenDto regenerateTokenDto = new RegenerateTokenDto(
|
||||
response.getBody().getRefresh_token()
|
||||
);
|
||||
|
||||
ResponseEntity<TokenDto> regeneratedToken = authService.regenerateToken(regenerateTokenDto);
|
||||
|
||||
// then
|
||||
assertThat(regeneratedToken.getBody().getAccess_token()).isNotEqualTo(prevAccessToken);
|
||||
}
|
||||
|
||||
private SignUpReq createSignUpRequest() {
|
||||
return SignUpReq.builder()
|
||||
.email(EMAIL)
|
||||
.password(PASSWORD)
|
||||
.name(NAME)
|
||||
.build();
|
||||
}
|
||||
|
||||
private SignInReq createSignInRequest() {
|
||||
return SignInReq.builder()
|
||||
.email(EMAIL)
|
||||
.password(PASSWORD)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
75
src/test/java/com/api/user/service/UserServiceTest.java
Normal file
75
src/test/java/com/api/user/service/UserServiceTest.java
Normal file
@@ -0,0 +1,75 @@
|
||||
package com.api.user.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.api.auth.AuthService;
|
||||
import com.api.auth.dtos.SignUpReq;
|
||||
import com.api.user.UserService;
|
||||
import com.api.user.domain.Users;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
@DisplayName("User Service Test")
|
||||
class UserServiceTest {
|
||||
private static final String EMAIL = "test@email.com";
|
||||
private static final String PASSWORD = "12345";
|
||||
private static final String NAME = "김정호";
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder bCryptPasswordEncoder;
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private AuthService authService;
|
||||
|
||||
@Test
|
||||
@DisplayName("모든 유저 리스트를 반환")
|
||||
void findAll() {
|
||||
// given
|
||||
List<Users> prevUserList = userService.findAll();
|
||||
int prevLen = prevUserList.size();
|
||||
SignUpReq user1 = createSignUpRequest();
|
||||
authService.signUp(user1);
|
||||
|
||||
// when
|
||||
List<Users> userList = userService.findAll();
|
||||
|
||||
// then
|
||||
assertEquals(prevLen + 1, userList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("이메일로 유저 찾기")
|
||||
void findByEmail() {
|
||||
// given
|
||||
SignUpReq user1 = createSignUpRequest();
|
||||
authService.signUp(user1);
|
||||
|
||||
// when
|
||||
Optional<Users> byEmail = userService.findByEmail(EMAIL);
|
||||
|
||||
// then
|
||||
assertThat(byEmail.get().getEmail()).isEqualTo(user1.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUser() {
|
||||
}
|
||||
|
||||
private SignUpReq createSignUpRequest() {
|
||||
return SignUpReq.builder()
|
||||
.email(EMAIL)
|
||||
.password(PASSWORD)
|
||||
.name(NAME)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user