commit
This commit is contained in:
parent
67bf62b481
commit
142f1f24c2
3
.gitattributes
vendored
Normal file
3
.gitattributes
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
/gradlew text eol=lf
|
||||||
|
*.bat text eol=crlf
|
||||||
|
*.jar binary
|
||||||
37
.gitignore
vendored
Normal file
37
.gitignore
vendored
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
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/
|
||||||
130
build.gradle
Normal file
130
build.gradle
Normal file
@ -0,0 +1,130 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java'
|
||||||
|
id 'org.springframework.boot' version "${springBootVersion}"
|
||||||
|
id 'io.spring.dependency-management' version "${springDependencyManagementVersion}"
|
||||||
|
}
|
||||||
|
|
||||||
|
group = "${projectGroup}"
|
||||||
|
version = "${projectVersion}"
|
||||||
|
|
||||||
|
ext {
|
||||||
|
LOCAL = 'local'
|
||||||
|
DEV = 'dev'
|
||||||
|
|
||||||
|
if(!project.hasProperty('profile') || !profile) {
|
||||||
|
ext.profile = LOCAL;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentProfile = "${profile}"
|
||||||
|
println(project.name + "[${profile}]/" + currentProfile + "]" )
|
||||||
|
|
||||||
|
isLOCAL = currentProfile == LOCAL
|
||||||
|
isDEV = currentProfile == DEV
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
sourceCompatibility = "${javaVersion}"
|
||||||
|
targetCompatibility = "${javaVersion}"
|
||||||
|
}
|
||||||
|
|
||||||
|
configurations {
|
||||||
|
all {
|
||||||
|
exclude group: 'commons-logging' , module: 'commons-logging'
|
||||||
|
exclude group: 'log4j' , module: 'log4j'
|
||||||
|
exclude group: 'org.apache.logging.log4j', module: 'log4j-to-slf4j'
|
||||||
|
exclude group: 'org.slf4j' , module: 'slf4j-log4j12'
|
||||||
|
}
|
||||||
|
compileOnly {
|
||||||
|
extendsFrom annotationProcessor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyManagement {
|
||||||
|
imports {
|
||||||
|
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceSets {
|
||||||
|
main {
|
||||||
|
java.srcDirs = ['src/main/java']
|
||||||
|
|
||||||
|
if(project.hasProperty( 'profile' )) {
|
||||||
|
resources.srcDirs = ['src/main/resources']
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
/** lombok & spring-boot-devtools */
|
||||||
|
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
|
||||||
|
compileOnly "org.projectlombok:lombok:${lombokVersion}"
|
||||||
|
testAnnotationProcessor "org.projectlombok:lombok:${lombokVersion}"
|
||||||
|
testCompileOnly "org.projectlombok:lombok:${lombokVersion}"
|
||||||
|
|
||||||
|
/** spring boot */
|
||||||
|
developmentOnly 'org.springframework.boot:spring-boot-devtools'
|
||||||
|
|
||||||
|
/** spring-boot-starter */
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-aop'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-webflux'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-actuator-autoconfigure'
|
||||||
|
/*implementation 'org.springframework.boot:spring-boot-starter-batch'*/
|
||||||
|
|
||||||
|
|
||||||
|
/** spring-boot-starter-security */
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||||
|
|
||||||
|
/** apache-commons */
|
||||||
|
implementation 'commons-beanutils:commons-beanutils:1.9.4'
|
||||||
|
implementation 'commons-codec:commons-codec:1.17.1'
|
||||||
|
implementation 'commons-io:commons-io:2.17.0'
|
||||||
|
implementation 'org.apache.commons:commons-collections4:4.4'
|
||||||
|
implementation 'org.apache.commons:commons-lang3:3.17.0'
|
||||||
|
implementation 'org.apache.commons:commons-text:1.12.0'
|
||||||
|
implementation 'commons-fileupload:commons-fileupload:1.5' // file upload
|
||||||
|
|
||||||
|
/** log4jdbc */
|
||||||
|
implementation 'org.bgee.log4jdbc-log4j2:log4jdbc-log4j2-jdbc4.1:1.16'
|
||||||
|
|
||||||
|
/** mariaDB */
|
||||||
|
implementation "org.mariadb.jdbc:mariadb-java-client:${mariadbClientVersion}"
|
||||||
|
|
||||||
|
/** mybatis-spring-boot-starter */
|
||||||
|
implementation "org.mybatis.spring.boot:mybatis-spring-boot-starter:${mybatisSpringBootVersion}"
|
||||||
|
|
||||||
|
/** org.json */
|
||||||
|
implementation "org.json:json:${jsonVersion}"
|
||||||
|
//implementation 'com.fasterxml.jackson.core:jackson-annotations'
|
||||||
|
//implementation 'com.fasterxml.jackson.core:jackson-core'
|
||||||
|
//implementation 'com.fasterxml.jackson.core:jackson-databind'
|
||||||
|
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'
|
||||||
|
|
||||||
|
/** test dependency */
|
||||||
|
testImplementation('org.springframework.boot:spring-boot-starter-test') {
|
||||||
|
exclude group : 'org.junit.vintage'
|
||||||
|
exclude module : 'junit-vintage-engine'
|
||||||
|
//exclude module : 'org.junit.vintage:junit-vintage-engine'
|
||||||
|
}
|
||||||
|
testImplementation "org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}"
|
||||||
|
testImplementation "org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}"
|
||||||
|
testImplementation 'org.junit.platform:junit-platform-runner:1.11.0'
|
||||||
|
testImplementation 'org.springframework.batch:spring-batch-test'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
options.encoding = "${javaEncoding}"
|
||||||
|
}
|
||||||
|
tasks.javadoc {
|
||||||
|
options.encoding = "${javaEncoding}"
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('test') {
|
||||||
|
useJUnitPlatform()
|
||||||
|
}
|
||||||
20
gradle.properties
Normal file
20
gradle.properties
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
#
|
||||||
|
rootProjectName = localhost
|
||||||
|
|
||||||
|
projectGroup = io.company
|
||||||
|
projectVersion = 0.0.1
|
||||||
|
|
||||||
|
javaEncoding = UTF-8
|
||||||
|
javaVersion = 17
|
||||||
|
|
||||||
|
# spring-boot version
|
||||||
|
springBootVersion = 3.4.0
|
||||||
|
springDependencyManagementVersion = 1.1.6
|
||||||
|
springCloudVersion = 2023.0.3
|
||||||
|
|
||||||
|
# 3rd party library version
|
||||||
|
junitJupiterVersion=5.9.3
|
||||||
|
lombokVersion=1.18.34
|
||||||
|
mybatisSpringBootVersion=3.0.3
|
||||||
|
jsonVersion = 20240303
|
||||||
|
mariadbClientVersion = 3.4.1
|
||||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
252
gradlew
vendored
Normal file
252
gradlew
vendored
Normal file
@ -0,0 +1,252 @@
|
|||||||
|
#!/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.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||||
|
' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
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=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
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, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-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" "$@"
|
||||||
94
gradlew.bat
vendored
Normal file
94
gradlew.bat
vendored
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables 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. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
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
|
||||||
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@ -0,0 +1 @@
|
|||||||
|
rootProject.name = 'localhost'
|
||||||
45
src/main/java/io/company/localhost/LocalhostApplication.java
Normal file
45
src/main/java/io/company/localhost/LocalhostApplication.java
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
package io.company.localhost;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
|
||||||
|
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
|
||||||
|
import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration;
|
||||||
|
|
||||||
|
import io.company.localhost.common.config.ComponentScanConfig;
|
||||||
|
import io.company.localhost.common.context.ApplicationContextProvider;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@SpringBootApplication(scanBasePackageClasses = { ApplicationContextProvider.class , ComponentScanConfig.class} ,
|
||||||
|
exclude = {DataSourceTransactionManagerAutoConfiguration.class, TransactionAutoConfiguration.class , JacksonAutoConfiguration.class})
|
||||||
|
public class LocalhostApplication {
|
||||||
|
|
||||||
|
public LocalhostApplication(@Value("${project.locale}") Locale defaultLocale,
|
||||||
|
@Value("${project.time-zone}") TimeZone defaultTimeZone) {
|
||||||
|
log.debug("yaml locale {}", defaultLocale);
|
||||||
|
log.debug("yaml locale {}", Locale.KOREA);
|
||||||
|
|
||||||
|
log.debug("yaml timeZone {}", defaultTimeZone.getID());
|
||||||
|
log.debug("yaml timeZone {}", defaultTimeZone.getDisplayName());
|
||||||
|
log.debug("yaml timeZone {}", defaultTimeZone.getID());
|
||||||
|
log.debug("yaml timeZone {}", TimeZone.getTimeZone("UTC").getID());
|
||||||
|
log.debug("yaml timeZone {}", TimeZone.getDefault().getID());
|
||||||
|
|
||||||
|
// default Locale, default TimeZone 설정
|
||||||
|
Locale.setDefault(defaultLocale);
|
||||||
|
TimeZone.setDefault(defaultTimeZone);
|
||||||
|
|
||||||
|
log.debug("yaml locale {}", Locale.getDefault());
|
||||||
|
log.debug("yaml timeZone {}", TimeZone.getDefault().getID());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run( LocalhostApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
12
src/main/java/io/company/localhost/ServletInitializer.java
Normal file
12
src/main/java/io/company/localhost/ServletInitializer.java
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package io.company.localhost;
|
||||||
|
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||||
|
|
||||||
|
public class ServletInitializer extends SpringBootServletInitializer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
|
||||||
|
return application.sources(LocalhostApplication.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
package io.company.localhost.common.annotation;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
@Target({ElementType.METHOD})
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface ParameterCheck {
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
package io.company.localhost.common.annotation;
|
||||||
|
|
||||||
|
import static java.lang.annotation.ElementType.*;
|
||||||
|
import static java.lang.annotation.RetentionPolicy.*;
|
||||||
|
|
||||||
|
import java.lang.annotation.Documented;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
@Documented
|
||||||
|
@Retention(RUNTIME)
|
||||||
|
@Target({ PARAMETER })
|
||||||
|
public @interface ReqMap {
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,53 @@
|
|||||||
|
package io.company.localhost.common.aop;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
import org.aspectj.lang.JoinPoint;
|
||||||
|
import org.aspectj.lang.annotation.AfterReturning;
|
||||||
|
import org.aspectj.lang.annotation.Aspect;
|
||||||
|
import org.aspectj.lang.annotation.Before;
|
||||||
|
import org.aspectj.lang.annotation.Pointcut;
|
||||||
|
import org.aspectj.lang.reflect.MethodSignature;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import io.company.localhost.common.response.ApiResponse;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Aspect
|
||||||
|
@Component
|
||||||
|
public class ParameterAop {
|
||||||
|
|
||||||
|
|
||||||
|
@Pointcut("@annotation(io.company.localhost.common.annotation.ParameterCheck)")
|
||||||
|
private void parameterCheck() {
|
||||||
|
}
|
||||||
|
|
||||||
|
//parameterCheck() 메서드가 실행 되는 지점 이전에 before() 메서드 실행
|
||||||
|
@Before("parameterCheck()")
|
||||||
|
public void before(JoinPoint joinPoint) {
|
||||||
|
|
||||||
|
//실행되는 함수 이름을 가져오고 출력
|
||||||
|
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
|
||||||
|
Method method = methodSignature.getMethod();
|
||||||
|
log.info("{}.{} 메서드 실행", joinPoint.getTarget().getClass().getSimpleName(), method.getName());
|
||||||
|
//메서드에 들어가는 매개변수 배열을 읽어옴
|
||||||
|
Object[] args = joinPoint.getArgs();
|
||||||
|
|
||||||
|
//매개변수 배열의 종류와 값을 출력
|
||||||
|
for (Object arg : args) {
|
||||||
|
log.info("type : {}", arg.getClass().getSimpleName());
|
||||||
|
log.info("value : {}", arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//parameterCheck() 메서드가 종료되는 시점에 afterReturning() 메서드 실행
|
||||||
|
@AfterReturning(value = "parameterCheck()", returning = "obj")
|
||||||
|
public void afterReturning(JoinPoint joinPoint, Object obj) {
|
||||||
|
Object returnObj = obj;
|
||||||
|
if(obj instanceof ApiResponse)
|
||||||
|
returnObj = ((ApiResponse)obj).getData();
|
||||||
|
|
||||||
|
log.info("리턴값 : {}", returnObj);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,25 @@
|
|||||||
|
package io.company.localhost.common.config;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class AuthConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder passwordEncoder() {
|
||||||
|
String encodingId = "bcrypt";
|
||||||
|
Map<String, PasswordEncoder> encoders = new HashMap<>();
|
||||||
|
encoders.put(encodingId, new BCryptPasswordEncoder());
|
||||||
|
DelegatingPasswordEncoder delegatingPasswordEncoder = new DelegatingPasswordEncoder(encodingId, encoders);
|
||||||
|
delegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(new BCryptPasswordEncoder());
|
||||||
|
|
||||||
|
return delegatingPasswordEncoder;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,23 @@
|
|||||||
|
package io.company.localhost.common.config;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||||
|
import org.springframework.boot.web.servlet.ServletComponentScan;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import io.company.localhost.common.constants.LocalhostProject;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
//컴포넌트 스캔, 설정 클래스 바인딩, 서블릿 구성 요소 등록을 처리하는 설정 파일
|
||||||
|
@Slf4j
|
||||||
|
@ComponentScan(basePackages = { LocalhostProject.BASE_PKG })
|
||||||
|
@ConfigurationPropertiesScan(basePackages = { LocalhostProject.BASE_PKG })
|
||||||
|
@ServletComponentScan(basePackages = { LocalhostProject.BASE_PKG })
|
||||||
|
@Configuration
|
||||||
|
public class ComponentScanConfig {
|
||||||
|
|
||||||
|
public ComponentScanConfig() {
|
||||||
|
log.debug("{} default Constructor", this.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,50 @@
|
|||||||
|
package io.company.localhost.common.config;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||||
|
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
|
||||||
|
|
||||||
|
import io.company.localhost.common.filter.SampleFilter;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
//ObjectMapper 를 빈으로 등록
|
||||||
|
//Object to JSON - JSON to Object
|
||||||
|
//JacksonUtil에서 사용됨
|
||||||
|
@Slf4j
|
||||||
|
@Configuration
|
||||||
|
public class JacksonCommonConfig {
|
||||||
|
|
||||||
|
public static Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
|
||||||
|
// @JsonFilter annotation 사용을 위한 default filterProvider 설정
|
||||||
|
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
|
||||||
|
filterProvider.setFailOnUnknownId(false); // 알 수 없는 필드가 있을 경우 오류를 발생시키지 않음
|
||||||
|
filterProvider.addFilter("jacksonFilter", new SampleFilter()); // 사용자 정의 필터 추가
|
||||||
|
|
||||||
|
Jackson2ObjectMapperBuilder mapperBuilder = Jackson2ObjectMapperBuilder.json()
|
||||||
|
.serializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) // null 값은 제외
|
||||||
|
.failOnUnknownProperties(false) // 알 수 없는 속성이 있으면 무시
|
||||||
|
.filters(filterProvider) // 필터 적용
|
||||||
|
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // 날짜를 타임스탬프로 변환하지 않음
|
||||||
|
.featuresToDisable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS) // 기간을 타임스탬프로 변환하지 않음
|
||||||
|
.timeZone(TimeZone.getDefault()) // 기본 타임존 사용
|
||||||
|
.locale(Locale.getDefault()) // 기본 로케일 사용
|
||||||
|
.simpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // 날짜 포맷 지정
|
||||||
|
|
||||||
|
return mapperBuilder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ObjectMapper objectMapper() {
|
||||||
|
ObjectMapper objectMapper = jackson2ObjectMapperBuilder().build();
|
||||||
|
|
||||||
|
return objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,125 @@
|
|||||||
|
package io.company.localhost.common.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.authentication.AuthenticationProvider;
|
||||||
|
import org.springframework.security.authorization.AuthorizationManager;
|
||||||
|
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||||
|
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.core.session.SessionRegistry;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
|
||||||
|
|
||||||
|
import org.springframework.security.web.authentication.RememberMeServices;
|
||||||
|
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
|
||||||
|
import org.springframework.security.web.session.SimpleRedirectSessionInformationExpiredStrategy;
|
||||||
|
|
||||||
|
import io.company.localhost.common.security.dsl.RestApiDsl;
|
||||||
|
import io.company.localhost.common.security.handler.RestAuthenticationEntryPointHandler;
|
||||||
|
import io.company.localhost.common.filter.WebCorsFilter;
|
||||||
|
import io.company.localhost.common.security.handler.MemberAuthFailureHandler;
|
||||||
|
import io.company.localhost.common.security.handler.MemberAuthSuccessHandler;
|
||||||
|
import io.company.localhost.common.security.handler.RestAccessDeniedHandler;
|
||||||
|
import io.company.localhost.common.security.service.CustomRememberMeServices;
|
||||||
|
import io.company.localhost.common.security.service.MemberPrincipalDetailService;
|
||||||
|
import io.company.localhost.common.security.session.AuthenticationSessionControlStrategy;
|
||||||
|
import io.company.localhost.common.security.session.CustomSessionRegistryImpl;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SecurityConfig {
|
||||||
|
|
||||||
|
// 의존성 주입
|
||||||
|
private final AuthenticationProvider memberAuthenticatorProvider;
|
||||||
|
private final MemberPrincipalDetailService userDetailsService;
|
||||||
|
private final MemberAuthFailureHandler failureHandler;
|
||||||
|
private final AuthorizationManager<RequestAuthorizationContext> authorizationManager;
|
||||||
|
|
||||||
|
// 세션 관련 상수 설정
|
||||||
|
final int MAX_SESSION = 1; // 최대 세션 수 설정 (한 사용자당 한 세션)
|
||||||
|
final boolean MAX_SESSION_PRENT = false; // 최대 세션 수 초과 시 로그인 방지 여부
|
||||||
|
final String REMEMBER = "remember"; // 'remember me' 기능을 위한 키
|
||||||
|
final String REMEMBER_KEY = "rememberSecretKey";
|
||||||
|
final int REMEMBER_TIME = 60 * 60 * 24 * 365; // 'remember me' 기능의 유효기간 (1년)
|
||||||
|
|
||||||
|
// API 경로 관련 상수 설정
|
||||||
|
final String SECURITY_BASE_URL = "/api/user";
|
||||||
|
final String LOGIN_URL = SECURITY_BASE_URL + "/login";
|
||||||
|
final String INVALID_URL = SECURITY_BASE_URL + "/login/duplicated-login";
|
||||||
|
|
||||||
|
// 보안 필터 체인 설정
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain restSecurityFilterChain(HttpSecurity http, WebCorsFilter webCorsFilter) throws Exception {
|
||||||
|
|
||||||
|
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManagerBuilder.class)
|
||||||
|
.authenticationProvider(memberAuthenticatorProvider)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
MemberAuthSuccessHandler successHandler = new MemberAuthSuccessHandler(rememberMeServices());
|
||||||
|
|
||||||
|
http
|
||||||
|
.securityMatcher("/api/**") // '/api/**' 경로에 대해서만 보안 적용
|
||||||
|
.authorizeHttpRequests(auth ->
|
||||||
|
auth.anyRequest().access(authorizationManager) // 모든 요청에 대해 권한 관리
|
||||||
|
)
|
||||||
|
// 세션 관리 설정
|
||||||
|
.sessionManagement(session ->
|
||||||
|
session
|
||||||
|
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // 세션이 필요한 경우에만 생성
|
||||||
|
.sessionAuthenticationStrategy(sessionControlStrategy()) // 세션 제어 전략 설정
|
||||||
|
.maximumSessions(MAX_SESSION) // 최대 세션 수 설정
|
||||||
|
.maxSessionsPreventsLogin(MAX_SESSION_PRENT) // 최대 세션 수 초과 시 로그인 방지 여부
|
||||||
|
.expiredSessionStrategy(new SimpleRedirectSessionInformationExpiredStrategy(INVALID_URL)) // 세션 만료 시 리디렉션
|
||||||
|
.sessionRegistry(sessionRegistry()) // 세션 레지스트리 설정
|
||||||
|
)
|
||||||
|
.csrf(csrf -> csrf.ignoringRequestMatchers("/api/**")) // CSRF 비활성화
|
||||||
|
.addFilter(webCorsFilter.corsFilter()) // CORS 필터 추가
|
||||||
|
.authenticationManager(authenticationManager) // 인증 매니저 설정
|
||||||
|
// 예외 처리 설정
|
||||||
|
.exceptionHandling(exception ->
|
||||||
|
exception
|
||||||
|
.authenticationEntryPoint(new RestAuthenticationEntryPointHandler()) // 인증 오류 처리
|
||||||
|
.accessDeniedHandler(new RestAccessDeniedHandler()) // 접근 거부 처리
|
||||||
|
)
|
||||||
|
.rememberMe(rm ->
|
||||||
|
rm
|
||||||
|
.key(REMEMBER_KEY)
|
||||||
|
.tokenValiditySeconds(REMEMBER_TIME)
|
||||||
|
.rememberMeParameter(REMEMBER)
|
||||||
|
.rememberMeServices(rememberMeServices()))
|
||||||
|
// 로그인 성공 및 실패 핸들러 설정
|
||||||
|
.with(new RestApiDsl<>(), resDsl ->
|
||||||
|
resDsl
|
||||||
|
.loginSuccessHandler(successHandler) // 로그인 성공 시 핸들러 설정
|
||||||
|
.loginFailureHandler(failureHandler) // 로그인 실패 시 핸들러 설정
|
||||||
|
.loginProcessingUrl(LOGIN_URL) // 로그인 처리 URL 설정
|
||||||
|
);
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public RememberMeServices rememberMeServices(){
|
||||||
|
return new CustomRememberMeServices(REMEMBER_KEY , userDetailsService);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 세션 관리
|
||||||
|
protected ConcurrentSessionControlAuthenticationStrategy sessionControlStrategy() {
|
||||||
|
AuthenticationSessionControlStrategy sessionControlStrategy = new AuthenticationSessionControlStrategy(sessionRegistry());
|
||||||
|
sessionControlStrategy.setMaximumSessions(MAX_SESSION); // 최대 세션 수 설정
|
||||||
|
sessionControlStrategy.setExceptionIfMaximumExceeded(MAX_SESSION_PRENT); // 세션 초과 시 예외 처리 여부 설정
|
||||||
|
return sessionControlStrategy;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 세션 레지스트리 설정
|
||||||
|
@Bean("sessionRegistry")
|
||||||
|
SessionRegistry sessionRegistry() {
|
||||||
|
return new CustomSessionRegistryImpl(); // 커스텀 세션 레지스트리 구현체 사용
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,72 @@
|
|||||||
|
package io.company.localhost.common.config;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||||
|
import org.springframework.web.servlet.LocaleResolver;
|
||||||
|
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
|
||||||
|
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||||
|
|
||||||
|
import io.company.localhost.common.resolver.RequestToMapArgumentResolver;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class WebMvcConfig implements WebMvcConfigurer {
|
||||||
|
|
||||||
|
public static final String WILD_CARD = "/**";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
|
// 여기서 인터셉터를 추가할 수 있음
|
||||||
|
// 예: registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 리소스 핸들러를 설정
|
||||||
|
@Override
|
||||||
|
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||||
|
registry
|
||||||
|
.addResourceHandler("/index.html")
|
||||||
|
.addResourceLocations("classpath:/static/index.html", "/index.html");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Controller의 파라미터를 처리할 Resolver 등록
|
||||||
|
@Override
|
||||||
|
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
|
||||||
|
// RequestToMapArgumentResolver는 요청을 Map으로 변환하여 파라미터로 받을 수 있도록 설정
|
||||||
|
resolvers.add(new RequestToMapArgumentResolver());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 클라이언트가 원하는 미디어 타입에 따라 반환할 타입 설정
|
||||||
|
@Override
|
||||||
|
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
|
||||||
|
// 기본 응답 타입을 JSON으로 설정
|
||||||
|
configurer.defaultContentType(MediaType.APPLICATION_JSON)
|
||||||
|
.ignoreAcceptHeader(true) // Accept 헤더를 무시하고 기본값을 JSON으로 설정
|
||||||
|
|
||||||
|
// "mediaType" 파라미터 값에 따라 반환할 미디어 타입 설정
|
||||||
|
.favorParameter(true) // 요청 파라미터로 mediaType을 사용할 수 있게 설정
|
||||||
|
.parameterName("mediaType") // 파라미터 이름 설정
|
||||||
|
.mediaType("xml", MediaType.APPLICATION_XML) // "mediaType=xml"이면 XML 응답
|
||||||
|
.mediaType("json", MediaType.APPLICATION_JSON); // "mediaType=json"이면 JSON 응답
|
||||||
|
}
|
||||||
|
|
||||||
|
//세션을 이용하여 언어와 시간대 설정
|
||||||
|
@Bean
|
||||||
|
LocaleResolver localeResolver() {
|
||||||
|
Locale defaultLocale = Locale.getDefault();
|
||||||
|
TimeZone defaultTimeZone = TimeZone.getDefault();
|
||||||
|
|
||||||
|
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
|
||||||
|
localeResolver.setDefaultLocale(defaultLocale);
|
||||||
|
localeResolver.setDefaultTimeZone(defaultTimeZone);
|
||||||
|
|
||||||
|
return localeResolver;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,34 @@
|
|||||||
|
package io.company.localhost.common.config.mybatis;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.InitializingBean;
|
||||||
|
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import net.sf.log4jdbc.sql.jdbcapi.DataSourceSpy;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Configuration
|
||||||
|
public class DataSourceConfig implements InitializingBean {
|
||||||
|
|
||||||
|
@Bean(name = "dataSource")
|
||||||
|
DataSource dataSource(DataSourceProperties dataSourceProperties) {
|
||||||
|
DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
|
||||||
|
dataSourceBuilder.driverClassName(dataSourceProperties.getDriverClassName());
|
||||||
|
dataSourceBuilder.url(dataSourceProperties.getJdbcUrl());
|
||||||
|
dataSourceBuilder.username(dataSourceProperties.getUsername());
|
||||||
|
dataSourceBuilder.password(dataSourceProperties.getPassword());
|
||||||
|
|
||||||
|
return dataSourceBuilder.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterPropertiesSet() throws Exception {
|
||||||
|
log.debug("{}",this.getClass().getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,25 @@
|
|||||||
|
package io.company.localhost.common.config.mybatis;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||||
|
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@ConfigurationProperties(prefix = "datasource.localhost")
|
||||||
|
public class DataSourceProperties {
|
||||||
|
|
||||||
|
private String driverClassName;
|
||||||
|
private String jdbcUrl;
|
||||||
|
private String username;
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
package io.company.localhost.common.config.mybatis;
|
||||||
|
|
||||||
|
import org.apache.ibatis.logging.Log;
|
||||||
|
import org.apache.ibatis.logging.LogFactory;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class MyBatisCustomLogger implements Log {
|
||||||
|
|
||||||
|
private final Logger logger;
|
||||||
|
|
||||||
|
public MyBatisCustomLogger(String clazz) {
|
||||||
|
this.logger = LoggerFactory.getLogger(clazz);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isDebugEnabled() {
|
||||||
|
return logger.isDebugEnabled();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isTraceEnabled() {
|
||||||
|
return logger.isTraceEnabled();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void error(String s, Throwable e) {
|
||||||
|
logger.error(s, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void error(String s) {
|
||||||
|
logger.error(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void debug(String s) {
|
||||||
|
// 줄바꿈을 제거하고 한 줄로 로그 출력
|
||||||
|
logger.debug(s.replaceAll("[\r\n]+", " "));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void trace(String s) {
|
||||||
|
// 줄바꿈을 제거하고 한 줄로 로그 출력
|
||||||
|
logger.trace(s.replaceAll("[\r\n]+", " "));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void warn(String s) {
|
||||||
|
logger.warn(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
static {
|
||||||
|
LogFactory.useCustomLogging(MyBatisCustomLogger.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,67 @@
|
|||||||
|
package io.company.localhost.common.config.mybatis;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
import org.apache.ibatis.session.ExecutorType;
|
||||||
|
import org.apache.ibatis.session.SqlSessionFactory;
|
||||||
|
import org.apache.ibatis.type.JdbcType;
|
||||||
|
|
||||||
|
import org.mybatis.spring.SqlSessionFactoryBean;
|
||||||
|
import org.mybatis.spring.SqlSessionTemplate;
|
||||||
|
import org.mybatis.spring.annotation.MapperScan;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.core.io.Resource;
|
||||||
|
|
||||||
|
import io.company.localhost.common.constants.LocalhostProject;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Configuration
|
||||||
|
@MapperScan(basePackages = LocalhostProject.BASE_PKG
|
||||||
|
,sqlSessionFactoryRef = "sqlSessionFactory")
|
||||||
|
public class MybatisConfig {
|
||||||
|
|
||||||
|
@Value("${mybatis.mapper-locations}")
|
||||||
|
String mapperLocations;
|
||||||
|
|
||||||
|
@Bean(name = "sqlSessionFactory")
|
||||||
|
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource")DataSource dataSource,ApplicationContext applicationContext) throws Exception {
|
||||||
|
|
||||||
|
Resource[] mapperResources = applicationContext.getResources(mapperLocations);
|
||||||
|
|
||||||
|
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
|
||||||
|
sqlSessionFactoryBean.setDataSource(dataSource);
|
||||||
|
sqlSessionFactoryBean.setMapperLocations(mapperResources);
|
||||||
|
|
||||||
|
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
|
||||||
|
|
||||||
|
org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
|
||||||
|
|
||||||
|
//스네이크 케이스 자동 카멜 케이스로 매핑
|
||||||
|
configuration.setMapUnderscoreToCamelCase(true);
|
||||||
|
//결과 매핑에서 null 값을 명시적으로 설정
|
||||||
|
configuration.setCallSettersOnNulls(true);
|
||||||
|
//JDBC 에서 null 값을 처리하는 방식 정의
|
||||||
|
configuration.setJdbcTypeForNull(JdbcType.NULL);
|
||||||
|
//MyBatis 의 캐시 기능 활성화
|
||||||
|
configuration.setCacheEnabled(true);
|
||||||
|
//자동 생성된 키를 사용할 수 있도록 설정
|
||||||
|
configuration.setUseGeneratedKeys(true);
|
||||||
|
//SQL 실행 객체를 재사용하여 성능 최적화
|
||||||
|
configuration.setDefaultExecutorType(ExecutorType.REUSE);
|
||||||
|
//SQL 실행 시간 초과를 1000초로 설정
|
||||||
|
configuration.setDefaultStatementTimeout(1000);
|
||||||
|
|
||||||
|
return sqlSessionFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean(name = "sqlSessionTemplate")
|
||||||
|
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
|
||||||
|
return new SqlSessionTemplate(sqlSessionFactory);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,121 @@
|
|||||||
|
package io.company.localhost.common.config.mybatis;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
import org.springframework.aop.Advisor;
|
||||||
|
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
|
||||||
|
import org.springframework.aop.support.DefaultPointcutAdvisor;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||||
|
import org.springframework.transaction.PlatformTransactionManager;
|
||||||
|
import org.springframework.transaction.TransactionDefinition;
|
||||||
|
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
|
||||||
|
import org.springframework.transaction.interceptor.RollbackRuleAttribute;
|
||||||
|
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;
|
||||||
|
import org.springframework.transaction.interceptor.TransactionInterceptor;
|
||||||
|
|
||||||
|
|
||||||
|
import io.company.localhost.common.constants.LocalhostProject;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* naming rule 은 method 기반으로 이뤄진다.
|
||||||
|
* select 가 포함되면 읽기전용 예) selectUserId select
|
||||||
|
* NewTx 독립적인 트랙잭션 예) insertNewTxMember insert
|
||||||
|
* NestedTx 중첩 트랜잭션 예) updateNestedTxMember 특수 상황에 사용
|
||||||
|
* 나머지는 기본 트랜잭션이 적용된다. update, delete
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Configuration
|
||||||
|
public class TransactionConfig {
|
||||||
|
|
||||||
|
// 30 seconds
|
||||||
|
public static final int TX_METHOD_TIMEOUT_SECONDS = 30;
|
||||||
|
|
||||||
|
private static final String AOP_POINTCUT_EXPRESSION = "execution(* " + LocalhostProject.BASE_PKG
|
||||||
|
+ "..service..*Service.*(..))";
|
||||||
|
|
||||||
|
@Bean("txInterceptor")
|
||||||
|
TransactionInterceptor txInterceptor(@Qualifier("txManager") PlatformTransactionManager txManager) {
|
||||||
|
|
||||||
|
TransactionInterceptor txInterceptor = new TransactionInterceptor();
|
||||||
|
|
||||||
|
Properties txAttributes = new Properties();
|
||||||
|
|
||||||
|
List<RollbackRuleAttribute> rollbackRules = new ArrayList<RollbackRuleAttribute>();
|
||||||
|
rollbackRules.add(new RollbackRuleAttribute(Exception.class));
|
||||||
|
|
||||||
|
// default
|
||||||
|
// DefaultTransactionAttribute readOnlyAttribute = new
|
||||||
|
// DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED);
|
||||||
|
DefaultTransactionAttribute readOnlyAttribute = new DefaultTransactionAttribute(
|
||||||
|
TransactionDefinition.PROPAGATION_SUPPORTS);
|
||||||
|
readOnlyAttribute.setReadOnly(true);
|
||||||
|
readOnlyAttribute.setTimeout(TX_METHOD_TIMEOUT_SECONDS);
|
||||||
|
|
||||||
|
// REQUIRED
|
||||||
|
RuleBasedTransactionAttribute writeTxAttribute = new RuleBasedTransactionAttribute(
|
||||||
|
TransactionDefinition.PROPAGATION_REQUIRED, rollbackRules);
|
||||||
|
writeTxAttribute.setTimeout(TX_METHOD_TIMEOUT_SECONDS);
|
||||||
|
|
||||||
|
// REQUIRED_NEW
|
||||||
|
// @Transactional로 처리할 수 있으나 호출자에서 트랜잭션 구분이 모호하다고 하여 명칭으로 구분함.
|
||||||
|
RuleBasedTransactionAttribute newTxAttribute = new RuleBasedTransactionAttribute(
|
||||||
|
TransactionDefinition.PROPAGATION_REQUIRES_NEW, rollbackRules);
|
||||||
|
newTxAttribute.setTimeout(TX_METHOD_TIMEOUT_SECONDS);
|
||||||
|
|
||||||
|
// NESTED
|
||||||
|
RuleBasedTransactionAttribute nestedTxAttribute = new RuleBasedTransactionAttribute(
|
||||||
|
TransactionDefinition.PROPAGATION_NESTED, rollbackRules);
|
||||||
|
nestedTxAttribute.setTimeout(TX_METHOD_TIMEOUT_SECONDS);
|
||||||
|
|
||||||
|
// naming 설정
|
||||||
|
txAttributes.setProperty("select*", readOnlyAttribute.toString());
|
||||||
|
txAttributes.setProperty("*NewTx*", newTxAttribute.toString());
|
||||||
|
txAttributes.setProperty("*NestedTx*", nestedTxAttribute.toString());
|
||||||
|
txAttributes.setProperty("*", writeTxAttribute.toString());
|
||||||
|
|
||||||
|
// transaction interceptor 설정
|
||||||
|
txInterceptor.setTransactionAttributes(txAttributes);
|
||||||
|
txInterceptor.setTransactionManager(txManager);
|
||||||
|
|
||||||
|
return txInterceptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean("txAdvisor")
|
||||||
|
Advisor txAdvisor(@Qualifier("txInterceptor") TransactionInterceptor txInterceptor) {
|
||||||
|
|
||||||
|
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
|
||||||
|
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
|
||||||
|
|
||||||
|
return new DefaultPointcutAdvisor(pointcut, txInterceptor);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean("txManager")
|
||||||
|
PlatformTransactionManager txManager(@Qualifier("dataSource") DataSource dataSource) {
|
||||||
|
|
||||||
|
DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource);
|
||||||
|
txManager.setGlobalRollbackOnParticipationFailure(false);
|
||||||
|
|
||||||
|
log.debug("txManager {}", txManager);
|
||||||
|
|
||||||
|
return txManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
static BeanDefinitionRegistryPostProcessor transactionRegistryBeanPostProcessorRemover() {
|
||||||
|
return registry -> {
|
||||||
|
registry.removeBeanDefinition("healthEndpointGroupsBeanPostProcessor");
|
||||||
|
registry.removeBeanDefinition("observationRegistryPostProcessor");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,10 @@
|
|||||||
|
package io.company.localhost.common.constants;
|
||||||
|
|
||||||
|
public final class LocalhostProject {
|
||||||
|
|
||||||
|
public static final String BASE_PKG = "io.company.localhost";
|
||||||
|
|
||||||
|
private LocalhostProject() {
|
||||||
|
//
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,51 @@
|
|||||||
|
package io.company.localhost.common.context;
|
||||||
|
|
||||||
|
import org.springframework.beans.BeansException;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.context.ApplicationContextAware;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
// Spring Bean을 동적으로 가져올 수 있음
|
||||||
|
// ex) MyService myService = applicationContext.getBean(MyService.class);
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class ApplicationContextProvider implements ApplicationContextAware {
|
||||||
|
|
||||||
|
// ApplicationContext를 저장할 static 변수
|
||||||
|
private static ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 기본 생성자
|
||||||
|
* 생성자에서 해당 클래스의 로그를 출력합니다.
|
||||||
|
*/
|
||||||
|
public ApplicationContextProvider() {
|
||||||
|
// 기본 생성자 호출 시 로그를 출력
|
||||||
|
log.debug("{} default Constructor", this.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ApplicationContext를 설정하는 메소드.
|
||||||
|
* Spring 컨테이너에서 제공하는 애플리케이션 컨텍스트를 받아서 static 변수에 저장.
|
||||||
|
*
|
||||||
|
* @param applicationCtx ApplicationContext 객체
|
||||||
|
* @throws BeansException 애플리케이션 컨텍스트 설정 중 발생할 수 있는 예외
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void setApplicationContext(ApplicationContext applicationCtx) throws BeansException {
|
||||||
|
// 전달된 ApplicationContext를 static 변수에 저장
|
||||||
|
applicationContext = applicationCtx;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 저장된 ApplicationContext를 반환하는 정적 메소드
|
||||||
|
*
|
||||||
|
* @return 저장된 ApplicationContext 객체
|
||||||
|
*/
|
||||||
|
public static ApplicationContext getContext() {
|
||||||
|
// static 변수에 저장된 ApplicationContext 반환
|
||||||
|
return applicationContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
44
src/main/java/io/company/localhost/common/dto/MapDto.java
Normal file
44
src/main/java/io/company/localhost/common/dto/MapDto.java
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package io.company.localhost.common.dto;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.apache.commons.collections.map.ListOrderedMap;
|
||||||
|
import org.springframework.util.ObjectUtils;
|
||||||
|
|
||||||
|
public class MapDto extends ListOrderedMap {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = -5354101794266218602L;
|
||||||
|
|
||||||
|
public MapDto() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public MapDto(Map<String, Object> map) {
|
||||||
|
super(map);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 주어진 키에 해당하는 값을 String 타입으로 반환합니다.
|
||||||
|
* 값이 null인 경우, null을 반환합니다.
|
||||||
|
*
|
||||||
|
* @param key Map에서 값을 검색할 키
|
||||||
|
* @return 해당 키에 대한 값(String 타입), 값이 없으면 null
|
||||||
|
*/
|
||||||
|
public String getString(String key) {
|
||||||
|
return (String) get(key); // key에 해당하는 값을 String으로 캐스팅하여 반환
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 주어진 키에 해당하는 값을 BigDecimal 타입으로 반환합니다.
|
||||||
|
* 값이 null이거나 비어있으면 null을 반환합니다.
|
||||||
|
*
|
||||||
|
* @param key Map에서 값을 검색할 키
|
||||||
|
* @return 해당 키에 대한 값(BigDecimal 타입), 값이 없으면 null
|
||||||
|
*/
|
||||||
|
public BigDecimal getBigDecimal(String key) {
|
||||||
|
// key에 해당하는 값을 String으로 가져오고, BigDecimal로 변환하여 반환
|
||||||
|
return ObjectUtils.isEmpty(get(key)) ? null : new BigDecimal(getString(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
package io.company.localhost.common.exception;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.validation.FieldError;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
|
||||||
|
import lombok.Builder;
|
||||||
|
|
||||||
|
@Builder
|
||||||
|
public record ErrorResponse(long code,String status, String message,
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_EMPTY) List<ValidationError> errors) {
|
||||||
|
|
||||||
|
@Builder
|
||||||
|
public static class ValidationError {
|
||||||
|
|
||||||
|
private final String field;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
public static ValidationError of(final FieldError fieldError) {
|
||||||
|
return ValidationError.builder()
|
||||||
|
.field(fieldError.getField())
|
||||||
|
.message(fieldError.getDefaultMessage())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,92 @@
|
|||||||
|
package io.company.localhost.common.exception;
|
||||||
|
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
|
||||||
|
import io.company.localhost.common.exception.code.ErrorCode;
|
||||||
|
|
||||||
|
public class ErrorResult {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 주어진 에러 코드를 기반으로 적절한 HTTP 상태 코드와 에러 메시지를 포함하는 ResponseEntity를 반환합니다.
|
||||||
|
*
|
||||||
|
* @param errorCode 에러 코드를 나타내는 Enum (ErrorCode)
|
||||||
|
* @return HTTP 응답 (ResponseEntity)
|
||||||
|
*/
|
||||||
|
public static ResponseEntity<Object> handleExceptionInternal(ErrorCode errorCode) {
|
||||||
|
// ErrorCode에서 HTTP 상태 코드 가져오기
|
||||||
|
// 에러 응답을 만들어 ResponseEntity에 포함하여 반환
|
||||||
|
return ResponseEntity.status(errorCode.getHttpStatus())
|
||||||
|
.body(makeErrorResponse(errorCode));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 주어진 에러 코드를 기반으로 에러 응답 객체를 생성합니다.
|
||||||
|
*
|
||||||
|
* @param errorCode 에러 코드를 나타내는 Enum (ErrorCode)
|
||||||
|
* @return ErrorResponse 객체
|
||||||
|
*/
|
||||||
|
public static ErrorResponse makeErrorResponse(ErrorCode errorCode) {
|
||||||
|
// ErrorCode의 코드, 상태 및 메시지를 기반으로 ErrorResponse 객체를 생성
|
||||||
|
return ErrorResponse.builder()
|
||||||
|
.code(errorCode.getCode())
|
||||||
|
.status(errorCode.name()) // 에러 코드 이름을 상태로 설정
|
||||||
|
.message(errorCode.getMessage()) // 에러 메시지 설정
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 에러 메시지를 추가로 받아서 ResponseEntity를 반환하는 메소드입니다.
|
||||||
|
*
|
||||||
|
* @param errorCode 에러 코드를 나타내는 Enum (ErrorCode)
|
||||||
|
* @param message 사용자 지정 메시지
|
||||||
|
* @return HTTP 응답 (ResponseEntity)
|
||||||
|
*/
|
||||||
|
public static ResponseEntity<Object> handleExceptionInternal(ErrorCode errorCode, String message) {
|
||||||
|
// ErrorCode에서 HTTP 상태 코드 가져오기
|
||||||
|
// 에러 메시지를 사용자 정의 메시지로 설정
|
||||||
|
return ResponseEntity.status(errorCode.getHttpStatus())
|
||||||
|
.body(makeErrorResponse(errorCode, message));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 에러 메시지를 추가로 받아서 ErrorResponse 객체를 생성하는 메소드입니다.
|
||||||
|
*
|
||||||
|
* @param errorCode 에러 코드를 나타내는 Enum (ErrorCode)
|
||||||
|
* @param message 사용자 지정 메시지
|
||||||
|
* @return ErrorResponse 객체
|
||||||
|
*/
|
||||||
|
public static ErrorResponse makeErrorResponse(ErrorCode errorCode, String message) {
|
||||||
|
// ErrorCode의 코드, 상태 및 사용자 지정 메시지를 기반으로 ErrorResponse 객체를 생성
|
||||||
|
return ErrorResponse.builder()
|
||||||
|
.code(errorCode.getCode())
|
||||||
|
.status(errorCode.name()) // 에러 코드 이름을 상태로 설정
|
||||||
|
.message(message) // 사용자 지정 메시지 설정
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// 아래는 BindException에 대한 예외 처리 부분이 주석 처리되어 있습니다.
|
||||||
|
// 사용자가 폼 바인딩에서 발생한 오류를 처리하는 예시 코드입니다.
|
||||||
|
|
||||||
|
private ResponseEntity<Object> handleExceptionInternal(BindException e, ErrorCode errorCode) {
|
||||||
|
// BindException에서 에러가 발생한 필드와 오류 메시지를 가져와서 처리
|
||||||
|
return ResponseEntity.status(errorCode.getHttpStatus())
|
||||||
|
.body(makeErrorResponse(e, errorCode));
|
||||||
|
}
|
||||||
|
|
||||||
|
private ErrorResponse makeErrorResponse(BindException e, ErrorCode errorCode) {
|
||||||
|
// 폼 바인딩 에러에서 발생한 필드 오류들을 가져와서 ErrorResponse로 변환
|
||||||
|
List<ErrorResponse.ValidationError> validationErrorList = e.getBindingResult()
|
||||||
|
.getFieldErrors()
|
||||||
|
.stream()
|
||||||
|
.map(ErrorResponse.ValidationError::of)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
return ErrorResponse.builder()
|
||||||
|
.code(errorCode.name())
|
||||||
|
.message(errorCode.getMessage())
|
||||||
|
.errors(validationErrorList) // 필드 오류 목록을 추가
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
}
|
||||||
@ -0,0 +1,43 @@
|
|||||||
|
package io.company.localhost.common.exception;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||||
|
|
||||||
|
import io.company.localhost.common.exception.code.CommonErrorCode;
|
||||||
|
import io.company.localhost.common.exception.code.ErrorCode;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestControllerAdvice(annotations = RestController.class)
|
||||||
|
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||||
|
|
||||||
|
@ExceptionHandler(RestApiException.class)
|
||||||
|
public ResponseEntity<Object> handleCustomException(RestApiException e) {
|
||||||
|
ErrorCode errorCode = e.getErrorCode();
|
||||||
|
return ErrorResult.handleExceptionInternal(errorCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(IllegalArgumentException.class)
|
||||||
|
public ResponseEntity<Object> handleIllegalArgument(IllegalArgumentException e) {
|
||||||
|
log.warn("handleIllegalArgument", e);
|
||||||
|
ErrorCode errorCode = CommonErrorCode.INVALID_PARAMETER;
|
||||||
|
return ErrorResult.handleExceptionInternal(errorCode, e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ExceptionHandler({Exception.class})
|
||||||
|
public ResponseEntity<Object> handleAllException(Exception ex) {
|
||||||
|
log.warn("handleAllException", ex);
|
||||||
|
ErrorCode errorCode = CommonErrorCode.INTERNAL_SERVER_ERROR;
|
||||||
|
return ErrorResult.handleExceptionInternal(errorCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
package io.company.localhost.common.exception;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||||
|
|
||||||
|
import io.company.localhost.common.exception.code.CommonErrorCode;
|
||||||
|
import io.company.localhost.common.exception.code.ErrorCode;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestControllerAdvice
|
||||||
|
public class NotFoundHandler {
|
||||||
|
|
||||||
|
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||||
|
@ExceptionHandler(NoHandlerFoundException.class)
|
||||||
|
public ResponseEntity<Object> noHandlerFoundArgument(NoHandlerFoundException e) {
|
||||||
|
log.warn("NoHandlerFoundException", e);
|
||||||
|
ErrorCode errorCode = CommonErrorCode.RESOURCE_NOT_FOUND;
|
||||||
|
return ErrorResult.handleExceptionInternal(errorCode, errorCode.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
package io.company.localhost.common.exception;
|
||||||
|
|
||||||
|
import io.company.localhost.common.exception.code.ErrorCode;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class RestApiException extends RuntimeException {
|
||||||
|
|
||||||
|
private final ErrorCode errorCode;
|
||||||
|
}
|
||||||
@ -0,0 +1,21 @@
|
|||||||
|
package io.company.localhost.common.exception.code;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public enum CommonErrorCode implements ErrorCode {
|
||||||
|
|
||||||
|
INVALID_PARAMETER(HttpStatus.BAD_REQUEST.value(),HttpStatus.BAD_REQUEST,"잘못된 매개변수가 포함되었습니다."),
|
||||||
|
RESOURCE_NOT_FOUND(HttpStatus.NOT_FOUND.value(),HttpStatus.NOT_FOUND,"리소스가 존재하지 않습니다"),
|
||||||
|
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(),HttpStatus.INTERNAL_SERVER_ERROR,"내부 서버 오류"),
|
||||||
|
;
|
||||||
|
|
||||||
|
private final long code;
|
||||||
|
private final HttpStatus httpStatus;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
package io.company.localhost.common.exception.code;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
|
||||||
|
public interface ErrorCode {
|
||||||
|
|
||||||
|
String name();
|
||||||
|
|
||||||
|
long getCode();
|
||||||
|
|
||||||
|
HttpStatus getHttpStatus();
|
||||||
|
|
||||||
|
String getMessage();
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
package io.company.localhost.common.exception.code;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
|
||||||
|
import io.company.localhost.common.response.ApiResponse;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public enum UserErrorCode implements ErrorCode {
|
||||||
|
|
||||||
|
NOT_AUTH_USER(HttpStatus.UNAUTHORIZED.value(),HttpStatus.UNAUTHORIZED ,"로그인이 필요합니다."),
|
||||||
|
INACTIVE_USER(HttpStatus.FORBIDDEN.value(),HttpStatus.FORBIDDEN,"권한이 필요합니다.");
|
||||||
|
|
||||||
|
private final long code;
|
||||||
|
private final HttpStatus httpStatus;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
|
||||||
|
public ApiResponse<?> getApiResponse() {
|
||||||
|
return ApiResponse.error(this.getHttpStatus() , this.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,47 @@
|
|||||||
|
package io.company.localhost.common.filter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import io.company.localhost.common.wrapper.CachedBodyRequestWrapper;
|
||||||
|
import jakarta.servlet.Filter;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.FilterConfig;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.ServletRequest;
|
||||||
|
import jakarta.servlet.ServletResponse;
|
||||||
|
import jakarta.servlet.annotation.WebFilter;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CachedBodyRequestWrapper 를 사용하여
|
||||||
|
* HTTP 요청의 본문을 캐시하고, 해당 본문을 여러 번 읽을 수 있도록 하는 것
|
||||||
|
* WebFilter 는 javaEE 기반이라 config 설정하면 Spring boot 내장 컨테이너까지 적용가능
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@WebFilter("/*")
|
||||||
|
public class RequestCachingFilter implements Filter {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init(FilterConfig filterConfig) throws ServletException {
|
||||||
|
// 필터 초기화 (필요한 경우)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
|
||||||
|
throws IOException, ServletException {
|
||||||
|
|
||||||
|
if (request instanceof HttpServletRequest) {
|
||||||
|
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||||
|
CachedBodyRequestWrapper wrappedRequest = new CachedBodyRequestWrapper(httpRequest);
|
||||||
|
chain.doFilter(wrappedRequest, response);
|
||||||
|
} else {
|
||||||
|
chain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void destroy() {
|
||||||
|
// 필터 종료 (필요한 경우)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,43 @@
|
|||||||
|
package io.company.localhost.common.filter;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonGenerator;
|
||||||
|
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||||
|
import com.fasterxml.jackson.databind.ser.PropertyWriter;
|
||||||
|
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
|
||||||
|
|
||||||
|
import io.company.localhost.common.annotation.ReqMap;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
//Object를 Json으로 변환할 때 적용
|
||||||
|
@Slf4j
|
||||||
|
public class SampleFilter extends SimpleBeanPropertyFilter {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 필드를 직렬화할 때 호출되는 메소드
|
||||||
|
*
|
||||||
|
* @param pojo 직렬화할 객체
|
||||||
|
* @param jgen JSON 생성기
|
||||||
|
* @param provider 직렬화 제공자
|
||||||
|
* @param writer 직렬화할 필드에 대한 메타데이터
|
||||||
|
* @throws Exception 직렬화 과정에서 발생할 수 있는 예외
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer)
|
||||||
|
throws Exception {
|
||||||
|
|
||||||
|
// 필드 직렬화 전에 로그를 출력하여 필드 직렬화 여부를 확인
|
||||||
|
log.debug("serializeAsField {}", pojo.getClass()); // 직렬화하려는 객체의 클래스 로그 출력
|
||||||
|
log.debug("serializeAsField {}", pojo); // 직렬화하려는 객체의 내용 로그 출력
|
||||||
|
|
||||||
|
// 필드에 @ReqMap 어노테이션이 붙어있는지 확인
|
||||||
|
Annotation anno = writer.getAnnotation(ReqMap.class);
|
||||||
|
|
||||||
|
// @ReqMap 어노테이션이 없으면 기본 직렬화 처리
|
||||||
|
if (anno == null) {
|
||||||
|
super.serializeAsField(pojo, jgen, provider, writer);
|
||||||
|
}
|
||||||
|
// @ReqMap 어노테이션이 있으면 직렬화하지 않음(아무것도 하지 않음)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,25 @@
|
|||||||
|
package io.company.localhost.common.filter;
|
||||||
|
|
||||||
|
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 WebCorsFilter {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CorsFilter corsFilter() {
|
||||||
|
|
||||||
|
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||||
|
CorsConfiguration config = new CorsConfiguration();
|
||||||
|
config.setAllowCredentials(true);
|
||||||
|
config.addAllowedOriginPattern("*");
|
||||||
|
config.addAllowedHeader("*");
|
||||||
|
config.addAllowedMethod("*");
|
||||||
|
source.registerCorsConfiguration("/api/**", config);
|
||||||
|
|
||||||
|
return new CorsFilter(source);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,106 @@
|
|||||||
|
package io.company.localhost.common.resolver;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||||
|
import org.springframework.web.context.request.NativeWebRequest;
|
||||||
|
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
|
||||||
|
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||||
|
|
||||||
|
import io.company.localhost.common.annotation.ReqMap;
|
||||||
|
import io.company.localhost.common.dto.MapDto;
|
||||||
|
import io.company.localhost.utils.JacksonUtil;
|
||||||
|
import io.company.localhost.utils.WebUtil;
|
||||||
|
import io.company.localhost.common.webEnum.WebEnum;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class RequestToMapArgumentResolver extends HandlerMethodArgumentResolverComposite {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 요청 파라미터에 @ReqMap 어노테이션이 있는지 확인하는 메소드
|
||||||
|
*
|
||||||
|
* @param parameter 메소드 파라미터
|
||||||
|
* @return @ReqMap 어노테이션이 존재하면 true 반환
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean supportsParameter(MethodParameter parameter) {
|
||||||
|
return parameter.hasParameterAnnotation(ReqMap.class); // @ReqMap 어노테이션이 있는 파라미터만 처리
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP 요청의 파라미터 또는 본문을 MapDto 객체로 변환하여 반환하는 메소드
|
||||||
|
*
|
||||||
|
* @param parameter 처리할 메소드 파라미터
|
||||||
|
* @param mavContainer ModelAndView 컨테이너 (여기서는 사용되지 않음)
|
||||||
|
* @param webRequest 웹 요청 객체
|
||||||
|
* @param binderFactory 바인딩 팩토리 (여기서는 사용되지 않음)
|
||||||
|
* @return 변환된 MapDto 객체
|
||||||
|
* @throws Exception 요청 처리 중 발생할 수 있는 예외
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
|
||||||
|
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
|
||||||
|
|
||||||
|
// HTTP ServletRequest를 얻어옵니다.
|
||||||
|
HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
|
||||||
|
|
||||||
|
MapDto parameterMap = null;
|
||||||
|
try {
|
||||||
|
// 요청이 JSON인지 확인
|
||||||
|
boolean isJson = WebUtil.isJson(request);
|
||||||
|
|
||||||
|
// JSON 형식일 경우, 요청 본문을 MapDto로 변환
|
||||||
|
if (isJson) {
|
||||||
|
InputStream is = request.getInputStream();
|
||||||
|
byte[] rawdata = org.apache.commons.io.IOUtils.toByteArray(is); // 요청 본문을 바이트 배열로 읽음
|
||||||
|
String body = new String(rawdata, StandardCharsets.UTF_8); // 바이트 배열을 문자열로 변환
|
||||||
|
|
||||||
|
// JSON을 MapDto 객체로 변환
|
||||||
|
parameterMap = JacksonUtil.fromJson(body, MapDto.class);
|
||||||
|
|
||||||
|
return parameterMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSON이 아닌 경우, 쿼리 파라미터를 MapDto에 넣음
|
||||||
|
parameterMap = new MapDto();
|
||||||
|
|
||||||
|
String name;
|
||||||
|
String[] values;
|
||||||
|
|
||||||
|
// 요청의 파라미터 이름들을 순차적으로 가져와서 처리
|
||||||
|
Enumeration<String> enumeration = request.getParameterNames();
|
||||||
|
while (enumeration.hasMoreElements()) {
|
||||||
|
name = enumeration.nextElement(); // 파라미터 이름
|
||||||
|
if (WebEnum.JSON_PART.value().equals(name)) { // 특정 파라미터는 무시
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
values = request.getParameterValues(name); // 파라미터 값들
|
||||||
|
if (values != null) {
|
||||||
|
if (values.length > 1) {
|
||||||
|
// 파라미터 값이 여러 개인 경우 List로 변환하여 MapDto에 추가
|
||||||
|
List<String> valuesList = new ArrayList<>(Arrays.asList(values));
|
||||||
|
parameterMap.put(name, valuesList);
|
||||||
|
} else {
|
||||||
|
// 파라미터 값이 하나일 경우 MapDto에 추가
|
||||||
|
// XSS 필터링을 적용할 수도 있음 (현재 주석 처리)
|
||||||
|
parameterMap.put(name, values[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parameterMap; // MapDto 객체 반환
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Request parameter parsing failed", e); // 예외 발생 시 로그 출력
|
||||||
|
return new MapDto(); // 예외 발생 시 빈 MapDto 반환
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,36 @@
|
|||||||
|
package io.company.localhost.common.response;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
public class ApiResponse<T> {
|
||||||
|
private int code;
|
||||||
|
private HttpStatus status;
|
||||||
|
private String message;
|
||||||
|
private T data;
|
||||||
|
|
||||||
|
public ApiResponse(HttpStatus status, String message, T data) {
|
||||||
|
this.code = status.value();
|
||||||
|
this.status = status;
|
||||||
|
this.message = message;
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> ApiResponse<T> of(HttpStatus status, String message, T data) {
|
||||||
|
return new ApiResponse<>(status, message, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> ApiResponse<T> of(HttpStatus status, T data) {
|
||||||
|
return ApiResponse.of(status, status.name(), data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> ApiResponse<T> ok(T data) {
|
||||||
|
return ApiResponse.of(HttpStatus.OK, HttpStatus.OK.name(), data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> ApiResponse<T> error(HttpStatus status, String message) {
|
||||||
|
return new ApiResponse<>(status, message, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,51 @@
|
|||||||
|
package io.company.localhost.common.security.details;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
|
||||||
|
public record MemberPrincipalDetails(MemberVo member) implements UserDetails {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||||
|
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||||
|
authorities.add(new SimpleGrantedAuthority(member.getRole()));
|
||||||
|
return authorities;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getPassword() {
|
||||||
|
return member.getPassword();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getUsername() {
|
||||||
|
return member.getLoginId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAccountNonExpired() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isAccountNonLocked() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isCredentialsNonExpired() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isEnabled() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,84 @@
|
|||||||
|
package io.company.localhost.common.security.dsl;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
|
||||||
|
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
|
||||||
|
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||||
|
import org.springframework.security.web.authentication.RememberMeServices;
|
||||||
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
|
||||||
|
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||||
|
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||||
|
import io.company.localhost.common.security.filter.RestAuthenticationFilter;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class RestApiDsl <H extends HttpSecurityBuilder<H>> extends
|
||||||
|
AbstractAuthenticationFilterConfigurer<H, RestApiDsl<H>, RestAuthenticationFilter> {
|
||||||
|
|
||||||
|
private AuthenticationSuccessHandler successHandler;
|
||||||
|
private AuthenticationFailureHandler failureHandler;
|
||||||
|
|
||||||
|
public RestApiDsl(){
|
||||||
|
super(new RestAuthenticationFilter(),null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void init(H http) throws Exception {
|
||||||
|
super.init(http);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void configure(H http) {
|
||||||
|
|
||||||
|
// AuthenticationManager를 가져와서 RestAuthenticationFilter에 설정
|
||||||
|
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
|
||||||
|
getAuthenticationFilter().setAuthenticationManager(authenticationManager);
|
||||||
|
// 인증 성공/실패 핸들러 설정
|
||||||
|
getAuthenticationFilter().setAuthenticationSuccessHandler(successHandler);
|
||||||
|
getAuthenticationFilter().setAuthenticationFailureHandler(failureHandler);
|
||||||
|
|
||||||
|
RememberMeServices rememberMeServices = http.getSharedObject(RememberMeServices.class);
|
||||||
|
if (rememberMeServices != null) {
|
||||||
|
getAuthenticationFilter().setRememberMeServices(rememberMeServices);
|
||||||
|
}
|
||||||
|
|
||||||
|
// SecurityContextRepository 설정
|
||||||
|
getAuthenticationFilter().setSecurityContextRepository(getAuthenticationFilter().getSecurityContextRepository((HttpSecurity) http));
|
||||||
|
|
||||||
|
SessionAuthenticationStrategy sessionAuthenticationStrategy = http.getSharedObject(SessionAuthenticationStrategy.class);
|
||||||
|
if (sessionAuthenticationStrategy != null) {
|
||||||
|
getAuthenticationFilter().setSessionAuthenticationStrategy(sessionAuthenticationStrategy);
|
||||||
|
}
|
||||||
|
|
||||||
|
http.setSharedObject(RestAuthenticationFilter.class,getAuthenticationFilter());
|
||||||
|
// UsernamePasswordAuthenticationFilter 이전에 RestAuthenticationFilter를 배치
|
||||||
|
http.addFilterBefore(getAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 로그인 성공 핸들러를 설정
|
||||||
|
public RestApiDsl<H> loginSuccessHandler(AuthenticationSuccessHandler successHandler) {
|
||||||
|
this.successHandler = successHandler;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 로그인 실패 핸들러를 설정
|
||||||
|
public RestApiDsl<H> loginFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
|
||||||
|
this.failureHandler = authenticationFailureHandler;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 로그인 처리 URL을 설정
|
||||||
|
public RestApiDsl<H> loginProcessingUrl(String loginPage) {
|
||||||
|
return super.loginProcessingUrl(loginPage);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 로그인 처리 URL을 위한 RequestMatcher를 생성
|
||||||
|
@Override
|
||||||
|
protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
|
||||||
|
return new AntPathRequestMatcher(loginProcessingUrl, HttpMethod.POST.name());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,89 @@
|
|||||||
|
package io.company.localhost.common.security.filter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
|
||||||
|
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||||
|
import org.springframework.security.web.authentication.RememberMeServices;
|
||||||
|
import org.springframework.security.web.context.DelegatingSecurityContextRepository;
|
||||||
|
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||||
|
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
|
||||||
|
import org.springframework.security.web.context.SecurityContextRepository;
|
||||||
|
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import io.company.localhost.common.security.token.RestAuthenticationToken;
|
||||||
|
import io.company.localhost.utils.WebUtil;
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.Setter;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
|
@Setter
|
||||||
|
private AuthenticationSuccessHandler successHandler;
|
||||||
|
|
||||||
|
public RestAuthenticationFilter() {
|
||||||
|
super(new AntPathRequestMatcher("/api/user/login", HttpMethod.POST.name()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public SecurityContextRepository getSecurityContextRepository(HttpSecurity http) {
|
||||||
|
SecurityContextRepository securityContextRepository = http.getSharedObject(SecurityContextRepository.class);
|
||||||
|
if (securityContextRepository == null) {
|
||||||
|
securityContextRepository = new DelegatingSecurityContextRepository(
|
||||||
|
new HttpSessionSecurityContextRepository(),new RequestAttributeSecurityContextRepository());
|
||||||
|
}
|
||||||
|
return securityContextRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException {
|
||||||
|
|
||||||
|
// 로그인 시 POST 요청과 Ajax 요청만 처리하도록 제한
|
||||||
|
if(!HttpMethod.POST.matches(request.getMethod()) || !WebUtil.isAjax(request)){
|
||||||
|
throw new IllegalArgumentException("지원하지 않는 메서드");
|
||||||
|
}
|
||||||
|
MemberVo member = objectMapper.readValue(request.getReader(), MemberVo.class);
|
||||||
|
|
||||||
|
// 로그인 ID 또는 비밀번호가 비어있는 경우
|
||||||
|
if(!StringUtils.hasText(member.getLoginId()) || !StringUtils.hasText(member.getPassword())){
|
||||||
|
throw new AuthenticationServiceException("id 혹은 비밀번호 가 비어있음");
|
||||||
|
}
|
||||||
|
boolean rememberMe = member.getRemember();
|
||||||
|
|
||||||
|
request.setAttribute("remember" , rememberMe);
|
||||||
|
|
||||||
|
//로그인 ID와 비밀번호를 토큰으로 생성
|
||||||
|
RestAuthenticationToken authToken = new RestAuthenticationToken(member.getLoginId(), member.getPassword());
|
||||||
|
authToken.setDetails(rememberMe);
|
||||||
|
|
||||||
|
|
||||||
|
return this.getAuthenticationManager().authenticate(authToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws
|
||||||
|
ServletException,
|
||||||
|
IOException {
|
||||||
|
|
||||||
|
if(successHandler != null){
|
||||||
|
successHandler.onAuthenticationSuccess(request,response,authentication);
|
||||||
|
}else{
|
||||||
|
super.successfulAuthentication(request, response, chain, authentication);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,33 @@
|
|||||||
|
package io.company.localhost.common.security.handler;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
@Component("failHandler")
|
||||||
|
public class MemberAuthFailureHandler implements AuthenticationFailureHandler {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
|
||||||
|
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
|
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
|
|
||||||
|
if (exception instanceof BadCredentialsException) {
|
||||||
|
mapper.writeValue(response.getWriter(),"아이디 혹은 비밀번호 문제");
|
||||||
|
}
|
||||||
|
|
||||||
|
mapper.writeValue(response.getWriter(), "인증 실패");
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
package io.company.localhost.common.security.handler;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.web.WebAttributes;
|
||||||
|
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||||
|
import org.springframework.security.web.authentication.RememberMeServices;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import jakarta.servlet.http.HttpSession;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component("successHandler")
|
||||||
|
public class MemberAuthSuccessHandler implements AuthenticationSuccessHandler{
|
||||||
|
|
||||||
|
private final RememberMeServices rememberMeServices;
|
||||||
|
|
||||||
|
public MemberAuthSuccessHandler(RememberMeServices rememberMeServices) {
|
||||||
|
this.rememberMeServices = rememberMeServices;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
Boolean rememberMe = (Boolean) request.getAttribute("remember");
|
||||||
|
if (rememberMe != null && rememberMe) {
|
||||||
|
rememberMeServices.loginSuccess(request, response, authentication);
|
||||||
|
}
|
||||||
|
|
||||||
|
MemberVo member = (MemberVo) authentication.getPrincipal();
|
||||||
|
response.setStatus(HttpStatus.OK.value());
|
||||||
|
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
|
|
||||||
|
mapper.writeValue(response.getWriter(), member);
|
||||||
|
|
||||||
|
clearAuthenticationAttributes(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected final void clearAuthenticationAttributes(HttpServletRequest request) {
|
||||||
|
HttpSession session = request.getSession(false);
|
||||||
|
if (session == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
package io.company.localhost.common.security.handler;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.access.AccessDeniedException;
|
||||||
|
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import io.company.localhost.common.exception.code.UserErrorCode;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
public class RestAccessDeniedHandler implements AccessDeniedHandler {
|
||||||
|
|
||||||
|
private final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handle(HttpServletRequest request, HttpServletResponse response,
|
||||||
|
AccessDeniedException accessDeniedException) throws IOException, ServletException {
|
||||||
|
|
||||||
|
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||||
|
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
|
|
||||||
|
response.getWriter().write(mapper.writeValueAsString(UserErrorCode.INACTIVE_USER.getApiResponse()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,32 @@
|
|||||||
|
package io.company.localhost.common.security.handler;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import io.company.localhost.common.exception.code.UserErrorCode;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
public class RestAuthenticationEntryPointHandler implements AuthenticationEntryPoint {
|
||||||
|
|
||||||
|
private final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void commence(HttpServletRequest request, HttpServletResponse response,
|
||||||
|
AuthenticationException authException) throws IOException, ServletException {
|
||||||
|
|
||||||
|
// HTTP 상태 코드를 401 (Unauthorized)로 설정
|
||||||
|
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
|
// 응답의 콘텐츠 타입을 JSON으로 설정
|
||||||
|
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
|
|
||||||
|
// 사용자 정의 에러 코드와 메시지를 JSON 형식으로 응답
|
||||||
|
response.getWriter().write(mapper.writeValueAsString(UserErrorCode.NOT_AUTH_USER.getApiResponse()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,86 @@
|
|||||||
|
package io.company.localhost.common.security.manager;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.checkerframework.common.reflection.qual.Invoke;
|
||||||
|
import org.springframework.security.authorization.AuthorityAuthorizationManager;
|
||||||
|
import org.springframework.security.authorization.AuthorizationDecision;
|
||||||
|
import org.springframework.security.authorization.AuthorizationManager;
|
||||||
|
import org.springframework.security.authorization.AuthorizationResult;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.web.access.expression.WebExpressionAuthorizationManager;
|
||||||
|
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
|
||||||
|
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||||
|
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||||
|
import org.springframework.security.web.util.matcher.RequestMatcherEntry;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
|
||||||
|
|
||||||
|
import io.company.localhost.common.security.mapper.MapBasedUrlRoleMapper;
|
||||||
|
import io.company.localhost.common.security.service.DynamicAuthorizationService;
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CustomDynamicAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
|
||||||
|
List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings;
|
||||||
|
private static final AuthorizationDecision DENY = new AuthorizationDecision(false);
|
||||||
|
private final HandlerMappingIntrospector handlerMappingIntrospector;
|
||||||
|
|
||||||
|
// 클래스 초기화 후 동적으로 URL-권한 매핑을 설정
|
||||||
|
@PostConstruct
|
||||||
|
public void mapping() {
|
||||||
|
DynamicAuthorizationService dynamicAuthorizationService = new DynamicAuthorizationService(new MapBasedUrlRoleMapper());
|
||||||
|
mappings = dynamicAuthorizationService.getUrlRoleMappings()
|
||||||
|
.entrySet().stream()
|
||||||
|
.map(entry -> new RequestMatcherEntry<>(
|
||||||
|
new MvcRequestMatcher(handlerMappingIntrospector, entry.getKey()),
|
||||||
|
customAuthorizationManager(entry.getValue())))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 요청에 대해 권한을 확인하는 메소드
|
||||||
|
@Override
|
||||||
|
public AuthorizationResult authorize(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
|
||||||
|
for (RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings) {
|
||||||
|
|
||||||
|
RequestMatcher matcher = mapping.getRequestMatcher();
|
||||||
|
RequestMatcher.MatchResult matchResult = matcher.matcher(object.getRequest());
|
||||||
|
|
||||||
|
if (matchResult.isMatch()) {
|
||||||
|
AuthorizationManager<RequestAuthorizationContext> manager = mapping.getEntry();
|
||||||
|
return manager.authorize(authentication,
|
||||||
|
new RequestAuthorizationContext(object.getRequest(), matchResult.getVariables()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return DENY;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 역할에 맞는 AuthorizationManager 반환
|
||||||
|
private AuthorizationManager<RequestAuthorizationContext> customAuthorizationManager(String role) {
|
||||||
|
if (role.startsWith("ROLE")) {
|
||||||
|
return AuthorityAuthorizationManager.hasAuthority(role);
|
||||||
|
}else{
|
||||||
|
return new WebExpressionAuthorizationManager(role);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void verify(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
|
||||||
|
AuthorizationManager.super.verify(authentication, object);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//deprecated 됬는디 값 안 넣으면 세팅이 안 됨
|
||||||
|
@Deprecated
|
||||||
|
@Invoke
|
||||||
|
@Override
|
||||||
|
public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
|
||||||
|
return (AuthorizationDecision)authorize(authentication,object);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
package io.company.localhost.common.security.mapper;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MapBasedUrlRoleMapper implements UrlRoleMapper{
|
||||||
|
|
||||||
|
private final LinkedHashMap<String, String> urlRoleMappings = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
final String PERMIT_ALL = "permitAll";
|
||||||
|
final String ROLE_MEMBER = "ROLE_MEMBER";
|
||||||
|
final String ROLE_MANAGER = "ROLE_MANAGER";
|
||||||
|
final String ROLE_ADMIN = "ROLE_ADMIN";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, String> getUrlRoleMappings() {
|
||||||
|
urlRoleMappings.put("/api/login", PERMIT_ALL);
|
||||||
|
urlRoleMappings.put("/api/user/**", ROLE_MEMBER);
|
||||||
|
urlRoleMappings.put("/api/user/logout", PERMIT_ALL);
|
||||||
|
urlRoleMappings.put("/api/test/**", ROLE_MEMBER);
|
||||||
|
|
||||||
|
|
||||||
|
return new HashMap<>(urlRoleMappings);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
package io.company.localhost.common.security.mapper;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
//DB 정보로 권한 요청 할거면 여기서 설정하자
|
||||||
|
public class PersistentUrlRoleMapper implements UrlRoleMapper{
|
||||||
|
@Override
|
||||||
|
public Map<String, String> getUrlRoleMappings() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
package io.company.localhost.common.security.mapper;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public interface UrlRoleMapper {
|
||||||
|
Map<String, String> getUrlRoleMappings();
|
||||||
|
}
|
||||||
@ -0,0 +1,48 @@
|
|||||||
|
package io.company.localhost.common.security.provider;
|
||||||
|
|
||||||
|
import org.springframework.security.authentication.AuthenticationProvider;
|
||||||
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import io.company.localhost.common.security.service.MemberPrincipalDetailService;
|
||||||
|
import io.company.localhost.common.security.details.MemberPrincipalDetails;
|
||||||
|
import io.company.localhost.common.security.token.RestAuthenticationToken;
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MemberAuthenticatorProvider implements AuthenticationProvider {
|
||||||
|
|
||||||
|
private final MemberPrincipalDetailService memberPrincipalDetailService;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
|
String username = authentication.getName();
|
||||||
|
String password = (String) authentication.getCredentials();
|
||||||
|
|
||||||
|
MemberPrincipalDetails memberPrincipalDetails = (MemberPrincipalDetails) memberPrincipalDetailService.loadUserByUsername(username);
|
||||||
|
|
||||||
|
String dbPassword = memberPrincipalDetails.getPassword();
|
||||||
|
|
||||||
|
if(!passwordEncoder.matches(password, dbPassword)) {
|
||||||
|
throw new BadCredentialsException("[사용자] 아이디 또는 비밀번호가 일치하지 않습니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
MemberVo member = memberPrincipalDetails.member();
|
||||||
|
if (member == null || "N".equals(member.getIsUsed())) {
|
||||||
|
throw new BadCredentialsException("[사용자] 사용할 수 없는 계정입니다.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RestAuthenticationToken(memberPrincipalDetails.getAuthorities(), member , null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supports(Class<?> authentication) {
|
||||||
|
return authentication.equals(RestAuthenticationToken.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,119 @@
|
|||||||
|
package io.company.localhost.common.security.service;
|
||||||
|
|
||||||
|
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.*;
|
||||||
|
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
import org.springframework.security.authentication.RememberMeAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.web.authentication.RememberMeServices;
|
||||||
|
|
||||||
|
import io.company.localhost.common.security.details.MemberPrincipalDetails;
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
import jakarta.servlet.http.Cookie;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class CustomRememberMeServices implements RememberMeServices {
|
||||||
|
|
||||||
|
private static final String REMEMBER_ME_KEY = "remember";
|
||||||
|
private final UserDetailsService userDetailsService;
|
||||||
|
private final String key;
|
||||||
|
|
||||||
|
public CustomRememberMeServices(String key, UserDetailsService userDetailsService) {
|
||||||
|
this.key = key;
|
||||||
|
this.userDetailsService = userDetailsService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
|
||||||
|
|
||||||
|
Cookie rememberMeCookie = getRememberMeCookie(request);
|
||||||
|
if (rememberMeCookie == null) {
|
||||||
|
log.debug("No remember-me cookie found");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String username = decodeCookie(rememberMeCookie.getValue());
|
||||||
|
if (username == null || username.isEmpty()) {
|
||||||
|
log.error("Invalid remember-me cookie");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
|
||||||
|
|
||||||
|
if (userDetails != null) {
|
||||||
|
MemberPrincipalDetails memberDetails = (MemberPrincipalDetails) userDetails;
|
||||||
|
MemberVo memberVo = memberDetails.member();
|
||||||
|
RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(key, memberVo, userDetails.getAuthorities());
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
return auth;
|
||||||
|
}else {
|
||||||
|
log.error("UserDetailsService returned null for username: {}", username);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
|
||||||
|
|
||||||
|
Boolean rememberMe = (Boolean) request.getAttribute(REMEMBER_ME_KEY);
|
||||||
|
if (rememberMe != null && rememberMe) {
|
||||||
|
// Remember-Me 토큰 생성 및 설정
|
||||||
|
Object principal = successfulAuthentication.getPrincipal();
|
||||||
|
MemberVo member = (MemberVo)principal;
|
||||||
|
String username = member.getLoginId();
|
||||||
|
String rememberMeToken = generateRememberMeToken(username);
|
||||||
|
int tokenValiditySeconds = getTokenValiditySeconds();
|
||||||
|
|
||||||
|
Cookie rememberMeCookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, rememberMeToken);
|
||||||
|
rememberMeCookie.setPath("/");
|
||||||
|
rememberMeCookie.setMaxAge(tokenValiditySeconds);
|
||||||
|
rememberMeCookie.setHttpOnly(true);
|
||||||
|
rememberMeCookie.setSecure(request.isSecure());
|
||||||
|
response.addCookie(rememberMeCookie);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void loginFail(HttpServletRequest request, HttpServletResponse response) {
|
||||||
|
// 로그인 실패 처리
|
||||||
|
}
|
||||||
|
|
||||||
|
private Cookie getRememberMeCookie(HttpServletRequest request) {
|
||||||
|
Cookie[] cookies = request.getCookies();
|
||||||
|
if (cookies == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
for(Cookie cookie : cookies) {
|
||||||
|
if(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY.equals(cookie.getName())) {
|
||||||
|
return cookie;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String decodeCookie(String cookieValue) {
|
||||||
|
try { // Base64 디코딩
|
||||||
|
return new String(Base64.getDecoder().decode(cookieValue));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.error("Failed to decode remember-me cookie", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String generateRememberMeToken(String username) {
|
||||||
|
return Base64.getEncoder().encodeToString(username.getBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getTokenValiditySeconds() {
|
||||||
|
return 60 * 60 * 24 * 365;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
package io.company.localhost.common.security.service;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import io.company.localhost.common.security.mapper.UrlRoleMapper;
|
||||||
|
|
||||||
|
public class DynamicAuthorizationService {
|
||||||
|
private final UrlRoleMapper delegate;
|
||||||
|
public DynamicAuthorizationService(UrlRoleMapper delegate) {
|
||||||
|
this.delegate = delegate;
|
||||||
|
}
|
||||||
|
public Map<String, String> getUrlRoleMappings() {
|
||||||
|
return delegate.getUrlRoleMappings();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,36 @@
|
|||||||
|
package io.company.localhost.common.security.service;
|
||||||
|
|
||||||
|
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 io.company.localhost.common.security.details.MemberPrincipalDetails;
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
import io.company.localhost.mapper.MemberMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MemberPrincipalDetailService implements UserDetailsService {
|
||||||
|
|
||||||
|
private final MemberMapper memberMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
|
||||||
|
MemberVo member = memberMapper.findByLoginId(id);
|
||||||
|
|
||||||
|
// 없을경우 에러 발생
|
||||||
|
if(member == null)
|
||||||
|
throw new UsernameNotFoundException(id + "을 찾을 수 없습니다.");
|
||||||
|
|
||||||
|
if(!"Y".equals(member.getIsUsed()))
|
||||||
|
throw new UsernameNotFoundException("사용할 수 없는 계정입니다.");
|
||||||
|
|
||||||
|
if(!"N".equals(member.getIsDel()))
|
||||||
|
throw new UsernameNotFoundException("삭제된 계정입니다.");
|
||||||
|
|
||||||
|
// MemberPrincipalDetails 에 Member 객체를 넘겨줌
|
||||||
|
return new MemberPrincipalDetails(member);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,48 @@
|
|||||||
|
package io.company.localhost.common.security.session;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.security.core.session.SessionInformation;
|
||||||
|
import org.springframework.security.core.session.SessionRegistry;
|
||||||
|
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
|
||||||
|
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
//세션 만료에 대한 로직
|
||||||
|
@Slf4j
|
||||||
|
public class AuthenticationSessionControlStrategy extends ConcurrentSessionControlAuthenticationStrategy {
|
||||||
|
|
||||||
|
public AuthenticationSessionControlStrategy(@Qualifier("sessionRegistry") SessionRegistry sessionRegistry) {
|
||||||
|
super(sessionRegistry);
|
||||||
|
log.debug("AuthenticationSessionControlStrategy constructor run!");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions,
|
||||||
|
SessionRegistry registry) throws SessionAuthenticationException {
|
||||||
|
|
||||||
|
if (CollectionUtils.isEmpty(sessions)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 가져온 세션(기존에 존재하는 세션들, 현재 세션 포함 안함)을 정렬 후
|
||||||
|
// 설정한 max-session 수에서 1개 더 제외 하고 모두 제거
|
||||||
|
// max-session = 기존 세션 + 현재 세션
|
||||||
|
// 기존 세션에서 하나 더 제거 해줘야 함
|
||||||
|
// sessions.sort(Comparator.comparing(SessionInformation::getLastRequest)); // ASC
|
||||||
|
sessions.sort(Collections.reverseOrder(Comparator.comparing(SessionInformation::getLastRequest))); // DESC
|
||||||
|
int sessionCnt = sessions.size();
|
||||||
|
int maximumSessionsExceededBy = allowableSessions - 1;
|
||||||
|
|
||||||
|
for (int i = maximumSessionsExceededBy; i < sessionCnt; i++) {
|
||||||
|
SessionInformation sessionInformation = sessions.get(i);
|
||||||
|
sessionInformation.expireNow();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,161 @@
|
|||||||
|
package io.company.localhost.common.security.session;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
|
||||||
|
import org.springframework.context.ApplicationListener;
|
||||||
|
import org.springframework.security.core.session.SessionDestroyedEvent;
|
||||||
|
import org.springframework.security.core.session.SessionInformation;
|
||||||
|
import org.springframework.security.core.session.SessionRegistry;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
import io.company.localhost.common.security.details.MemberPrincipalDetails;
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
// 세션 관리용
|
||||||
|
@Slf4j
|
||||||
|
public class CustomSessionRegistryImpl implements SessionRegistry, ApplicationListener<SessionDestroyedEvent> {
|
||||||
|
|
||||||
|
private final Map<String, List<String>> principals;
|
||||||
|
|
||||||
|
private final Map<String, SessionInformation> sessionIds;
|
||||||
|
|
||||||
|
// ~ Methods
|
||||||
|
// ========================================================================================================
|
||||||
|
|
||||||
|
public CustomSessionRegistryImpl() {
|
||||||
|
principals = new TreeMap<>();
|
||||||
|
sessionIds = new TreeMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 로그인 ID를 반환하는 메소드
|
||||||
|
private String getLoginId(Object principal) {
|
||||||
|
|
||||||
|
if (principal instanceof MemberVo) {
|
||||||
|
MemberVo loginUser = (MemberVo) principal;
|
||||||
|
return loginUser.getLoginId();
|
||||||
|
} else if (principal instanceof MemberPrincipalDetails) {
|
||||||
|
MemberPrincipalDetails memberDetails = (MemberPrincipalDetails) principal;
|
||||||
|
MemberVo memberVo = memberDetails.member(); // MemberPrincipalDetails에서 MemberVo 추출
|
||||||
|
return memberVo.getLoginId();
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Unsupported principal type: " + principal.getClass().getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 세션이 파괴될 때 호출되는 이벤트 리스너
|
||||||
|
@Override
|
||||||
|
public void onApplicationEvent(SessionDestroyedEvent event) {
|
||||||
|
String sessionId = event.getId();
|
||||||
|
log.debug("onApplicationEvent sessionId {}", sessionId);
|
||||||
|
removeSessionInformation(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 모든 principal(로그인 ID)을 반환하는 메소드
|
||||||
|
@Override
|
||||||
|
public List<Object> getAllPrincipals() {
|
||||||
|
return new ArrayList<>(principals.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 특정 principal의 모든 세션 정보를 반환하는 메소드
|
||||||
|
@Override
|
||||||
|
public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {
|
||||||
|
String loginId = getLoginId(principal);
|
||||||
|
|
||||||
|
final List<String> sessionsUsedByPrincipal = principals.get(loginId);
|
||||||
|
if (sessionsUsedByPrincipal == null) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<SessionInformation> list = new ArrayList<>(sessionsUsedByPrincipal.size());
|
||||||
|
|
||||||
|
for (String sessionId : sessionsUsedByPrincipal) {
|
||||||
|
SessionInformation sessionInformation = getSessionInformation(sessionId);
|
||||||
|
|
||||||
|
if (sessionInformation == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (includeExpiredSessions || !sessionInformation.isExpired()) {
|
||||||
|
list.add(sessionInformation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 세션 ID에 대한 세션 정보를 반환하는 메소드
|
||||||
|
@Override
|
||||||
|
public SessionInformation getSessionInformation(String sessionId) {
|
||||||
|
Assert.hasText(sessionId, "SessionId required as per interface contract");
|
||||||
|
|
||||||
|
return sessionIds.get(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 세션의 마지막 요청 시간을 갱신하는 메소드
|
||||||
|
@Override
|
||||||
|
public void refreshLastRequest(String sessionId) {
|
||||||
|
Assert.hasText(sessionId, "SessionId required as per interface contract");
|
||||||
|
|
||||||
|
SessionInformation info = getSessionInformation(sessionId);
|
||||||
|
|
||||||
|
if (info != null) {
|
||||||
|
info.refreshLastRequest();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 새로운 세션을 등록하는 메소드
|
||||||
|
@Override
|
||||||
|
public void registerNewSession(String sessionId, Object principal) {
|
||||||
|
Assert.hasText(sessionId, "SessionId required as per interface contract");
|
||||||
|
Assert.notNull(principal, "Principal required as per interface contract");
|
||||||
|
|
||||||
|
if (getSessionInformation(sessionId) != null) {
|
||||||
|
removeSessionInformation(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
String loginId = getLoginId(principal);
|
||||||
|
|
||||||
|
sessionIds.put(sessionId, new SessionInformation(loginId, sessionId, new Date()));
|
||||||
|
|
||||||
|
List<String> sessionListById = principals.get(loginId);
|
||||||
|
if (sessionListById == null) {
|
||||||
|
sessionListById = new ArrayList<>();
|
||||||
|
}
|
||||||
|
sessionListById.add(sessionId);
|
||||||
|
|
||||||
|
principals.put(loginId, sessionListById);
|
||||||
|
|
||||||
|
// log.debug("new add {}", principals);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 세션 정보를 제거하는 메소드
|
||||||
|
@Override
|
||||||
|
public void removeSessionInformation(String sessionId) {
|
||||||
|
Assert.hasText(sessionId, "SessionId required as per interface contract");
|
||||||
|
|
||||||
|
SessionInformation info = getSessionInformation(sessionId);
|
||||||
|
|
||||||
|
if (info == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sessionIds.remove(sessionId);
|
||||||
|
|
||||||
|
List<String> sessionListById = principals.get(info.getPrincipal());
|
||||||
|
sessionListById.remove(sessionId);
|
||||||
|
|
||||||
|
if (sessionListById.isEmpty()) {
|
||||||
|
sessionListById = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// log.debug("remove {}", principals);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,36 @@
|
|||||||
|
package io.company.localhost.common.security.token;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
|
||||||
|
public class RestAuthenticationToken extends AbstractAuthenticationToken {
|
||||||
|
|
||||||
|
private final Object principal;
|
||||||
|
private final Object credentials;
|
||||||
|
|
||||||
|
public RestAuthenticationToken(Collection<? extends GrantedAuthority> authorities, Object principal, Object credentials) {
|
||||||
|
super(authorities);
|
||||||
|
this.principal = principal;
|
||||||
|
this.credentials = credentials;
|
||||||
|
setAuthenticated(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RestAuthenticationToken(Object principal, Object credentials) {
|
||||||
|
super(null);
|
||||||
|
this.principal = principal;
|
||||||
|
this.credentials = credentials;
|
||||||
|
setAuthenticated(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getCredentials() {
|
||||||
|
return this.credentials;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getPrincipal() {
|
||||||
|
return this.principal;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,21 @@
|
|||||||
|
package io.company.localhost.common.webEnum;
|
||||||
|
|
||||||
|
//WebUtil 타입 Header
|
||||||
|
public enum WebEnum {
|
||||||
|
|
||||||
|
JSON_PART("---jsonboundary"), MSIE_USER_AGENT_IDENTIFIER("MSIE"), USER_AGENT_HEADER("user-agent"),
|
||||||
|
REQUESTED_WITH("X-Requested-With"), AJAX_IDENTIFIER("XMLHttpRequest")
|
||||||
|
// , CONTENT_TYPE ("Content-Type")
|
||||||
|
;
|
||||||
|
|
||||||
|
private String value;
|
||||||
|
|
||||||
|
private WebEnum(String value) {
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String value() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,132 @@
|
|||||||
|
package io.company.localhost.common.wrapper;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import org.springframework.util.StreamUtils;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
|
||||||
|
import io.company.localhost.utils.JacksonUtil;
|
||||||
|
import io.netty.handler.codec.ValueConverter;
|
||||||
|
import jakarta.servlet.ReadListener;
|
||||||
|
import jakarta.servlet.ServletInputStream;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletRequestWrapper;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
// body 읽어서 cash로 만듬
|
||||||
|
// 필요하면 filter로 사용
|
||||||
|
@Slf4j
|
||||||
|
public class CachedBodyRequestWrapper extends HttpServletRequestWrapper {
|
||||||
|
|
||||||
|
private final Charset encoding;
|
||||||
|
|
||||||
|
private final byte[] cachedBody;
|
||||||
|
|
||||||
|
private ValueConverter targetConvert;
|
||||||
|
|
||||||
|
public CachedBodyRequestWrapper(HttpServletRequest request) throws IOException {
|
||||||
|
super(request);
|
||||||
|
|
||||||
|
String characterEncoding = request.getCharacterEncoding();
|
||||||
|
if (StringUtils.hasText(characterEncoding) == false) {
|
||||||
|
characterEncoding = StandardCharsets.UTF_8.name();
|
||||||
|
}
|
||||||
|
|
||||||
|
// XSS 방지를 이곳에서 하지 않을 경우 아래주석 해제 후 아래 //XSS 방지 이후 코드 삭제
|
||||||
|
// InputStream requestInputStream = request.getInputStream();
|
||||||
|
// this.cachedBody = StreamUtils.copyToByteArray(requestInputStream);
|
||||||
|
this.encoding = Charset.forName(characterEncoding);
|
||||||
|
|
||||||
|
// XSS 방지
|
||||||
|
String requestBody = null;
|
||||||
|
try {
|
||||||
|
requestBody = StreamUtils.copyToString(request.getInputStream(), Charset.defaultCharset());
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("StreamUtil.toString Exception", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (requestBody == null) {
|
||||||
|
InputStream requestInputStream = request.getInputStream();
|
||||||
|
this.cachedBody = StreamUtils.copyToByteArray(requestInputStream);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object bodyObject = null;
|
||||||
|
if (requestBody.startsWith("[")) { // List
|
||||||
|
bodyObject = JacksonUtil.fromJson(requestBody, new TypeReference<List<Map<String, Object>>>() {
|
||||||
|
});
|
||||||
|
} else { // Map
|
||||||
|
bodyObject = JacksonUtil.fromJson(requestBody, new TypeReference<Map<String, Object>>() {
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
String newRequestBody = JacksonUtil.toJson(bodyObject);
|
||||||
|
if (Objects.isNull(newRequestBody)) {
|
||||||
|
newRequestBody = new String("");
|
||||||
|
}
|
||||||
|
this.cachedBody = newRequestBody.getBytes(StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** json body 관련 메소드 START */
|
||||||
|
@Override
|
||||||
|
public ServletInputStream getInputStream() throws IOException {
|
||||||
|
return new CachedBodyServletInputStream(this.cachedBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BufferedReader getReader() throws IOException {
|
||||||
|
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
|
||||||
|
return new BufferedReader(new InputStreamReader(byteArrayInputStream, encoding));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** json body 관련 메소드 END */
|
||||||
|
|
||||||
|
private class CachedBodyServletInputStream extends ServletInputStream {
|
||||||
|
|
||||||
|
private InputStream cachedBodyInputStream;
|
||||||
|
|
||||||
|
public CachedBodyServletInputStream(byte[] cachedBody) {
|
||||||
|
this.cachedBodyInputStream = new ByteArrayInputStream(cachedBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isFinished() {
|
||||||
|
try {
|
||||||
|
return this.cachedBodyInputStream.available() == 0;
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("", e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isReady() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setReadListener(ReadListener listener) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int read() throws IOException {
|
||||||
|
return this.cachedBodyInputStream.read();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,58 @@
|
|||||||
|
package io.company.localhost.common.wrapper;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.web.util.HtmlUtils;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletRequestWrapper;
|
||||||
|
|
||||||
|
//HTML 태그를 escape 처리하는 기능
|
||||||
|
//필요하면 filter 로 만들어서 쓰자
|
||||||
|
public class HTMLTagRequestWrapper extends HttpServletRequestWrapper {
|
||||||
|
|
||||||
|
public HTMLTagRequestWrapper(HttpServletRequest request) {
|
||||||
|
super(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** form parameter 관련 메소드 START */
|
||||||
|
@Override
|
||||||
|
public String getParameter(String name) {
|
||||||
|
String value = super.getParameter(name);
|
||||||
|
return getValue(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, String[]> getParameterMap() {
|
||||||
|
Map<String, String[]> params = super.getParameterMap();
|
||||||
|
if (params != null) {
|
||||||
|
params.forEach((key, value) -> {
|
||||||
|
for (int i = 0; i < value.length; i++) {
|
||||||
|
value[i] = getValue(value[i]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String[] getParameterValues(String name) {
|
||||||
|
String[] params = super.getParameterValues(name);
|
||||||
|
if (params != null) {
|
||||||
|
for (int i = 0; i < params.length; i++) {
|
||||||
|
params[i] = getValue(params[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getValue(String srcValue) {
|
||||||
|
if (srcValue == null) {
|
||||||
|
return srcValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return HtmlUtils.htmlEscape(srcValue);
|
||||||
|
}
|
||||||
|
/** form parameter 관련 메소드 END */
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,131 @@
|
|||||||
|
package io.company.localhost.common.wrapper;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.HandlerExecutionChain;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
|
||||||
|
//특정 어노테이션이 있는지 확인하는용 @ReqMap 확인용
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class RequestMappingWrapper {
|
||||||
|
|
||||||
|
private RequestMappingHandlerMapping mapping;
|
||||||
|
|
||||||
|
public RequestMappingWrapper(
|
||||||
|
@Nullable @Qualifier("requestMappingHandlerMapping") RequestMappingHandlerMapping mapping) {
|
||||||
|
this.mapping = mapping;
|
||||||
|
log.debug("RequestMappingHandlerMapping {}", this.mapping);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* controller method 특정 annotation 가져오는 메소드
|
||||||
|
* @param HttpServletRequest
|
||||||
|
* @param Class<? extends Annotation>
|
||||||
|
* @return Annotation
|
||||||
|
*/
|
||||||
|
public <T> T getAnnotation(HttpServletRequest request, Class<? extends Annotation> annotationType) {
|
||||||
|
if (Objects.isNull(mapping)) {
|
||||||
|
log.warn("RequestMappingHandlerMapping is NULL");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// yml 파일에 아래와 같이 설정해줘야 함 (spring-boot 2.6.x issue)
|
||||||
|
// spring.mvc.pathmatch.matching-strategy=ANT-PATH-MATCHER
|
||||||
|
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||||
|
|
||||||
|
if (Objects.nonNull(chain)) {
|
||||||
|
Object handler = chain.getHandler();
|
||||||
|
if (Objects.nonNull(handler) && handler instanceof HandlerMethod) {
|
||||||
|
HandlerMethod handlerMethod = (HandlerMethod) chain.getHandler();
|
||||||
|
// Annotation methodAnnotation =
|
||||||
|
// handlerMethod.getMethodAnnotation(annotationType);
|
||||||
|
//
|
||||||
|
// return methodAnnotation;
|
||||||
|
return getAnnotation(handlerMethod, annotationType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Exception {}, {}", request.getRequestURI(), request.getHeader("referer"), e);
|
||||||
|
throw new IllegalArgumentException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <T> T getAnnotation(HandlerMethod handlerMethod, Class<? extends Annotation> annotationType) {
|
||||||
|
if (Objects.nonNull(handlerMethod)) {
|
||||||
|
Annotation methodAnnotation = handlerMethod.getMethodAnnotation(annotationType);
|
||||||
|
|
||||||
|
return (T) methodAnnotation;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* controller method 특정 annotation 선언 여부
|
||||||
|
* @param HttpServletRequest
|
||||||
|
* @param Class<A>[]
|
||||||
|
* @return boolean
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <A extends Annotation> boolean hasAnyAnnotation(HttpServletRequest request, Class<A>... annotationTypes) {
|
||||||
|
if (Objects.isNull(mapping)) {
|
||||||
|
log.warn("RequestMappingHandlerMapping is NULL");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// yml 파일에 아래와 같이 설정해줘야 함 (spring-boot 2.6.x issue)
|
||||||
|
// spring.mvc.pathmatch.matching-strategy=ANT-PATH-MATCHER
|
||||||
|
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||||
|
|
||||||
|
if (Objects.nonNull(chain)) {
|
||||||
|
Object handler = chain.getHandler();
|
||||||
|
if (Objects.nonNull(handler) && handler instanceof HandlerMethod) {
|
||||||
|
HandlerMethod handlerMethod = (HandlerMethod) chain.getHandler();
|
||||||
|
// for(Class<A> anno : annotationTypes) {
|
||||||
|
// A methodAnnotation = handlerMethod.getMethodAnnotation(anno);
|
||||||
|
// if ( Objects.nonNull(methodAnnotation) ) {
|
||||||
|
// return true;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
return hasAnyAnnotation(handlerMethod, annotationTypes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Exception {}, {}", request.getRequestURI(), request.getHeader("referer"), e);
|
||||||
|
throw new IllegalArgumentException(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public <A extends Annotation> boolean hasAnyAnnotation(HandlerMethod handlerMethod, Class<A>... annotationTypes) {
|
||||||
|
if (Objects.nonNull(handlerMethod)) {
|
||||||
|
for (Class<A> anno : annotationTypes) {
|
||||||
|
A methodAnnotation = handlerMethod.getMethodAnnotation(anno);
|
||||||
|
|
||||||
|
if (Objects.nonNull(methodAnnotation)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,63 @@
|
|||||||
|
package io.company.localhost.controller.common;
|
||||||
|
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import io.company.localhost.common.annotation.ParameterCheck;
|
||||||
|
import io.company.localhost.common.annotation.ReqMap;
|
||||||
|
import io.company.localhost.common.dto.MapDto;
|
||||||
|
import io.company.localhost.common.response.ApiResponse;
|
||||||
|
|
||||||
|
import io.company.localhost.service.TestService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RequestMapping("/api/test/")
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class TestController {
|
||||||
|
|
||||||
|
private final TestService testService;
|
||||||
|
|
||||||
|
//annotation TEST
|
||||||
|
@ParameterCheck
|
||||||
|
@PostMapping("parameter")
|
||||||
|
public ApiResponse<String> parameter(@ReqMap MapDto map) {
|
||||||
|
return ApiResponse.ok("test");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//MyBatis TEST
|
||||||
|
@GetMapping("getCong")
|
||||||
|
public ApiResponse getCong() {
|
||||||
|
return ApiResponse.ok(testService.getCong());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ParameterCheck
|
||||||
|
@GetMapping("reqTest1")
|
||||||
|
public ApiResponse<?> reqTest1(@ReqMap MapDto map) {
|
||||||
|
return ApiResponse.ok("OK");
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterCheck
|
||||||
|
@PostMapping("reqTest1")
|
||||||
|
public ApiResponse<?> reqTest2(@ReqMap MapDto map) {
|
||||||
|
return ApiResponse.ok("OK");
|
||||||
|
}
|
||||||
|
|
||||||
|
@ParameterCheck
|
||||||
|
@PatchMapping("reqTest1")
|
||||||
|
public ApiResponse<?> reqTest3(@ReqMap MapDto map) {
|
||||||
|
return ApiResponse.ok("OK");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ParameterCheck
|
||||||
|
@DeleteMapping("reqTest1")
|
||||||
|
public ApiResponse<?> reqTest4(@ReqMap MapDto map) {
|
||||||
|
return ApiResponse.ok("OK");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,120 @@
|
|||||||
|
package io.company.localhost.controller.common;
|
||||||
|
|
||||||
|
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.*;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.security.authentication.RememberMeAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
|
import org.springframework.security.core.context.SecurityContext;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolderStrategy;
|
||||||
|
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import io.company.localhost.common.response.ApiResponse;
|
||||||
|
import io.company.localhost.utils.AuthUtil;
|
||||||
|
import io.company.localhost.utils.SessionListener;
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
import jakarta.servlet.http.Cookie;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import jakarta.servlet.http.HttpSession;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/user")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class UserController {
|
||||||
|
|
||||||
|
|
||||||
|
//security 인증 체크
|
||||||
|
@GetMapping("userInfo")
|
||||||
|
public ApiResponse<MemberVo> getUserInfo(@AuthenticationPrincipal MemberVo memberVo) {
|
||||||
|
SecurityContextHolderStrategy contextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
|
||||||
|
log.info(">> contextHolderStrategy : {}", contextHolderStrategy);
|
||||||
|
SecurityContext context = contextHolderStrategy.getContext();
|
||||||
|
log.info(">> context : {}", context);
|
||||||
|
Authentication authentication = context.getAuthentication();
|
||||||
|
log.info(">> authentication : {}", authentication);
|
||||||
|
log.info(">> memberVo : {}", memberVo);
|
||||||
|
|
||||||
|
MemberVo user = AuthUtil.getUser();
|
||||||
|
log.info(">> AuthUtil : {}", user);
|
||||||
|
|
||||||
|
return ApiResponse.ok(memberVo);
|
||||||
|
}
|
||||||
|
|
||||||
|
//유저 세션 체크
|
||||||
|
@GetMapping(value = "check")
|
||||||
|
public ApiResponse<?> check(){
|
||||||
|
Map<String, HttpSession> sessions = SessionListener.getSessions();
|
||||||
|
Map<String, Object> sessionData = new HashMap<>();
|
||||||
|
|
||||||
|
for (Map.Entry<String, HttpSession> entry : sessions.entrySet()) {
|
||||||
|
String sessionId = entry.getKey();
|
||||||
|
HttpSession session = entry.getValue();
|
||||||
|
Object principal = session.getAttribute("SPRING_SECURITY_CONTEXT");
|
||||||
|
sessionData.put(sessionId, principal);
|
||||||
|
}
|
||||||
|
return ApiResponse.ok(sessionData);
|
||||||
|
}
|
||||||
|
|
||||||
|
// rememberMe 확인용
|
||||||
|
@GetMapping(value = "rememberCheck")
|
||||||
|
public ApiResponse<?> rememberCheck(HttpServletRequest request) {
|
||||||
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
boolean remember = false;
|
||||||
|
|
||||||
|
if (authentication != null && authentication instanceof RememberMeAuthenticationToken) {
|
||||||
|
remember = true;
|
||||||
|
}
|
||||||
|
// 쿠키 확인
|
||||||
|
Cookie[] cookies = request.getCookies();
|
||||||
|
if (cookies != null) {
|
||||||
|
for (Cookie cookie : cookies) {
|
||||||
|
if (SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY.equals(cookie.getName())) {
|
||||||
|
log.debug("Remember-Me cookie found: {}", cookie.getValue());
|
||||||
|
remember = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.debug("No cookies found");
|
||||||
|
}
|
||||||
|
return ApiResponse.ok(remember);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//로그아웃
|
||||||
|
@GetMapping("/logout")
|
||||||
|
public ApiResponse<String> logout(HttpServletRequest request, HttpServletResponse response) {
|
||||||
|
String returnMessage = "Successfully logged out";
|
||||||
|
|
||||||
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
if (authentication != null) {
|
||||||
|
new SecurityContextLogoutHandler().logout(request, response, authentication);
|
||||||
|
|
||||||
|
// Remember-Me 쿠키 삭제
|
||||||
|
Cookie rememberMeCookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, null);
|
||||||
|
rememberMeCookie.setPath("/");
|
||||||
|
rememberMeCookie.setMaxAge(0);
|
||||||
|
rememberMeCookie.setHttpOnly(true);
|
||||||
|
rememberMeCookie.setSecure(request.isSecure());
|
||||||
|
response.addCookie(rememberMeCookie);
|
||||||
|
} else {
|
||||||
|
returnMessage = "Failed to log out";
|
||||||
|
}
|
||||||
|
|
||||||
|
return ApiResponse.ok(returnMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
11
src/main/java/io/company/localhost/mapper/MemberMapper.java
Normal file
11
src/main/java/io/company/localhost/mapper/MemberMapper.java
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package io.company.localhost.mapper;
|
||||||
|
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface MemberMapper {
|
||||||
|
|
||||||
|
MemberVo findByLoginId(String id);
|
||||||
|
}
|
||||||
11
src/main/java/io/company/localhost/mapper/TestMapper.java
Normal file
11
src/main/java/io/company/localhost/mapper/TestMapper.java
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package io.company.localhost.mapper;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface TestMapper {
|
||||||
|
|
||||||
|
List<Long> getCong();
|
||||||
|
}
|
||||||
19
src/main/java/io/company/localhost/service/TestService.java
Normal file
19
src/main/java/io/company/localhost/service/TestService.java
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
package io.company.localhost.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import io.company.localhost.mapper.TestMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class TestService {
|
||||||
|
|
||||||
|
private final TestMapper testMapper;
|
||||||
|
|
||||||
|
public List<Long> getCong(){
|
||||||
|
return testMapper.getCong();
|
||||||
|
}
|
||||||
|
}
|
||||||
109
src/main/java/io/company/localhost/utils/AuthUtil.java
Normal file
109
src/main/java/io/company/localhost/utils/AuthUtil.java
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.context.SecurityContext;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||||
|
|
||||||
|
import io.company.localhost.vo.MemberVo;
|
||||||
|
import lombok.experimental.UtilityClass;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
|
||||||
|
// 로그인 유저 정보
|
||||||
|
@Slf4j
|
||||||
|
@UtilityClass
|
||||||
|
public class AuthUtil {
|
||||||
|
|
||||||
|
public static Authentication getAuthentication() {
|
||||||
|
try {
|
||||||
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
if (Objects.isNull(authentication)) {
|
||||||
|
SecurityContext securityContext = (SecurityContext)SessionUtil
|
||||||
|
.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
|
||||||
|
if (securityContext != null) {
|
||||||
|
authentication = securityContext.getAuthentication();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return authentication;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("", e);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 사용자 인증 정보 return
|
||||||
|
*
|
||||||
|
* @return MapDto
|
||||||
|
*/
|
||||||
|
public static MemberVo getUser() {
|
||||||
|
try {
|
||||||
|
Authentication authentication = getAuthentication();
|
||||||
|
if (Objects.isNull(authentication)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object principal = authentication.getPrincipal();
|
||||||
|
if (principal instanceof MemberVo) {
|
||||||
|
MemberVo member = (MemberVo)principal;
|
||||||
|
|
||||||
|
return member;
|
||||||
|
} else {
|
||||||
|
log.debug("principal type {}[{}]", principal, principal == null ? null : principal.getClass());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("", e);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 로그인 여부 return
|
||||||
|
*
|
||||||
|
* @return true : 로그인, false : 비로그인
|
||||||
|
*/
|
||||||
|
public static boolean isLoggedIn() {
|
||||||
|
// return
|
||||||
|
// hasRole(com.example.securityweb.common.security.SecurityUserRole.UserRole.ROLE_DEFAULT.name());
|
||||||
|
return isAuthenticated();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 인증 여부 return
|
||||||
|
*
|
||||||
|
* @return true : 인증, false : 비인증
|
||||||
|
*/
|
||||||
|
public static boolean isAuthenticated() {
|
||||||
|
Authentication authentication = getAuthentication();
|
||||||
|
if (Objects.isNull(authentication)) {
|
||||||
|
return false;
|
||||||
|
} else if (authentication instanceof AnonymousAuthenticationToken) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return authentication.isAuthenticated();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasRole(String role) {
|
||||||
|
Authentication authentication = getAuthentication();
|
||||||
|
if (Objects.isNull(authentication)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
|
||||||
|
// log.debug("authorities {}", authorities);
|
||||||
|
return authorities.contains(new SimpleGrantedAuthority(role));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
68
src/main/java/io/company/localhost/utils/CamelUtil.java
Normal file
68
src/main/java/io/company/localhost/utils/CamelUtil.java
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import lombok.experimental.UtilityClass;
|
||||||
|
|
||||||
|
@UtilityClass
|
||||||
|
public class CamelUtil {
|
||||||
|
|
||||||
|
private static final String REGEX = "([a-z])([A-Z])";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* underscore ('_') 가 포함되어 있는 문자열을 Camel Case ( 낙타등 표기법 - 단어의 변경시에 대문자로 시작하는 형태. 시작은
|
||||||
|
* 소문자) 로 변환해주는 utility 메서드 ('_' 가 나타나지 않고 첫문자가 대문자인 경우도 변환 처리 함.)
|
||||||
|
* @param underScore - '_' 가 포함된 변수명
|
||||||
|
* @return Camel 표기법 변수명
|
||||||
|
*/
|
||||||
|
public static String snakeToCamel(String underScore) {
|
||||||
|
|
||||||
|
// '_' 가 나타나지 않으면 이미 camel case 로 가정함.
|
||||||
|
// 단 첫째문자가 대문자이면 camel case 변환 (전체를 소문자로) 처리가
|
||||||
|
// 필요하다고 가정함. --> 아래 로직을 수행하면 바뀜
|
||||||
|
if (underScore.indexOf('_') < 0 && Character.isLowerCase(underScore.charAt(0))) {
|
||||||
|
return underScore;
|
||||||
|
}
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
boolean nextUpper = false;
|
||||||
|
int len = underScore.length();
|
||||||
|
|
||||||
|
for (int i = 0; i < len; i++) {
|
||||||
|
char currentChar = underScore.charAt(i);
|
||||||
|
if (currentChar == '_') {
|
||||||
|
nextUpper = true;
|
||||||
|
} else {
|
||||||
|
if (nextUpper) {
|
||||||
|
result.append(Character.toUpperCase(currentChar));
|
||||||
|
nextUpper = false;
|
||||||
|
} else {
|
||||||
|
result.append(Character.toLowerCase(currentChar));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* camel case to snake case
|
||||||
|
* @param Camel 표기법 변수명
|
||||||
|
* @return underScore - '_' 가 포함된 변수명
|
||||||
|
*/
|
||||||
|
public static String camelToSnake(String camelStr) {
|
||||||
|
Matcher matcher = Pattern.compile(REGEX).matcher(camelStr);
|
||||||
|
|
||||||
|
StringBuffer sb = new StringBuffer();
|
||||||
|
while (matcher.find()) {
|
||||||
|
String format = String.format("%s_%s", matcher.group(1), matcher.group(2));
|
||||||
|
matcher.appendReplacement(sb, format);
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuffer stringBuffer = matcher.appendTail(sb);
|
||||||
|
String convert = stringBuffer.toString().toLowerCase();
|
||||||
|
|
||||||
|
return convert;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
122
src/main/java/io/company/localhost/utils/ContextUtil.java
Normal file
122
src/main/java/io/company/localhost/utils/ContextUtil.java
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import org.springframework.beans.BeansException;
|
||||||
|
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||||
|
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||||
|
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.context.ConfigurableApplicationContext;
|
||||||
|
|
||||||
|
import io.company.localhost.common.context.ApplicationContextProvider;
|
||||||
|
import lombok.experimental.UtilityClass;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@UtilityClass
|
||||||
|
public class ContextUtil {
|
||||||
|
|
||||||
|
/****************************************************************************************************
|
||||||
|
*
|
||||||
|
* Application Context에 등록된 Object 가져오는 method AND Application Context에 등록된 Object
|
||||||
|
* destroy & remove method
|
||||||
|
*
|
||||||
|
****************************************************************************************************/
|
||||||
|
|
||||||
|
private static ApplicationContext getContext() {
|
||||||
|
return ApplicationContextProvider.getContext();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get bean from context
|
||||||
|
* @param Class - requiredType
|
||||||
|
* @return T - requiredType 객체
|
||||||
|
*/
|
||||||
|
public static <T> T getBean(Class<T> requiredType) {
|
||||||
|
if (getContext() == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return getContext().getBean(requiredType);
|
||||||
|
} catch (BeansException e) {
|
||||||
|
log.error("BeanUtil[getBean] Exception [{}]{}", e.getMessage(), e.toString());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get bean from context
|
||||||
|
* @param String - 등록 이름
|
||||||
|
* @param Class - requiredType
|
||||||
|
* @return T - requiredType 객체
|
||||||
|
*/
|
||||||
|
public static <T> T getBean(String beanName, Class<T> requiredType) {
|
||||||
|
if (getContext() == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return getContext().getBean(beanName, requiredType);
|
||||||
|
} catch (BeansException e) {
|
||||||
|
log.error("BeanUtil[getBean] Exception [{}]{}", e.getMessage(), e.toString());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get bean from context
|
||||||
|
* @param String - 등록 이름s
|
||||||
|
* @return Object - 해당 이름으로 등록된 Object
|
||||||
|
*/
|
||||||
|
public static Object getBean(String beanName) {
|
||||||
|
if (getContext() == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return getContext().getBean(beanName);
|
||||||
|
} catch (BeansException e) {
|
||||||
|
log.error("BeanUtil[getBean] Exception [{}]{}", e.getMessage(), e.toString());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* destroy & remove bean from context
|
||||||
|
* @param String - bean name
|
||||||
|
*/
|
||||||
|
public static void destroySingleton(String beanName) {
|
||||||
|
ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) getContext()).getBeanFactory();
|
||||||
|
|
||||||
|
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) factory;
|
||||||
|
|
||||||
|
boolean isExistBean = beanFactory.containsSingleton(beanName);
|
||||||
|
log.debug("isExistBean {}", isExistBean);
|
||||||
|
|
||||||
|
beanFactory.destroySingleton(beanName);
|
||||||
|
beanFactory.removeBeanDefinition(beanName);
|
||||||
|
|
||||||
|
isExistBean = beanFactory.containsSingleton(beanName);
|
||||||
|
log.debug("isExistBean {}", isExistBean);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated
|
||||||
|
public static void destroySingleton2(String beanName) {
|
||||||
|
DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) getContext()
|
||||||
|
.getAutowireCapableBeanFactory();
|
||||||
|
|
||||||
|
boolean isExistBean = registry.containsSingleton(beanName);
|
||||||
|
log.debug("isExistBean {}", isExistBean);
|
||||||
|
|
||||||
|
registry.destroySingleton(beanName);
|
||||||
|
|
||||||
|
isExistBean = registry.containsSingleton(beanName);
|
||||||
|
log.debug("isExistBean {}", isExistBean);
|
||||||
|
|
||||||
|
//
|
||||||
|
ConfigurableListableBeanFactory factory = ((ConfigurableApplicationContext) getContext()).getBeanFactory();
|
||||||
|
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) factory;
|
||||||
|
beanFactory.removeBeanDefinition(beanName);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
106
src/main/java/io/company/localhost/utils/ConvertUtil.java
Normal file
106
src/main/java/io/company/localhost/utils/ConvertUtil.java
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
// VO <-> MAP 변환용
|
||||||
|
public class ConvertUtil {
|
||||||
|
|
||||||
|
private ConvertUtil() {}
|
||||||
|
|
||||||
|
// VO -> Map
|
||||||
|
public static Map<String, Object> convertToMap(Object obj) {
|
||||||
|
try {
|
||||||
|
if (Objects.isNull(obj)) {
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
Map<String, Object> convertMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
Field[] fields = obj.getClass().getDeclaredFields();
|
||||||
|
|
||||||
|
for (Field field : fields) {
|
||||||
|
field.setAccessible(true);
|
||||||
|
convertMap.put(field.getName(), field.get(obj));
|
||||||
|
}
|
||||||
|
return convertMap;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Map -> VO
|
||||||
|
public static <T> T convertToValueObject(Map<String, Object> map, Class<T> type) {
|
||||||
|
try {
|
||||||
|
if (Objects.isNull(type)) {
|
||||||
|
throw new NullPointerException("Class cannot be null");
|
||||||
|
}
|
||||||
|
if (Objects.isNull(map) || map.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("map is null or empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
T instance = type.getConstructor().newInstance();
|
||||||
|
Field[] fields = type.getDeclaredFields();
|
||||||
|
|
||||||
|
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||||
|
for (Field field : fields) {
|
||||||
|
if (entry.getKey().equals(field.getName())) {
|
||||||
|
field.setAccessible(true);
|
||||||
|
|
||||||
|
Object value = Objects.isNull(entry.getValue()) && field.getType().isPrimitive()
|
||||||
|
? getDefaultValue(field.getType())
|
||||||
|
: map.get(field.getName());
|
||||||
|
|
||||||
|
field.set(instance, value);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return instance;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//List<Vo> -> List<Map>
|
||||||
|
public static List<Map<String, Object>> convertToMaps(List<?> list) {
|
||||||
|
if (list == null || list.isEmpty()) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
return list.stream()
|
||||||
|
.map(ConvertUtil::convertToMap)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
//List<Map> -> List<Vo>
|
||||||
|
public static <T> List<T> convertToValueObjects(List<Map<String, Object>> list, Class<T> type) {
|
||||||
|
if (list == null || list.isEmpty()) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
List<T> convertList = new ArrayList<>(list.size());
|
||||||
|
|
||||||
|
for (Map<String, Object> map : list) {
|
||||||
|
convertList.add(convertToValueObject(map, type));
|
||||||
|
}
|
||||||
|
return convertList;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object getDefaultValue(Class<?> type) {
|
||||||
|
return switch (type.getName()) {
|
||||||
|
case "byte", "short", "int" -> 0;
|
||||||
|
case "long" -> 0L;
|
||||||
|
case "float" -> 0.0f;
|
||||||
|
case "double" -> 0.0d;
|
||||||
|
case "char" -> '\u0000';
|
||||||
|
case "boolean" -> false;
|
||||||
|
default -> null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
50
src/main/java/io/company/localhost/utils/ExceptionUtil.java
Normal file
50
src/main/java/io/company/localhost/utils/ExceptionUtil.java
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import lombok.experimental.UtilityClass;
|
||||||
|
|
||||||
|
// try-catch 시 error 메시지 처리용
|
||||||
|
// System.out.println(ExceptionUtil.messageTrace(t)); 등등
|
||||||
|
@UtilityClass
|
||||||
|
public class ExceptionUtil {
|
||||||
|
|
||||||
|
private static final String delimiter = ": ";
|
||||||
|
|
||||||
|
public static String stackTrace(Throwable t) {
|
||||||
|
StringWriter out = new StringWriter();
|
||||||
|
try (PrintWriter w = new PrintWriter(out)) {
|
||||||
|
t.printStackTrace(w);
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String messageTrace(Throwable t) {
|
||||||
|
if (Objects.isNull(t)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
sb.append(t.getClass().getName()).append(delimiter).append(t.getMessage());
|
||||||
|
|
||||||
|
messageTrace(t.getCause(), sb, 4);
|
||||||
|
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void messageTrace(Throwable t, StringBuilder sb, int remaining) {
|
||||||
|
if (Objects.isNull(t)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sb.append('\n').append(t.getClass().getName()).append(delimiter).append(t.getMessage());
|
||||||
|
|
||||||
|
if (remaining == 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
messageTrace(t.getCause(), sb, --remaining);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
207
src/main/java/io/company/localhost/utils/JacksonUtil.java
Normal file
207
src/main/java/io/company/localhost/utils/JacksonUtil.java
Normal file
@ -0,0 +1,207 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import org.springframework.core.io.ClassPathResource;
|
||||||
|
import org.springframework.util.ResourceUtils;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.type.CollectionType;
|
||||||
|
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||||
|
|
||||||
|
import io.company.localhost.common.config.JacksonCommonConfig;
|
||||||
|
import lombok.experimental.UtilityClass;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
//json 변환 유틸
|
||||||
|
@Slf4j
|
||||||
|
@UtilityClass
|
||||||
|
public class JacksonUtil {
|
||||||
|
|
||||||
|
private ObjectMapper jacksonMapper() {
|
||||||
|
ObjectMapper objectMapper = ContextUtil.getBean(ObjectMapper.class);
|
||||||
|
if (objectMapper == null) {
|
||||||
|
objectMapper = JacksonCommonConfig.jackson2ObjectMapperBuilder().build();
|
||||||
|
}
|
||||||
|
|
||||||
|
return objectMapper.copy();
|
||||||
|
}
|
||||||
|
|
||||||
|
private XmlMapper xmlMapper() {
|
||||||
|
return new XmlMapper();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* object -> json
|
||||||
|
*
|
||||||
|
* @param Object
|
||||||
|
* @return String
|
||||||
|
*/
|
||||||
|
public static String toJson(Object source) {
|
||||||
|
if (Objects.isNull(source)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
ObjectMapper objectMapper = jacksonMapper();
|
||||||
|
|
||||||
|
return objectMapper.writeValueAsString(source);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
log.error("toJson Exception", e);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* json -> object
|
||||||
|
*
|
||||||
|
* @param jsonString
|
||||||
|
* @param targetType
|
||||||
|
* @return T
|
||||||
|
*/
|
||||||
|
public static <T> T fromJson(String jsonString, Class<T> targetType) {
|
||||||
|
if (StringUtils.hasText(jsonString) == false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
ObjectMapper objectMapper = jacksonMapper();
|
||||||
|
|
||||||
|
return objectMapper.readValue(jsonString, targetType);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
log.error("fromJson Exception", e);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* json -> object
|
||||||
|
*
|
||||||
|
* @param jsonString
|
||||||
|
* @param TypeReference<T> - ex) new TypeReference<List<MapDto>>() {}
|
||||||
|
* @return T
|
||||||
|
*/
|
||||||
|
public static <T> T fromJson(String jsonString, TypeReference<T> targetType) {
|
||||||
|
if (StringUtils.hasText(jsonString) == false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
ObjectMapper objectMapper = jacksonMapper();
|
||||||
|
|
||||||
|
return objectMapper.readValue(jsonString, targetType);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
log.error("fromJson Exception", e);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* json -> List<E>
|
||||||
|
*
|
||||||
|
* @paramjsonString
|
||||||
|
* @param targetType
|
||||||
|
* @return List<T>
|
||||||
|
*/
|
||||||
|
public static <E> List<E> listFromJson(String jsonString, Class<E> targetType) {
|
||||||
|
if (StringUtils.hasText(jsonString) == false) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
ObjectMapper objectMapper = jacksonMapper();
|
||||||
|
|
||||||
|
CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, targetType);
|
||||||
|
|
||||||
|
return objectMapper.readValue(jsonString, listType);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
log.error("listFromJson Exception", e);
|
||||||
|
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static <T> T xmlToJsonByJackson(String filePath) {
|
||||||
|
if (StringUtils.hasText(filePath) == false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
InputStream inputStream = null;
|
||||||
|
try {
|
||||||
|
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + filePath);
|
||||||
|
|
||||||
|
log.debug("filePath by classpath");
|
||||||
|
|
||||||
|
Map<String, Object> map = xmlMapper().readValue(file, Map.class);
|
||||||
|
return (T) map;
|
||||||
|
} catch (Exception e) {
|
||||||
|
// log.error("FileNotFoundException", e);
|
||||||
|
|
||||||
|
// jar 배포시 ResourceUtils 사용 안되어 아래 방법 사용
|
||||||
|
try {
|
||||||
|
ClassPathResource resource = new ClassPathResource(filePath);
|
||||||
|
inputStream = resource.getInputStream();
|
||||||
|
|
||||||
|
log.debug("filePath by ClassPathResource");
|
||||||
|
|
||||||
|
Map<String, Object> map = xmlMapper().readValue(inputStream, Map.class);
|
||||||
|
return (T) map;
|
||||||
|
} catch (IOException ioe) {
|
||||||
|
log.error("xmlToJson Exception", e);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (inputStream != null) {
|
||||||
|
try {
|
||||||
|
//
|
||||||
|
inputStream.close();
|
||||||
|
} catch (IOException e) {
|
||||||
|
//
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static Map<String, Object> toMap(Object source) {
|
||||||
|
return to(source, Map.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> T to(Object source, Class<T> targetType) {
|
||||||
|
if (Objects.isNull(source)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjectMapper objectMapper = jacksonMapper();
|
||||||
|
|
||||||
|
return objectMapper.convertValue(source, targetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> T to(Object source, TypeReference<T> targetType) {
|
||||||
|
String jsonStr = toJson(source);
|
||||||
|
|
||||||
|
return fromJson(jsonStr, targetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <E> List<E> toList(Object source, Class<E> targetType) {
|
||||||
|
String jsonStr = toJson(source);
|
||||||
|
|
||||||
|
return listFromJson(jsonStr, targetType);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,31 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpSession;
|
||||||
|
import jakarta.servlet.http.HttpSessionEvent;
|
||||||
|
import jakarta.servlet.http.HttpSessionListener;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
//세션 확인용
|
||||||
|
@Component
|
||||||
|
public class SessionListener implements HttpSessionListener {
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
private static final Map<String, HttpSession> sessions = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sessionCreated(HttpSessionEvent event) {
|
||||||
|
HttpSession session = event.getSession();
|
||||||
|
sessions.put(session.getId(), session);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sessionDestroyed(HttpSessionEvent event) {
|
||||||
|
HttpSession session = event.getSession();
|
||||||
|
sessions.remove(session.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
89
src/main/java/io/company/localhost/utils/SessionUtil.java
Normal file
89
src/main/java/io/company/localhost/utils/SessionUtil.java
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import org.springframework.web.util.WebUtils;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpSession;
|
||||||
|
import lombok.experimental.UtilityClass;
|
||||||
|
|
||||||
|
@UtilityClass
|
||||||
|
public class SessionUtil {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* attribute 값을 가져 오기 위한 method
|
||||||
|
*
|
||||||
|
* @param String attribute key name
|
||||||
|
* @return Object attribute obj
|
||||||
|
*/
|
||||||
|
public static Object getAttribute(String name) throws Exception {
|
||||||
|
HttpServletRequest request = WebUtil.getRequest();
|
||||||
|
if (request != null) {
|
||||||
|
return WebUtils.getSessionAttribute(request, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static <T> T getAttribute(String name, Class<T> returnType) throws Exception {
|
||||||
|
return (T) getAttribute(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* attribute 설정 method
|
||||||
|
*
|
||||||
|
* @param String attribute key name
|
||||||
|
* @param Object attribute obj
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static void setAttribute(String name, Object object) {
|
||||||
|
// RequestContextHolder.getRequestAttributes().setAttribute(name, object,
|
||||||
|
// RequestAttributes.SCOPE_SESSION);
|
||||||
|
// WebUtil.getRequestAttributes().setAttribute(name, object,
|
||||||
|
// RequestAttributes.SCOPE_SESSION);
|
||||||
|
|
||||||
|
HttpServletRequest request = WebUtil.getRequest();
|
||||||
|
if (request != null) {
|
||||||
|
WebUtils.setSessionAttribute(request, name, object);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 설정한 attribute 삭제
|
||||||
|
*
|
||||||
|
* @param String attribute key name
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static void removeAttribute(String name) {
|
||||||
|
// RequestContextHolder.getRequestAttributes().removeAttribute(name,
|
||||||
|
// RequestAttributes.SCOPE_SESSION);
|
||||||
|
HttpServletRequest request = WebUtil.getRequest();
|
||||||
|
HttpSession session = null;
|
||||||
|
if (request != null) {
|
||||||
|
session = request.getSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request != null && session != null) {
|
||||||
|
session.removeAttribute(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* session id
|
||||||
|
*
|
||||||
|
* @param void
|
||||||
|
* @return String SessionId 값
|
||||||
|
*/
|
||||||
|
public static String getSessionId() {
|
||||||
|
// return RequestContextHolder.getRequestAttributes().getSessionId();
|
||||||
|
// return WebUtil.getRequestAttributes().getSessionId();
|
||||||
|
|
||||||
|
HttpServletRequest request = WebUtil.getRequest();
|
||||||
|
if (request != null) {
|
||||||
|
return WebUtils.getSessionId(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
144
src/main/java/io/company/localhost/utils/WebUtil.java
Normal file
144
src/main/java/io/company/localhost/utils/WebUtil.java
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
package io.company.localhost.utils;
|
||||||
|
|
||||||
|
import java.lang.annotation.Annotation;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.HandlerMapping;
|
||||||
|
|
||||||
|
import io.company.localhost.common.wrapper.RequestMappingWrapper;
|
||||||
|
import io.company.localhost.common.webEnum.WebEnum;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
|
||||||
|
//web 요청에 대한 정보얻을 때 사용
|
||||||
|
@Slf4j
|
||||||
|
public class WebUtil {
|
||||||
|
|
||||||
|
private WebUtil() {
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HttpServletRequest를 가져옴
|
||||||
|
*
|
||||||
|
* @return HttpServletRequest
|
||||||
|
*/
|
||||||
|
public static HttpServletRequest getRequest() {
|
||||||
|
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HttpServletResponse를 가져옴
|
||||||
|
*
|
||||||
|
* @return HttpServletResponse
|
||||||
|
*/
|
||||||
|
public static HttpServletResponse getResponse() {
|
||||||
|
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ajax 호출 여부
|
||||||
|
*
|
||||||
|
* @param HttpServletRequest
|
||||||
|
* @return boolean - true : ajax호출, false : 일반(?) 호출
|
||||||
|
*/
|
||||||
|
public static boolean isAjax(HttpServletRequest request) {
|
||||||
|
// String xRequestedWith = request.getHeader("X-REQUESTED-WITH");
|
||||||
|
// String xRequestedWith = request.getHeader("x-requested-with");
|
||||||
|
// String xRequestedWith = request.getHeader(HttpHeaders.CONTENT_TYPE);
|
||||||
|
if (Objects.isNull(request)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String xRequestedWith = request.getHeader("X-Requested-With");
|
||||||
|
return WebEnum.AJAX_IDENTIFIER.value().equals(xRequestedWith);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param HttpServletRequest
|
||||||
|
* @return boolean - true : json type, false : not json type
|
||||||
|
*/
|
||||||
|
public static boolean isJson(HttpServletRequest request) {
|
||||||
|
// String contentType = request.getHeader("Content-Type");
|
||||||
|
// return MediaType.APPLICATION_JSON_VALUE.equals(contentType);
|
||||||
|
if (Objects.isNull(request)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);
|
||||||
|
if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* controller method annotation 가져오는 메소드
|
||||||
|
*
|
||||||
|
* @param HttpServletRequest
|
||||||
|
* @param Class<? extends Annotation>
|
||||||
|
* @return Annotation
|
||||||
|
*/
|
||||||
|
public static <T> T getAnnotation(HttpServletRequest request, Class<? extends Annotation> annotationType) {
|
||||||
|
RequestMappingWrapper wrapper = ContextUtil.getBean(RequestMappingWrapper.class);
|
||||||
|
|
||||||
|
return wrapper.getAnnotation(request, annotationType);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> T getAnnotation(HandlerMethod handlerMethod, Class<? extends Annotation> annotationType) {
|
||||||
|
RequestMappingWrapper wrapper = ContextUtil.getBean(RequestMappingWrapper.class);
|
||||||
|
|
||||||
|
return wrapper.getAnnotation(handlerMethod, annotationType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* controller method annotation 있는지 여부
|
||||||
|
*
|
||||||
|
* @param HttpServletRequest
|
||||||
|
* @param Class<? extends Annotation>
|
||||||
|
* @return boolean
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static <A extends Annotation> boolean hasAnyAnnotation(HttpServletRequest request,
|
||||||
|
Class<A>... annotationTypes) {
|
||||||
|
RequestMappingWrapper wrapper = ContextUtil.getBean(RequestMappingWrapper.class);
|
||||||
|
|
||||||
|
return wrapper.hasAnyAnnotation(request, annotationTypes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static <A extends Annotation> boolean hasAnyAnnotation(HandlerMethod handlerMethod,
|
||||||
|
Class<A>... annotationTypes) {
|
||||||
|
RequestMappingWrapper wrapper = ContextUtil.getBean(RequestMappingWrapper.class);
|
||||||
|
|
||||||
|
return wrapper.hasAnyAnnotation(handlerMethod, annotationTypes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PathVariable
|
||||||
|
*
|
||||||
|
* @param HttpServletRequest
|
||||||
|
* @param String
|
||||||
|
* @return String
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public static String getPathVariable(HttpServletRequest request, String pathVariableName) {
|
||||||
|
final Map<String, String> pathVariables = (Map<String, String>) request
|
||||||
|
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
|
||||||
|
|
||||||
|
if (pathVariables == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return pathVariables.get(pathVariableName);
|
||||||
|
}
|
||||||
|
}
|
||||||
35
src/main/java/io/company/localhost/vo/MemberVo.java
Normal file
35
src/main/java/io/company/localhost/vo/MemberVo.java
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package io.company.localhost.vo;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFilter;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
import lombok.ToString;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@ToString
|
||||||
|
public class MemberVo {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private String loginId;
|
||||||
|
private String role;
|
||||||
|
private String name;
|
||||||
|
private String password;
|
||||||
|
private String email;
|
||||||
|
private String isUsed;
|
||||||
|
private String isDel;
|
||||||
|
private Date isrtDate;
|
||||||
|
private Date updtDate;
|
||||||
|
private Boolean remember;
|
||||||
|
}
|
||||||
86
src/main/resources/application.yml
Normal file
86
src/main/resources/application.yml
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
project:
|
||||||
|
name: localhost
|
||||||
|
locale: ko_KR
|
||||||
|
time-zone: Asia/Seoul
|
||||||
|
|
||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: ${project.name}
|
||||||
|
config:
|
||||||
|
import:
|
||||||
|
- classpath:datasource.yml
|
||||||
|
mvc:
|
||||||
|
servlet:
|
||||||
|
path: /
|
||||||
|
web:
|
||||||
|
resources:
|
||||||
|
add-mappings: false
|
||||||
|
|
||||||
|
mybatis:
|
||||||
|
mapper-locations: classpath:mapper/**/*.xml
|
||||||
|
|
||||||
|
#상태 모니터링 (재시작,메모리 등등 관리해줌)
|
||||||
|
#localhost:10325/health 로 보면 됨
|
||||||
|
management:
|
||||||
|
health:
|
||||||
|
defaults:
|
||||||
|
enabled: false
|
||||||
|
endpoints:
|
||||||
|
web:
|
||||||
|
base-path: /health
|
||||||
|
path-mapping:
|
||||||
|
health: check
|
||||||
|
exposure:
|
||||||
|
include: health,prometheus,metrics
|
||||||
|
endpoint:
|
||||||
|
health:
|
||||||
|
show-details: never
|
||||||
|
show-components: never
|
||||||
|
probes:
|
||||||
|
enabled: true
|
||||||
|
metrics:
|
||||||
|
web:
|
||||||
|
client:
|
||||||
|
max-uri-tags: 200
|
||||||
|
server:
|
||||||
|
max-uri-tags: 200
|
||||||
|
|
||||||
|
|
||||||
|
server:
|
||||||
|
shutdown: graceful
|
||||||
|
port: 10325
|
||||||
|
tomcat:
|
||||||
|
max-http-form-post-size: 20MB
|
||||||
|
max-connections: 1024 # default 8192
|
||||||
|
threads:
|
||||||
|
min-spare: 51
|
||||||
|
max: 101 # default 200
|
||||||
|
servlet:
|
||||||
|
encoding:
|
||||||
|
charset: UTF-8
|
||||||
|
enabled: true
|
||||||
|
force: true
|
||||||
|
context-path: /
|
||||||
|
session:
|
||||||
|
tracking-modes: cookie
|
||||||
|
timeout: 300m
|
||||||
|
cookie:
|
||||||
|
path: /
|
||||||
|
# 쿠키 보안
|
||||||
|
http-only: true
|
||||||
|
secure: true
|
||||||
|
same-site: NONE
|
||||||
|
|
||||||
|
# logging
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
jdbc:
|
||||||
|
sqlonly: off
|
||||||
|
sqltiming: info
|
||||||
|
resultsettable: off
|
||||||
|
audit: off
|
||||||
|
resultset: off
|
||||||
|
connection: off
|
||||||
|
io.company: DEBUG
|
||||||
|
io.company.localhost.mapper : off
|
||||||
|
|
||||||
13
src/main/resources/banner.txt
Normal file
13
src/main/resources/banner.txt
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
___ ________ ________ ________ ___ ___ ___ ________ ________ _________
|
||||||
|
|\ \ |\ __ \|\ ____\|\ __ \|\ \ |\ \|\ \|\ __ \|\ ____\|\___ ___\
|
||||||
|
\ \ \ \ \ \|\ \ \ \___|\ \ \|\ \ \ \ \ \ \\\ \ \ \|\ \ \ \___|\|___ \ \_|
|
||||||
|
\ \ \ \ \ \\\ \ \ \ \ \ __ \ \ \ \ \ __ \ \ \\\ \ \_____ \ \ \ \
|
||||||
|
\ \ \____\ \ \\\ \ \ \____\ \ \ \ \ \ \____\ \ \ \ \ \ \\\ \|____|\ \ \ \ \
|
||||||
|
\ \_______\ \_______\ \_______\ \__\ \__\ \_______\ \__\ \__\ \_______\____\_\ \ \ \__\
|
||||||
|
\|_______|\|_______|\|_______|\|__|\|__|\|_______|\|__|\|__|\|_______|\_________\ \|__|
|
||||||
|
\|_________|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Spring Boot Version : ${spring-boot.version}
|
||||||
|
Spring Boot Formatted Version : ${spring-boot.formatted-version}
|
||||||
14
src/main/resources/datasource.yml
Normal file
14
src/main/resources/datasource.yml
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
datasource:
|
||||||
|
localhost:
|
||||||
|
driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
|
||||||
|
jdbc-url: jdbc:log4jdbc:mariadb://192.168.0.251:3306/test
|
||||||
|
username: root
|
||||||
|
password: host1234
|
||||||
|
hikari:
|
||||||
|
maximum-pool-size: 1
|
||||||
|
minimum-idle: 1
|
||||||
|
connection-timeout: 30000
|
||||||
|
validation-timeout: 5000
|
||||||
|
max-lifetime: 1800000
|
||||||
|
idle-timeout: 600000
|
||||||
|
|
||||||
7
src/main/resources/log4jdbc.log4j2.properties
Normal file
7
src/main/resources/log4jdbc.log4j2.properties
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
#log4jdbc
|
||||||
|
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
|
||||||
|
log4jdbc.dump.sql.maxlinelength=0
|
||||||
|
log4jdbc.sqltiming.debug.stack.trace.class.skip=true
|
||||||
|
log4jdbc.sqltiming.format=false
|
||||||
|
log4jdbc.dump.sql.format=false
|
||||||
|
log4jdbc.drivers=org.mariadb.jdbc.Driver
|
||||||
24
src/main/resources/mapper/memberMapper.xml
Normal file
24
src/main/resources/mapper/memberMapper.xml
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
|
<mapper namespace="io.company.localhost.mapper.MemberMapper">
|
||||||
|
|
||||||
|
<select id="findByLoginId" parameterType="String" resultType="io.company.localhost.vo.MemberVo">
|
||||||
|
SELECT
|
||||||
|
MEMBER_ID AS id
|
||||||
|
, MEMBER_LOGIN_ID AS loginId
|
||||||
|
, MEMBER_ROLE AS role
|
||||||
|
, MEMBER_NAME AS name
|
||||||
|
, MEMBER_PASSWORD AS password
|
||||||
|
, MEMBER_EMAIL AS email
|
||||||
|
, IS_USED AS isUsed
|
||||||
|
, IS_DEL AS isDel
|
||||||
|
, ISRT_DATE AS isrtDate
|
||||||
|
, UPDT_DATE AS updtDate
|
||||||
|
, #{remember} as remember
|
||||||
|
FROM
|
||||||
|
MEMBER_TB
|
||||||
|
WHERE
|
||||||
|
MEMBER_LOGIN_ID = #{id}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
</mapper>
|
||||||
12
src/main/resources/mapper/testMapper.xml
Normal file
12
src/main/resources/mapper/testMapper.xml
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
|
<mapper namespace="io.company.localhost.mapper.TestMapper">
|
||||||
|
|
||||||
|
<select id="getCong" resultType="Long">
|
||||||
|
SELECT
|
||||||
|
*
|
||||||
|
FROM
|
||||||
|
test.cong
|
||||||
|
</select>
|
||||||
|
|
||||||
|
</mapper>
|
||||||
24
src/main/resources/sql/MEMBER_TB.sql
Normal file
24
src/main/resources/sql/MEMBER_TB.sql
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
DROP TABLE IF EXISTS MEMBER_TB;
|
||||||
|
|
||||||
|
CREATE TABLE MEMBER_TB
|
||||||
|
(
|
||||||
|
MEMBER_ID INT AUTO_INCREMENT NOT NULL,
|
||||||
|
MEMBER_LOGIN_ID VARCHAR(20) NOT NULL,
|
||||||
|
MEMBER_ROLE VARCHAR(20) DEFAULT 'ROLE_MEMBER' NOT NULL,
|
||||||
|
MEMBER_NAME VARCHAR(20) NOT NULL,
|
||||||
|
MEMBER_PASSWORD VARCHAR(400) NOT NULL,
|
||||||
|
MEMBER_EMAIL VARCHAR(100) NOT NULL,
|
||||||
|
IS_USED CHAR(1) DEFAULT 'Y' NOT NULL,
|
||||||
|
IS_DEL CHAR(1) DEFAULT 'N' NOT NULL,
|
||||||
|
ISRT_DATE DATETIME DEFAULT NOW() NOT NULL,
|
||||||
|
UPDT_DATE DATETIME ,
|
||||||
|
CONSTRAINT MEMBER_PK PRIMARY KEY (MEMBER_ID)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 비밀번호 1111
|
||||||
|
INSERT INTO MEMBER_TB (MEMBER_LOGIN_ID, MEMBER_NAME, MEMBER_PASSWORD, MEMBER_EMAIL)
|
||||||
|
VALUES ('member1', '고릴라', '$2a$12$umem9giXuB0lDzAQ1ofzmeVqwHHFX76sbMObVEWpcIOPc6O.47NGa', 'jo@naver.com');
|
||||||
|
|
||||||
|
-- 비밀번호 1234
|
||||||
|
INSERT INTO MEMBER_TB (MEMBER_LOGIN_ID, MEMBER_NAME, MEMBER_PASSWORD, MEMBER_EMAIL)
|
||||||
|
VALUES ('member2', '기리리', '$2a$12$R0ZgpAnBKh8CX0sATNRY8OyXPfke6GsXOxOA18gWyJ7RrnzOGnDOu', '');
|
||||||
12
src/main/resources/static/index.html
Normal file
12
src/main/resources/static/index.html
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Title</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
localhost bo test page
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@ -0,0 +1,13 @@
|
|||||||
|
package io.company.localhost;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
class LocalhostApplicationTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void contextLoads() {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user