diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..27377ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### SECRET ### +src/main/resources/application-secret.yml diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..8521c6b --- /dev/null +++ b/build.gradle @@ -0,0 +1,47 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' +} + +group = 'gdsc' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-security' + testImplementation 'junit:junit:4.13.1' + compileOnly 'org.projectlombok:lombok' + runtimeOnly 'com.h2database:h2' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + testImplementation("org.junit.vintage:junit-vintage-engine") { + exclude group: "org.hamcrest", module: "hamcrest-core" + } + + // JWT + implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5' + runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5' + runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.5' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..033e24c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9f4197d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..fcb6fca --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=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=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $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 \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..1d250d3 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'coke-poke' diff --git a/src/main/java/gdsc/cokepoke/CokePokeApplication.java b/src/main/java/gdsc/cokepoke/CokePokeApplication.java new file mode 100644 index 0000000..ea868e2 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/CokePokeApplication.java @@ -0,0 +1,13 @@ +package gdsc.cokepoke; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CokePokeApplication { + + public static void main(String[] args) { + SpringApplication.run(CokePokeApplication.class, args); + } + +} diff --git a/src/main/java/gdsc/cokepoke/config/CorsConfig.java b/src/main/java/gdsc/cokepoke/config/CorsConfig.java new file mode 100644 index 0000000..b290cc5 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/config/CorsConfig.java @@ -0,0 +1,27 @@ +package gdsc.cokepoke.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +@Configuration +public class CorsConfig { + + // CORS 설정 + // 프론트엔드, 백엔드를 구분지어 개발하거나, 서로 다른 서버 환경에서 자원을 공유할 때, + // CORS를 허용하지 않으면, 다른 출처의 자원을 요청하는 것이 불가능하다. + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + config.addAllowedOrigin("*"); // 모든 출처 허용 + config.addAllowedHeader("*"); // 모든 헤더 허용 + config.addAllowedMethod("*"); // 모든 HTTP 메소드 허용 (GET, POST, PUT...) + + source.registerCorsConfiguration("/api/**", config); + return new CorsFilter(source); + } +} diff --git a/src/main/java/gdsc/cokepoke/config/SecurityConfig.java b/src/main/java/gdsc/cokepoke/config/SecurityConfig.java new file mode 100644 index 0000000..7be77c9 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/config/SecurityConfig.java @@ -0,0 +1,59 @@ +package gdsc.cokepoke.config; + +import gdsc.cokepoke.jwt.JwtAccessDeniedHandler; +import gdsc.cokepoke.jwt.JwtAuthenticationEntryPoint; +import gdsc.cokepoke.jwt.JwtSecurityConfig; +import gdsc.cokepoke.jwt.TokenProvider; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.filter.CorsFilter; + +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + + private final TokenProvider tokenProvider; + private final CorsFilter corsFilter; + private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; + private final JwtAccessDeniedHandler jwtAccessDeniedHandler; + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .csrf(CsrfConfigurer::disable) + .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) + // exceptionHandling 메소드를 통해 만들어둔 클래스들을 추가 + .exceptionHandling(authenticationManager -> authenticationManager + .authenticationEntryPoint(jwtAuthenticationEntryPoint) + .accessDeniedHandler(jwtAccessDeniedHandler)) + // h2-console을 위한 설정 + .headers(headers -> headers + .frameOptions(frameOptions -> frameOptions.sameOrigin())) + // 세션을 사용하지 않기 때문에 STATELESS로 설정 + .sessionManagement(configurer -> configurer + .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + // authorizeRequests 메소드를 통해 접근 권한을 설정 + .authorizeHttpRequests(authorize -> authorize + .requestMatchers("/auth/**").permitAll() + .anyRequest().authenticated()) + // JwtSecurityConfig 클래스를 적용 + .apply(new JwtSecurityConfig(tokenProvider)); + + return http.build(); + } +} diff --git a/src/main/java/gdsc/cokepoke/controller/AuthController.java b/src/main/java/gdsc/cokepoke/controller/AuthController.java new file mode 100644 index 0000000..468ef8a --- /dev/null +++ b/src/main/java/gdsc/cokepoke/controller/AuthController.java @@ -0,0 +1,36 @@ +package gdsc.cokepoke.controller; + +import gdsc.cokepoke.dto.MemberRequestDto; +import gdsc.cokepoke.dto.MemberResponseDto; +import gdsc.cokepoke.dto.TokenDto; +import gdsc.cokepoke.dto.TokenRequestDto; +import gdsc.cokepoke.service.AuthService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +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 ResponseEntity signup(@RequestBody MemberRequestDto memberRequestDto) { + return ResponseEntity.ok(authService.signup(memberRequestDto)); + } + + @PostMapping("/login") + public ResponseEntity login(@RequestBody MemberRequestDto memberRequestDto) { + return ResponseEntity.ok(authService.login(memberRequestDto)); + } + + @PostMapping("/reissue") + public ResponseEntity reissue(@RequestBody TokenRequestDto tokenRequestDto) { + return ResponseEntity.ok(authService.reissue(tokenRequestDto)); + } + +} diff --git a/src/main/java/gdsc/cokepoke/dto/MemberRequestDto.java b/src/main/java/gdsc/cokepoke/dto/MemberRequestDto.java new file mode 100644 index 0000000..5f6bfde --- /dev/null +++ b/src/main/java/gdsc/cokepoke/dto/MemberRequestDto.java @@ -0,0 +1,17 @@ +package gdsc.cokepoke.dto; + +import gdsc.cokepoke.entity.Authority; +import gdsc.cokepoke.entity.Member; +import lombok.*; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Data +public class MemberRequestDto { + private String email; + private String password; + + public UsernamePasswordAuthenticationToken toAuthentication() { + return new UsernamePasswordAuthenticationToken(email, password); + } +} diff --git a/src/main/java/gdsc/cokepoke/dto/MemberResponseDto.java b/src/main/java/gdsc/cokepoke/dto/MemberResponseDto.java new file mode 100644 index 0000000..5026b9a --- /dev/null +++ b/src/main/java/gdsc/cokepoke/dto/MemberResponseDto.java @@ -0,0 +1,17 @@ +package gdsc.cokepoke.dto; + +import gdsc.cokepoke.entity.Member; +import lombok.*; + +@Data +@Builder +public class MemberResponseDto { + private Long id; + private String email; + public static MemberResponseDto of(Member save) { + return MemberResponseDto.builder() + .id(save.getId()) + .email(save.getEmail()) + .build(); + } +} diff --git a/src/main/java/gdsc/cokepoke/dto/TokenDto.java b/src/main/java/gdsc/cokepoke/dto/TokenDto.java new file mode 100644 index 0000000..003ccd1 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/dto/TokenDto.java @@ -0,0 +1,12 @@ +package gdsc.cokepoke.dto; + +import lombok.*; + +@Data +@Builder +public class TokenDto { + private String grantType; + private String accessToken; + private Long accessTokenExpiresIn; + private String refreshToken; +} diff --git a/src/main/java/gdsc/cokepoke/dto/TokenRequestDto.java b/src/main/java/gdsc/cokepoke/dto/TokenRequestDto.java new file mode 100644 index 0000000..4a0ef0a --- /dev/null +++ b/src/main/java/gdsc/cokepoke/dto/TokenRequestDto.java @@ -0,0 +1,9 @@ +package gdsc.cokepoke.dto; + +import lombok.*; + +@Data +public class TokenRequestDto { + private String accessToken; + private String refreshToken; +} diff --git a/src/main/java/gdsc/cokepoke/entity/Authority.java b/src/main/java/gdsc/cokepoke/entity/Authority.java new file mode 100644 index 0000000..496071b --- /dev/null +++ b/src/main/java/gdsc/cokepoke/entity/Authority.java @@ -0,0 +1,5 @@ +package gdsc.cokepoke.entity; + +public enum Authority { + ROLE_USER, ROLE_ADMIN +} diff --git a/src/main/java/gdsc/cokepoke/entity/Member.java b/src/main/java/gdsc/cokepoke/entity/Member.java new file mode 100644 index 0000000..ea507b4 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/entity/Member.java @@ -0,0 +1,29 @@ +package gdsc.cokepoke.entity; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "member", indexes = @Index(name = "idx_member_email", columnList = "member_email")) +public class Member { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "member_id") + private Long id; + + @Column(name = "member_email", unique = true) + private String email; + private String password; + + @Enumerated(EnumType.STRING) + private Authority authority; + +} diff --git a/src/main/java/gdsc/cokepoke/entity/RefreshToken.java b/src/main/java/gdsc/cokepoke/entity/RefreshToken.java new file mode 100644 index 0000000..c221b4b --- /dev/null +++ b/src/main/java/gdsc/cokepoke/entity/RefreshToken.java @@ -0,0 +1,32 @@ +package gdsc.cokepoke.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@Entity +@NoArgsConstructor +public class RefreshToken { + + @Id + @Column(name = "rt_key") + private String key; // member_id + + @Column(name = "rt_value") + private String value; // refresh_token + + @Builder + public RefreshToken(String key, String value) { + this.key = key; + this.value = value; + } + + public RefreshToken updateValue(String token) { + this.value = token; + return this; + } +} diff --git a/src/main/java/gdsc/cokepoke/jwt/JwtAccessDeniedHandler.java b/src/main/java/gdsc/cokepoke/jwt/JwtAccessDeniedHandler.java new file mode 100644 index 0000000..9cde56b --- /dev/null +++ b/src/main/java/gdsc/cokepoke/jwt/JwtAccessDeniedHandler.java @@ -0,0 +1,20 @@ +package gdsc.cokepoke.jwt; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class JwtAccessDeniedHandler implements AccessDeniedHandler { + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { + // 필요한 권한이 존재하지 않는 경우 403 Forbidden 에러를 리턴 + response.sendError(HttpServletResponse.SC_FORBIDDEN); + } +} diff --git a/src/main/java/gdsc/cokepoke/jwt/JwtAuthenticationEntryPoint.java b/src/main/java/gdsc/cokepoke/jwt/JwtAuthenticationEntryPoint.java new file mode 100644 index 0000000..478f184 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/jwt/JwtAuthenticationEntryPoint.java @@ -0,0 +1,21 @@ +package gdsc.cokepoke.jwt; + +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) + throws IOException, ServletException { + // 유효한 자격증명을 제공하지 않고 접근하려 할 때 401 Unauthorized 에러를 리턴 + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + } +} diff --git a/src/main/java/gdsc/cokepoke/jwt/JwtFilter.java b/src/main/java/gdsc/cokepoke/jwt/JwtFilter.java new file mode 100644 index 0000000..89d0317 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/jwt/JwtFilter.java @@ -0,0 +1,54 @@ +package gdsc.cokepoke.jwt; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@RequiredArgsConstructor +public class JwtFilter extends OncePerRequestFilter { + + public static final String AUTHORIZATION_HEADER = "Authorization"; + public static final String BEARER_PREFIX = "Bearer "; + + private final TokenProvider tokenProvider; + + // doFilterInternal + // JWT 토큰의 인증정보를 현재 실행중인 쓰레드의 SecurityContext에 저장하는 역할을 수행 + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + // Request 헤더에서 JWT Token을 받아옴 + String jwt = resolveToken(request); + String requestURI = request.getRequestURI(); + + // 유효한 토큰인지 확인 + if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { + // 토큰이 유효하면 토큰으로부터 유저 정보를 받아옴 + Authentication authentication = tokenProvider.getAuthentication(jwt); + // SecurityContext에 Authentication 객체를 저장 + SecurityContextHolder.getContext().setAuthentication(authentication); + } else { + // 유효하지 않은 토큰이거나, 토큰이 없는 경우 + logger.debug("유효하지 않은 JWT 토큰입니다"); + } + + filterChain.doFilter(request, response); + } + + // resolveToken + // Request Header에서 토큰 정보를 꺼내오기 위한 메소드 + private String resolveToken(HttpServletRequest request) { + String bearerToken = request.getHeader(AUTHORIZATION_HEADER); + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER_PREFIX)) { + return bearerToken.substring(BEARER_PREFIX.length()); // "Bearer " 이후의 문자열을 반환 + } + return null; + } +} diff --git a/src/main/java/gdsc/cokepoke/jwt/JwtSecurityConfig.java b/src/main/java/gdsc/cokepoke/jwt/JwtSecurityConfig.java new file mode 100644 index 0000000..17def6c --- /dev/null +++ b/src/main/java/gdsc/cokepoke/jwt/JwtSecurityConfig.java @@ -0,0 +1,20 @@ +package gdsc.cokepoke.jwt; + +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; + +@RequiredArgsConstructor +public class JwtSecurityConfig extends SecurityConfigurerAdapter { + private final TokenProvider tokenProvider; + + // configure + // JwtFilter를 통해 Security 로직에 필터를 등록 + @Override + public void configure(HttpSecurity http) { + JwtFilter customFilter = new JwtFilter(tokenProvider); + http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); + } +} diff --git a/src/main/java/gdsc/cokepoke/jwt/TokenProvider.java b/src/main/java/gdsc/cokepoke/jwt/TokenProvider.java new file mode 100644 index 0000000..544b1ef --- /dev/null +++ b/src/main/java/gdsc/cokepoke/jwt/TokenProvider.java @@ -0,0 +1,132 @@ +package gdsc.cokepoke.jwt; + +import gdsc.cokepoke.dto.TokenDto; +import io.jsonwebtoken.*; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; +import io.jsonwebtoken.security.SecurityException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.security.Key; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.stream.Collectors; + +@Slf4j +@Component +public class TokenProvider { + + private static final String AUTORITIES_KEY = "auth"; + private static final String BEARER_TYPE = "Bearer"; + + private final Key key; + + + // 1. [생성자] + // application.yml에 설정한 jwt.secret 값을 가져와서 key 변수에 할당 + public TokenProvider(@Value("${jwt.secret}") String secretKey) { + byte[] keyBytes = Decoders.BASE64.decode(secretKey); + this.key = Keys.hmacShaKeyFor(keyBytes); + } + + + // 2. [토큰 생성 (인증 -> 토큰)] + // 토큰을 생성하는 메소드 + public TokenDto generateTokenDto(Authentication authentication) { + // authentication 객체에서 권한 정보를 가져옴 + String authorities = authentication.getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.joining(",")); + + // 토큰 만료 시간 설정 + ZoneId koreaZone = ZoneId.of("Asia/Seoul"); + LocalDateTime now = LocalDateTime.now(koreaZone); + LocalDateTime accessTokenExpiresIn = now.plus(1, ChronoUnit.HOURS); // 1시간 + LocalDateTime refreshTokenExpiresIn = now.plus(7, ChronoUnit.DAYS); // 7일 + + // 토큰 생성 (accessToken, refreshToken) + String accessToken = Jwts.builder() + .setSubject(authentication.getName()) // payload "sub": "username" + .claim(AUTORITIES_KEY, authorities) // payload "auth": "ROLE_USER" + .setExpiration(Date.from(accessTokenExpiresIn.atZone(koreaZone).toInstant())) + .signWith(key, SignatureAlgorithm.HS512) // header "alg": "HS512" + .compact(); + String refreshToken = Jwts.builder() + .setExpiration(Date.from(refreshTokenExpiresIn.atZone(koreaZone).toInstant())) + .signWith(key, SignatureAlgorithm.HS512) + .compact(); + + // 토큰을 TokenDto 객체에 담아서 리턴 + return TokenDto.builder() + .grantType(BEARER_TYPE) + .accessToken(accessToken) + .accessTokenExpiresIn(accessTokenExpiresIn.atZone(koreaZone).toEpochSecond()) + .refreshToken(refreshToken) + .build(); + } + + + // 3. [토큰에서 인증 정보 조회 (토큰 -> 인증)] + // Access 토큰에서 인증 정보를 조회하는 메소드 + public Authentication getAuthentication(String token) { + // 토큰을 파싱해서 Claims 객체를 생성 + Claims claims = parseClaims(token); + if (claims.get(AUTORITIES_KEY) == null) { + throw new RuntimeException("권한 정보가 없는 토큰입니다."); + } + + // Claims 객체에서 권한 정보를 가져옴 + Collection authorities = + Arrays.stream(claims.get(AUTORITIES_KEY).toString().split(",")) + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + // 권한 정보를 이용해서 User 객체를 생성 + UserDetails principal = new User(claims.getSubject(), "", authorities); + return new UsernamePasswordAuthenticationToken(principal, "", authorities); + + } + + private Claims parseClaims(String token) { + try { + return Jwts.parserBuilder().setSigningKey(key).build() + .parseClaimsJws(token).getBody(); + } catch (ExpiredJwtException e) { + return e.getClaims(); + } + } + + + // 4. [토큰 검증] + // 토큰을 검증하는 메소드 + public boolean validateToken(String token) { + try { + // 토큰을 파싱해서 문제가 없으면 true 리턴 + Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token); + return true; + } catch (SecurityException | MalformedJwtException e) { + log.info("잘못된 JWT 서명입니다."); + } catch (ExpiredJwtException e) { + log.info("만료된 JWT 토큰입니다."); + } catch (UnsupportedJwtException e) { + log.info("지원되지 않는 JWT 토큰입니다."); + } catch (IllegalArgumentException e) { + log.info("JWT 토큰이 잘못되었습니다."); + } + return false; + } + + +} diff --git a/src/main/java/gdsc/cokepoke/repository/MemberRepository.java b/src/main/java/gdsc/cokepoke/repository/MemberRepository.java new file mode 100644 index 0000000..a3a7205 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/repository/MemberRepository.java @@ -0,0 +1,11 @@ +package gdsc.cokepoke.repository; + +import gdsc.cokepoke.entity.Member; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface MemberRepository extends JpaRepository { + Optional findByEmail(String email); + boolean existsByEmail(String email); +} diff --git a/src/main/java/gdsc/cokepoke/repository/RefreshTokenRepository.java b/src/main/java/gdsc/cokepoke/repository/RefreshTokenRepository.java new file mode 100644 index 0000000..113ca85 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/repository/RefreshTokenRepository.java @@ -0,0 +1,10 @@ +package gdsc.cokepoke.repository; + +import gdsc.cokepoke.entity.RefreshToken; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface RefreshTokenRepository extends JpaRepository { + Optional findByKey(String key); +} diff --git a/src/main/java/gdsc/cokepoke/service/AuthService.java b/src/main/java/gdsc/cokepoke/service/AuthService.java new file mode 100644 index 0000000..d796497 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/service/AuthService.java @@ -0,0 +1,89 @@ +package gdsc.cokepoke.service; + +import gdsc.cokepoke.dto.MemberRequestDto; +import gdsc.cokepoke.dto.MemberResponseDto; +import gdsc.cokepoke.dto.TokenDto; +import gdsc.cokepoke.dto.TokenRequestDto; +import gdsc.cokepoke.entity.Authority; +import gdsc.cokepoke.entity.Member; +import gdsc.cokepoke.entity.RefreshToken; +import gdsc.cokepoke.jwt.TokenProvider; +import gdsc.cokepoke.repository.MemberRepository; +import gdsc.cokepoke.repository.RefreshTokenRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class AuthService { + private final AuthenticationManagerBuilder authenticationManagerBuilder; + private final MemberRepository memberRepository; + private final PasswordEncoder passwordEncoder; + private final TokenProvider tokenProvider; + private final RefreshTokenRepository refreshTokenRepository; + + @Transactional + public MemberResponseDto signup(MemberRequestDto memberRequestDto) { + if (memberRepository.existsByEmail(memberRequestDto.getEmail())) { + throw new RuntimeException("이미 가입되어 있는 유저입니다."); + } + Member member = Member.builder() + .email(memberRequestDto.getEmail()) + .password(passwordEncoder.encode(memberRequestDto.getPassword())) + .authority(Authority.ROLE_USER) + .build(); + return MemberResponseDto.of(memberRepository.save(member)); + } + + @Transactional + public TokenDto login(MemberRequestDto memberRequestDto) { + // 1. Login ID/PW 를 기반으로 AuthenticationToken 생성 + UsernamePasswordAuthenticationToken authenticationToken = + memberRequestDto.toAuthentication(); + // 2. 실제로 검증 (사용자 비밀번호 체크) + // authenticate 메서드가 실행이 될 때 CustomUserDetailsService에서 loadUserByUsername 메서드가 실행됨 + Authentication authentication = + authenticationManagerBuilder.getObject().authenticate(authenticationToken); + // 3. 인증 정보를 기반으로 JWT 토큰 생성 + TokenDto tokenDto = tokenProvider.generateTokenDto(authentication); + // 4. RefreshToken 저장 + RefreshToken refreshToken = RefreshToken.builder() + .key(authentication.getName()) + .value(tokenDto.getRefreshToken()) + .build(); + refreshTokenRepository.save(refreshToken); + // 5. 토큰 발급 + return tokenDto; + } + + @Transactional + public TokenDto reissue(TokenRequestDto tokenRequestDto) { + // 1. Refresh Token 검증 + if (!tokenProvider.validateToken(tokenRequestDto.getRefreshToken())) { + throw new RuntimeException("Refresh Token이 유효하지 않습니다."); + } + // 2. Access Token 에서 Member ID 가져오기 + Authentication authentication = + tokenProvider.getAuthentication(tokenRequestDto.getAccessToken()); + // 3. 저장소에서 Member ID 를 기반으로 Refresh Token 값 가져옴 + RefreshToken refreshToken = + refreshTokenRepository.findByKey(authentication.getName()) + .orElseThrow(() -> new RuntimeException("로그아웃 된 사용자입니다.")); + // 4. Refresh Token 일치하는지 검사 + if (!refreshToken.getValue().equals(tokenRequestDto.getRefreshToken())) { + throw new RuntimeException("토큰의 유저 정보가 일치하지 않습니다."); + } + // 5. 새로운 토큰 생성 + TokenDto tokenDto = tokenProvider.generateTokenDto(authentication); + // 6. 저장소 정보 업데이트 + RefreshToken newRefreshToken = refreshToken.updateValue(tokenDto.getRefreshToken()); + refreshTokenRepository.save(newRefreshToken); + // 7. 토큰 발급 + return tokenDto; + } +} diff --git a/src/main/java/gdsc/cokepoke/service/CustomUserDetailsService.java b/src/main/java/gdsc/cokepoke/service/CustomUserDetailsService.java new file mode 100644 index 0000000..da1d397 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/service/CustomUserDetailsService.java @@ -0,0 +1,40 @@ +package gdsc.cokepoke.service; + +import gdsc.cokepoke.entity.Member; +import gdsc.cokepoke.repository.MemberRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Collections; + +@Service +@RequiredArgsConstructor +public class CustomUserDetailsService implements UserDetailsService { + + private final MemberRepository memberRepository; + + @Override + @Transactional + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + return memberRepository.findByEmail(username) + .map(this::createUserDetails) + .orElseThrow(() -> new UsernameNotFoundException(username + " -> 데이터베이스에서 찾을 수 없습니다.")); + } + + // DB에 저장된 Member를 UserDetails로 변환해서 리턴 + private UserDetails createUserDetails(Member member) { + GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(member.getAuthority().toString()); + return new User( + String.valueOf(member.getId()), + member.getPassword(), + Collections.singleton(grantedAuthority) + ); + } +} diff --git a/src/main/java/gdsc/cokepoke/util/SecurityUtil.java b/src/main/java/gdsc/cokepoke/util/SecurityUtil.java new file mode 100644 index 0000000..145f336 --- /dev/null +++ b/src/main/java/gdsc/cokepoke/util/SecurityUtil.java @@ -0,0 +1,23 @@ +package gdsc.cokepoke.util; + +import lombok.NoArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +@Slf4j +@NoArgsConstructor +public class SecurityUtil { + + // SecurityContext 에 유저 정보가 저장되는 시점 + // -> JwtFilter 의 doFilter 메소드에서 Request 가 들어올 때 + // getCurrentMemberId는 SecurityContext 에 저장된 member_id를 리턴하는 메소드 + public static Long getCurrentMemberId() { + final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + if (authentication == null || authentication.getName() == null) { + throw new RuntimeException("Security Context에 인증 정보가 없습니다."); + } + return Long.parseLong(authentication.getName()); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..4964784 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,20 @@ +spring: + profiles: + include: + - secret + + datasource: + url: jdbc:h2:tcp://localhost/~/cokepoke + username: sa + password: + driver-class-name: org.h2.Driver + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + format_sql: true + +logging.level: + org.hibernate.SQL: debug diff --git a/src/test/java/gdsc/cokepoke/CokePokeApplicationTests.java b/src/test/java/gdsc/cokepoke/CokePokeApplicationTests.java new file mode 100644 index 0000000..aef14d3 --- /dev/null +++ b/src/test/java/gdsc/cokepoke/CokePokeApplicationTests.java @@ -0,0 +1,13 @@ +package gdsc.cokepoke; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class CokePokeApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/gdsc/cokepoke/service/MemberServiceTest.java b/src/test/java/gdsc/cokepoke/service/MemberServiceTest.java new file mode 100644 index 0000000..cf47ae8 --- /dev/null +++ b/src/test/java/gdsc/cokepoke/service/MemberServiceTest.java @@ -0,0 +1,62 @@ +package gdsc.cokepoke.service; + +import gdsc.cokepoke.dto.MemberRequestDto; +import gdsc.cokepoke.dto.MemberResponseDto; +import gdsc.cokepoke.entity.Authority; +import gdsc.cokepoke.entity.Member; +import gdsc.cokepoke.repository.MemberRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +@RunWith(SpringRunner.class) +@SpringBootTest +@Transactional +public class MemberServiceTest { + + @Autowired AuthService authService; + @Autowired MemberRepository memberRepository; + @Autowired PasswordEncoder passwordEncoder; + + @Test + public void 회원가입() throws Exception { + // given + MemberRequestDto memberRequestDto = new MemberRequestDto(); + memberRequestDto.setEmail("abc@gmail.com"); + memberRequestDto.setPassword("1234"); + + // when + MemberResponseDto memberResponseDto = authService.signup(memberRequestDto); + + // then + Member findMember = memberRepository.findByEmail(memberRequestDto.getEmail()).get(); + assertEquals(memberResponseDto.getId(), findMember.getId()); + } + + @Test(expected = RuntimeException.class) + public void 중복_회원_예외() throws Exception { + // given + MemberRequestDto memberRequestDto1 = new MemberRequestDto(); + memberRequestDto1.setEmail("abc@gmail.com"); + memberRequestDto1.setPassword("1234"); + + MemberRequestDto memberRequestDto2 = new MemberRequestDto(); + memberRequestDto2.setEmail("abc@gmail.com"); + memberRequestDto2.setPassword("2345"); + + // when + authService.signup(memberRequestDto1); + authService.signup(memberRequestDto2); // 예외가 발생해야 한다. + + // then + fail("예외가 발생해야 한다."); + } + +}