diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..85e7c1d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.idea/ diff --git a/poke/.gitignore b/poke/.gitignore new file mode 100644 index 0000000..a58f7ec --- /dev/null +++ b/poke/.gitignore @@ -0,0 +1,45 @@ +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/ + +/myDB.db + + +/myTestDB.db +/jwt.yml +/src/main/resources/*.properties +/src/main/resources/*.yml diff --git a/poke/build.gradle b/poke/build.gradle new file mode 100644 index 0000000..c7dd734 --- /dev/null +++ b/poke/build.gradle @@ -0,0 +1,56 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.1.4' + id 'io.spring.dependency-management' version '1.1.3' + id 'org.asciidoctor.jvm.convert' version '3.3.2' +} + +group = 'com.inshining' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +ext { + set('snippetsDir', file("build/generated-snippets")) +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-web' + compileOnly 'org.projectlombok:lombok' + developmentOnly 'org.springframework.boot:spring-boot-devtools' + annotationProcessor 'org.projectlombok:lombok' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' + testImplementation 'org.springframework.security:spring-security-test' + implementation 'org.xerial:sqlite-jdbc:3.40.1.0' + implementation 'org.hibernate.orm:hibernate-community-dialects:6.1.7.Final' + implementation 'com.auth0:java-jwt:4.4.0' + testImplementation 'org.junit.jupiter:junit-jupiter:5.7.1' + testImplementation 'org.xerial:sqlite-jdbc:3.7.2' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + outputs.dir snippetsDir + useJUnitPlatform() +} + +tasks.named('asciidoctor') { + inputs.dir snippetsDir + dependsOn test +} diff --git a/poke/gradle/wrapper/gradle-wrapper.jar b/poke/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..033e24c Binary files /dev/null and b/poke/gradle/wrapper/gradle-wrapper.jar differ diff --git a/poke/gradle/wrapper/gradle-wrapper.properties b/poke/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9f4197d --- /dev/null +++ b/poke/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/poke/gradlew b/poke/gradlew new file mode 100755 index 0000000..fcb6fca --- /dev/null +++ b/poke/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/poke/gradlew.bat b/poke/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/poke/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/poke/settings.gradle b/poke/settings.gradle new file mode 100644 index 0000000..dc2d414 --- /dev/null +++ b/poke/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'poke' diff --git a/poke/src/main/java/com/inshining/poke/PokeApplication.java b/poke/src/main/java/com/inshining/poke/PokeApplication.java new file mode 100644 index 0000000..99912c8 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/PokeApplication.java @@ -0,0 +1,13 @@ +package com.inshining.poke; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PokeApplication { + + public static void main(String[] args) { + SpringApplication.run(PokeApplication.class, args); + } + +} diff --git a/poke/src/main/java/com/inshining/poke/config/DBConfig.java b/poke/src/main/java/com/inshining/poke/config/DBConfig.java new file mode 100644 index 0000000..30ab9c6 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/config/DBConfig.java @@ -0,0 +1,28 @@ +package com.inshining.poke.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +import javax.sql.DataSource; + +@Configuration +@PropertySource("persistence-sqlite.properties") +public class DBConfig { + + @Autowired + private Environment env; + + @Bean + public DataSource dataSource(){ + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(env.getProperty("driverClassName")); + dataSource.setUrl(env.getProperty("url")); + dataSource.setUsername(env.getProperty("user")); + dataSource.setPassword(env.getProperty("password")); + return dataSource; + } +} diff --git a/poke/src/main/java/com/inshining/poke/config/SecurityConfig.java b/poke/src/main/java/com/inshining/poke/config/SecurityConfig.java new file mode 100644 index 0000000..6a88128 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/config/SecurityConfig.java @@ -0,0 +1,45 @@ +package com.inshining.poke.config; + +import com.inshining.poke.config.security.JwtDecoderFilter; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +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.www.BasicAuthenticationFilter; + +@RequiredArgsConstructor +@EnableMethodSecurity +@Configuration +public class SecurityConfig { + private final JwtDecoderFilter jwtDecoderFilter; + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ + + return http + .csrf(AbstractHttpConfigurer::disable) + .formLogin(AbstractHttpConfigurer::disable) + .httpBasic(AbstractHttpConfigurer::disable) + .authorizeHttpRequests((request) -> request + .requestMatchers("/login").permitAll() + .requestMatchers("/sign-up").permitAll() + .anyRequest().authenticated() + ) + .sessionManagement(sessionManagement -> + sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .addFilterBefore(jwtDecoderFilter, BasicAuthenticationFilter.class) + .build(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} diff --git a/poke/src/main/java/com/inshining/poke/config/security/JwtDecoderFilter.java b/poke/src/main/java/com/inshining/poke/config/security/JwtDecoderFilter.java new file mode 100644 index 0000000..ff7146f --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/config/security/JwtDecoderFilter.java @@ -0,0 +1,62 @@ +package com.inshining.poke.config.security; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTVerificationException; +import com.auth0.jwt.interfaces.DecodedJWT; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.User; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.List; + +@RequiredArgsConstructor +@Component +public class JwtDecoderFilter extends OncePerRequestFilter { + + private static final String AUTHORIZATION_HEADER = "Authorization"; + private static final String BEARER_PREFIX = "Bearer "; + + @Value("${issuer}") + private String issuer; + + @Value("${algorithmWay}") + private String algorithmWay; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String header = request.getHeader(AUTHORIZATION_HEADER); + if (header != null && header.startsWith(BEARER_PREFIX)) { + try { + String accessToken = header.substring(BEARER_PREFIX.length()); + Authentication authenticationToken = getAuthentication(accessToken); + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + } catch (JWTVerificationException exception){ + exception.printStackTrace(); + } + } + filterChain.doFilter(request, response); + } + + private Authentication getAuthentication(String token){ + Algorithm algorithm = Algorithm.HMAC256(algorithmWay); + JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build(); + DecodedJWT decodedJWT = verifier.verify(token); + String username = decodedJWT.getSubject(); + + User user = new User(username, "", List.of(new SimpleGrantedAuthority("normal"))); + return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); + } +} diff --git a/poke/src/main/java/com/inshining/poke/config/security/TokenProvider.java b/poke/src/main/java/com/inshining/poke/config/security/TokenProvider.java new file mode 100644 index 0000000..2a6aa87 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/config/security/TokenProvider.java @@ -0,0 +1,73 @@ +package com.inshining.poke.config.security; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.inshining.poke.domain.repository.UserRefreshTokenRepository; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.Date; + +@PropertySource("classpath:jwt.yml") +@Service +public class TokenProvider { + private final String secretKey; + private final long expirationMinutes; + private final long refreshExpirationHours; + private final String issuer; + private final long reissueLimit; + private final String algorithmWay; + private final UserRefreshTokenRepository userRefreshTokenRepository; + + private final ObjectMapper objectMapper = new ObjectMapper(); + + public TokenProvider( + @Value("${secret-key}") String secretKey, + @Value("${expiration-minutes}") long expirationMinutes, + @Value("${refresh-expiration-hours}") long refreshExpirationHours, + @Value("${issuer}") String issuer, + @Value("${algorithmWay}") String algorithmWay, + UserRefreshTokenRepository userRefreshTokenRepository + ){ + this.secretKey = secretKey; + this.expirationMinutes = expirationMinutes; + this.refreshExpirationHours = refreshExpirationHours; + this.issuer = issuer; + this.userRefreshTokenRepository = userRefreshTokenRepository; + this.algorithmWay = algorithmWay; + reissueLimit = refreshExpirationHours * 60 / expirationMinutes; + } + public String createAccessToken(String userSpec){ + Algorithm algorithm = Algorithm.HMAC256(algorithmWay); + + ZoneId koreaZone = ZoneId.of("Asia/Seoul"); + LocalDateTime currentTime = LocalDateTime.now(koreaZone); + LocalDateTime expiredAccessTime = currentTime.plus(2, ChronoUnit.HOURS); + LocalDateTime expiredRefreshTime = currentTime.plus(7, ChronoUnit.DAYS); + + + return JWT.create() + .withIssuer(issuer) + .withSubject(userSpec) + .withIssuedAt(Date.from(currentTime.atZone(koreaZone).toInstant())) + .withExpiresAt(Date.from(expiredAccessTime.atZone(koreaZone).toInstant())) + .sign(algorithm); + } + + public String validateTokenAndGetSubject(String token){ + Algorithm algorithm = Algorithm.HMAC256("gdscys2023"); + JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer).build(); + DecodedJWT decodedJWT = verifier.verify(token); + String username = decodedJWT.getSubject(); + return username; + } + + +} diff --git a/poke/src/main/java/com/inshining/poke/controller/UserController.java b/poke/src/main/java/com/inshining/poke/controller/UserController.java new file mode 100644 index 0000000..9cd0c3f --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/controller/UserController.java @@ -0,0 +1,35 @@ +package com.inshining.poke.controller; + +import com.inshining.poke.domain.dto.SignInRequest; +import com.inshining.poke.domain.dto.SignInResponse; +import com.inshining.poke.domain.dto.SignUpRequest; +import com.inshining.poke.domain.dto.SignUpResponse; +import com.inshining.poke.domain.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + + +@RequiredArgsConstructor +@RestController +public class UserController { + private final UserService service; + + @PostMapping("/sign-up") + public SignUpResponse signUp(@RequestBody SignUpRequest request){ + return service.registerUser(request); + } + + @PostMapping("/login") + public SignInResponse signIn(@RequestBody SignInRequest request) { + return service.signIn(request); + } + + @GetMapping("/my") + public String getMyPage(){ + return "success"; + } + +} diff --git a/poke/src/main/java/com/inshining/poke/domain/dto/SignInRequest.java b/poke/src/main/java/com/inshining/poke/domain/dto/SignInRequest.java new file mode 100644 index 0000000..155b7e0 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/dto/SignInRequest.java @@ -0,0 +1,4 @@ +package com.inshining.poke.domain.dto; + +public record SignInRequest(String username, String password) { +} diff --git a/poke/src/main/java/com/inshining/poke/domain/dto/SignInResponse.java b/poke/src/main/java/com/inshining/poke/domain/dto/SignInResponse.java new file mode 100644 index 0000000..812d2c6 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/dto/SignInResponse.java @@ -0,0 +1,4 @@ +package com.inshining.poke.domain.dto; + +public record SignInResponse(String name, String accessToken) { +} diff --git a/poke/src/main/java/com/inshining/poke/domain/dto/SignUpRequest.java b/poke/src/main/java/com/inshining/poke/domain/dto/SignUpRequest.java new file mode 100644 index 0000000..825d461 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/dto/SignUpRequest.java @@ -0,0 +1,9 @@ +package com.inshining.poke.domain.dto; + +public record SignUpRequest( + String username, + String password, + String name +) { + +} diff --git a/poke/src/main/java/com/inshining/poke/domain/dto/SignUpResponse.java b/poke/src/main/java/com/inshining/poke/domain/dto/SignUpResponse.java new file mode 100644 index 0000000..60bf221 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/dto/SignUpResponse.java @@ -0,0 +1,15 @@ +package com.inshining.poke.domain.dto; + +import com.inshining.poke.domain.entity.user.User; + +public record SignUpResponse( + String username, + String name +) { + public static SignUpResponse from(User user) { + return new SignUpResponse( + user.getUsername(), + user.getName() + ); + } +} diff --git a/poke/src/main/java/com/inshining/poke/domain/entity/BaseTimeEntity.java b/poke/src/main/java/com/inshining/poke/domain/entity/BaseTimeEntity.java new file mode 100644 index 0000000..e60e997 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/entity/BaseTimeEntity.java @@ -0,0 +1,21 @@ +package com.inshining.poke.domain.entity; + +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; +import lombok.Getter; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import java.time.LocalDateTime; + +@Getter +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +public abstract class BaseTimeEntity { + @CreatedDate + private LocalDateTime createdDate; + + @LastModifiedDate + private LocalDateTime modifiedDate; +} diff --git a/poke/src/main/java/com/inshining/poke/domain/entity/user/User.java b/poke/src/main/java/com/inshining/poke/domain/entity/user/User.java new file mode 100644 index 0000000..f587d21 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/entity/user/User.java @@ -0,0 +1,47 @@ +package com.inshining.poke.domain.entity.user; + +import com.inshining.poke.domain.dto.SignUpRequest; +import com.inshining.poke.domain.entity.BaseTimeEntity; +import jakarta.persistence.*; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.crypto.password.PasswordEncoder; + +import java.util.ArrayList; +import java.util.Collection; + +@Getter +@Entity +@NoArgsConstructor +@Table(name = "users", indexes = @Index(columnList = "username")) +public class User extends BaseTimeEntity { + + @Id + @Column(name="id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(unique = true) + private String username; + + @Column(nullable = false) + private String password; + + @Column(nullable = false) + private String name; + + @Builder + public User(String username, String password, String name){ + this.username = username; + this.password = password; + this.name = name; + } + + + + public Collection getAuthorities(){ + return new ArrayList<>(); + } +} diff --git a/poke/src/main/java/com/inshining/poke/domain/entity/user/UserRefreshToken.java b/poke/src/main/java/com/inshining/poke/domain/entity/user/UserRefreshToken.java new file mode 100644 index 0000000..01b5415 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/entity/user/UserRefreshToken.java @@ -0,0 +1,38 @@ +package com.inshining.poke.domain.entity.user; + +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@NoArgsConstructor(access = AccessLevel.PROTECTED) +@Getter +@Entity +public class UserRefreshToken { + + @Id + private Integer userId; + @OneToOne(fetch = FetchType.LAZY) + @MapsId + @JoinColumn(name = "user_id") + private User user; + private String refreshToken; + private int reissueCount = 0; + + public UserRefreshToken(User user, String refreshToken){ + this.user = user; + this.refreshToken = refreshToken; + } + + public void updateRefreshToken(String refreshToken){ + this.refreshToken = refreshToken; + } + + public boolean validateRefreshToken(String refreshToken){ + return this.refreshToken.equals(refreshToken); + } + + public void increaseReissueCount(){ + reissueCount++; + } +} diff --git a/poke/src/main/java/com/inshining/poke/domain/repository/UserRefreshTokenRepository.java b/poke/src/main/java/com/inshining/poke/domain/repository/UserRefreshTokenRepository.java new file mode 100644 index 0000000..2b44a8b --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/repository/UserRefreshTokenRepository.java @@ -0,0 +1,10 @@ +package com.inshining.poke.domain.repository; + +import com.inshining.poke.domain.entity.user.UserRefreshToken; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRefreshTokenRepository extends JpaRepository { + Optional findByUserIdAndReissueCountLessThan(int id, long count); +} diff --git a/poke/src/main/java/com/inshining/poke/domain/repository/UserRepository.java b/poke/src/main/java/com/inshining/poke/domain/repository/UserRepository.java new file mode 100644 index 0000000..fd84c06 --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/repository/UserRepository.java @@ -0,0 +1,13 @@ +package com.inshining.poke.domain.repository; + +import com.inshining.poke.domain.entity.user.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface UserRepository extends JpaRepository { + Optional findByUsername(String username); + boolean existsByUsername(String username); +} diff --git a/poke/src/main/java/com/inshining/poke/domain/service/UserService.java b/poke/src/main/java/com/inshining/poke/domain/service/UserService.java new file mode 100644 index 0000000..5be949a --- /dev/null +++ b/poke/src/main/java/com/inshining/poke/domain/service/UserService.java @@ -0,0 +1,53 @@ +package com.inshining.poke.domain.service; + +import com.inshining.poke.config.security.TokenProvider; +import com.inshining.poke.domain.dto.SignInRequest; +import com.inshining.poke.domain.dto.SignInResponse; +import com.inshining.poke.domain.dto.SignUpRequest; +import com.inshining.poke.domain.dto.SignUpResponse; +import com.inshining.poke.domain.entity.user.User; +import com.inshining.poke.domain.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.hibernate.exception.ConstraintViolationException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + + +@RequiredArgsConstructor +@Service +public class UserService { + private final UserRepository userRepository; + private final PasswordEncoder encoder; + private final TokenProvider tokenProvider; + + private static User makeUser(SignUpRequest request, PasswordEncoder encoder){ + return User.builder() + .username(request.username()) + .password(encoder.encode(request.password())) + .name(request.name()) + .build(); + } + + @Transactional + public SignUpResponse registerUser(SignUpRequest request) { + boolean isExists = userRepository.existsByUsername(request.username()); + if (isExists){ + throw new IllegalArgumentException("이미 사용 중인 아이디입니다."); + } + User user = userRepository.save(makeUser(request, encoder)); + userRepository.flush(); + return SignUpResponse.from(user); + } + + @Transactional + public SignInResponse signIn(SignInRequest request){ + User user = userRepository.findByUsername(request.username()) + .filter(finedUser -> encoder.matches(request.password(), finedUser.getPassword())) + .orElseThrow(() -> new IllegalArgumentException("아이디 혹은 비밀번호가 일치하지 않습니다.")); + String accessToken = tokenProvider.createAccessToken(String.format("%s", user.getId())); + return new SignInResponse(user.getName(), accessToken); + } + +} diff --git a/poke/src/test/java/com/inshining/poke/PokeApplicationTests.java b/poke/src/test/java/com/inshining/poke/PokeApplicationTests.java new file mode 100644 index 0000000..9418212 --- /dev/null +++ b/poke/src/test/java/com/inshining/poke/PokeApplicationTests.java @@ -0,0 +1,14 @@ +package com.inshining.poke; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.PropertySource; + +@SpringBootTest +class PokeApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/poke/src/test/java/com/inshining/poke/repository/UserRepositoryTest.java b/poke/src/test/java/com/inshining/poke/repository/UserRepositoryTest.java new file mode 100644 index 0000000..d91e472 --- /dev/null +++ b/poke/src/test/java/com/inshining/poke/repository/UserRepositoryTest.java @@ -0,0 +1,48 @@ +package com.inshining.poke.repository; + +import com.inshining.poke.domain.entity.user.User; +import com.inshining.poke.domain.repository.UserRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(SpringExtension.class) +@DataJpaTest +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +public class UserRepositoryTest { + + @Autowired private UserRepository userRepository; + + @Test + void save(){ + User user = User.builder() + .username("aa") + .password("1234") + .name("inyeob") + .build(); + + User madeUser = userRepository.save(user); + + assertThat(madeUser.getId()).isEqualTo(1); + } + + @Test + void findByUsername(){ + userRepository.save( + User.builder() + .username("aa") + .password("1234") + .name("inyeob") + .build() + ); + + + User user = userRepository.findByUsername("aa").orElseThrow(); + assertThat(user.getUsername()).isEqualTo("aa"); + } +} diff --git a/poke/src/test/java/com/inshining/poke/service/UserServiceTest.java b/poke/src/test/java/com/inshining/poke/service/UserServiceTest.java new file mode 100644 index 0000000..e45ee58 --- /dev/null +++ b/poke/src/test/java/com/inshining/poke/service/UserServiceTest.java @@ -0,0 +1,58 @@ +package com.inshining.poke.service; + +import com.inshining.poke.config.security.TokenProvider; +import com.inshining.poke.domain.dto.SignInRequest; +import com.inshining.poke.domain.dto.SignInResponse; +import com.inshining.poke.domain.dto.SignUpRequest; +import com.inshining.poke.domain.dto.SignUpResponse; +import com.inshining.poke.domain.service.UserService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class UserServiceTest { + @Autowired + private UserService userService; + + @Test + void 회원가입_성공(){ + //given + SignUpRequest request = new SignUpRequest("abc", "1234", "myname"); + + //when + SignUpResponse response = userService.registerUser(request); + + assertThat(response.name()).isEqualTo(request.name()); + assertThat(response.username()).isEqualTo(request.username()); + } + + @Test + void 중복회원가입(){ + //given + SignUpRequest request = new SignUpRequest("abc", "1234", "myname"); + SignUpRequest request2 = new SignUpRequest("abc", "1234", "myname"); + + //when + SignUpResponse response = userService.registerUser(request); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + userService.registerUser(request2); + }); + + } + + @Test + void login성공(){ + //given + userService.registerUser(new SignUpRequest("aa", "11", "myname")); + SignInRequest request = new SignInRequest("aa", "11"); + + //when + SignInResponse response = userService.signIn(request); + + assertThat(response.name()).isEqualTo("myname"); + } +} diff --git a/poke/src/test/resources/application.properties b/poke/src/test/resources/application.properties new file mode 100644 index 0000000..f4d9c4f --- /dev/null +++ b/poke/src/test/resources/application.properties @@ -0,0 +1,6 @@ +spring.datasource.url=jdbc:sqlite:myTestDB.db +spring.datasource.driver-class-name=org.sqlite.JDBC +spring.datasource.username=test +spring.datasource.password=1234 +spring.jpa.database-platform=org.hibernate.community.dialect.SQLiteDialect +spring.jpa.hibernate.ddl-auto=create \ No newline at end of file