From 142f1f24c2e4de7a6446387a3709bccc5bb0dd6b Mon Sep 17 00:00:00 2001 From: ckx6954 Date: Mon, 9 Dec 2024 12:45:15 +0900 Subject: [PATCH] commit --- .gitattributes | 3 + .gitignore | 37 +++ build.gradle | 130 +++++++++ gradle.properties | 20 ++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43583 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 252 ++++++++++++++++++ gradlew.bat | 94 +++++++ settings.gradle | 1 + .../localhost/LocalhostApplication.java | 45 ++++ .../company/localhost/ServletInitializer.java | 12 + .../common/annotation/ParameterCheck.java | 12 + .../localhost/common/annotation/ReqMap.java | 15 ++ .../localhost/common/aop/ParameterAop.java | 53 ++++ .../localhost/common/config/AuthConfig.java | 25 ++ .../common/config/ComponentScanConfig.java | 23 ++ .../common/config/JacksonCommonConfig.java | 50 ++++ .../common/config/SecurityConfig.java | 125 +++++++++ .../localhost/common/config/WebMvcConfig.java | 72 +++++ .../config/mybatis/DataSourceConfig.java | 34 +++ .../config/mybatis/DataSourceProperties.java | 25 ++ .../config/mybatis/MyBatisCustomLogger.java | 56 ++++ .../common/config/mybatis/MybatisConfig.java | 67 +++++ .../config/mybatis/TransactionConfig.java | 121 +++++++++ .../common/constants/LocalhostProject.java | 10 + .../context/ApplicationContextProvider.java | 51 ++++ .../company/localhost/common/dto/MapDto.java | 44 +++ .../common/exception/ErrorResponse.java | 29 ++ .../common/exception/ErrorResult.java | 92 +++++++ .../exception/GlobalExceptionHandler.java | 43 +++ .../common/exception/NotFoundHandler.java | 26 ++ .../common/exception/RestApiException.java | 12 + .../exception/code/CommonErrorCode.java | 21 ++ .../common/exception/code/ErrorCode.java | 15 ++ .../common/exception/code/UserErrorCode.java | 24 ++ .../common/filter/RequestCachingFilter.java | 47 ++++ .../localhost/common/filter/SampleFilter.java | 43 +++ .../common/filter/WebCorsFilter.java | 25 ++ .../RequestToMapArgumentResolver.java | 106 ++++++++ .../common/response/ApiResponse.java | 36 +++ .../details/MemberPrincipalDetails.java | 51 ++++ .../common/security/dsl/RestApiDsl.java | 84 ++++++ .../filter/RestAuthenticationFilter.java | 89 +++++++ .../handler/MemberAuthFailureHandler.java | 33 +++ .../handler/MemberAuthSuccessHandler.java | 56 ++++ .../handler/RestAccessDeniedHandler.java | 29 ++ .../RestAuthenticationEntryPointHandler.java | 32 +++ .../CustomDynamicAuthorizationManager.java | 86 ++++++ .../mapper/MapBasedUrlRoleMapper.java | 26 ++ .../mapper/PersistentUrlRoleMapper.java | 11 + .../common/security/mapper/UrlRoleMapper.java | 7 + .../provider/MemberAuthenticatorProvider.java | 48 ++++ .../service/CustomRememberMeServices.java | 119 +++++++++ .../service/DynamicAuthorizationService.java | 15 ++ .../service/MemberPrincipalDetailService.java | 36 +++ .../AuthenticationSessionControlStrategy.java | 48 ++++ .../session/CustomSessionRegistryImpl.java | 161 +++++++++++ .../token/RestAuthenticationToken.java | 36 +++ .../localhost/common/webEnum/WebEnum.java | 21 ++ .../wrapper/CachedBodyRequestWrapper.java | 132 +++++++++ .../common/wrapper/HTMLTagRequestWrapper.java | 58 ++++ .../common/wrapper/RequestMappingWrapper.java | 131 +++++++++ .../controller/common/TestController.java | 63 +++++ .../controller/common/UserController.java | 120 +++++++++ .../localhost/mapper/MemberMapper.java | 11 + .../company/localhost/mapper/TestMapper.java | 11 + .../localhost/service/TestService.java | 19 ++ .../io/company/localhost/utils/AuthUtil.java | 109 ++++++++ .../io/company/localhost/utils/CamelUtil.java | 68 +++++ .../company/localhost/utils/ContextUtil.java | 122 +++++++++ .../company/localhost/utils/ConvertUtil.java | 106 ++++++++ .../localhost/utils/ExceptionUtil.java | 50 ++++ .../company/localhost/utils/JacksonUtil.java | 207 ++++++++++++++ .../localhost/utils/SessionListener.java | 31 +++ .../company/localhost/utils/SessionUtil.java | 89 +++++++ .../io/company/localhost/utils/WebUtil.java | 144 ++++++++++ .../io/company/localhost/vo/MemberVo.java | 35 +++ src/main/resources/application.yml | 86 ++++++ src/main/resources/banner.txt | 13 + src/main/resources/datasource.yml | 14 + src/main/resources/log4jdbc.log4j2.properties | 7 + src/main/resources/mapper/memberMapper.xml | 24 ++ src/main/resources/mapper/testMapper.xml | 12 + src/main/resources/sql/MEMBER_TB.sql | 24 ++ src/main/resources/static/index.html | 12 + .../localhost/LocalhostApplicationTests.java | 13 + 86 files changed, 4602 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 build.gradle create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 src/main/java/io/company/localhost/LocalhostApplication.java create mode 100644 src/main/java/io/company/localhost/ServletInitializer.java create mode 100644 src/main/java/io/company/localhost/common/annotation/ParameterCheck.java create mode 100644 src/main/java/io/company/localhost/common/annotation/ReqMap.java create mode 100644 src/main/java/io/company/localhost/common/aop/ParameterAop.java create mode 100644 src/main/java/io/company/localhost/common/config/AuthConfig.java create mode 100644 src/main/java/io/company/localhost/common/config/ComponentScanConfig.java create mode 100644 src/main/java/io/company/localhost/common/config/JacksonCommonConfig.java create mode 100644 src/main/java/io/company/localhost/common/config/SecurityConfig.java create mode 100644 src/main/java/io/company/localhost/common/config/WebMvcConfig.java create mode 100644 src/main/java/io/company/localhost/common/config/mybatis/DataSourceConfig.java create mode 100644 src/main/java/io/company/localhost/common/config/mybatis/DataSourceProperties.java create mode 100644 src/main/java/io/company/localhost/common/config/mybatis/MyBatisCustomLogger.java create mode 100644 src/main/java/io/company/localhost/common/config/mybatis/MybatisConfig.java create mode 100644 src/main/java/io/company/localhost/common/config/mybatis/TransactionConfig.java create mode 100644 src/main/java/io/company/localhost/common/constants/LocalhostProject.java create mode 100644 src/main/java/io/company/localhost/common/context/ApplicationContextProvider.java create mode 100644 src/main/java/io/company/localhost/common/dto/MapDto.java create mode 100644 src/main/java/io/company/localhost/common/exception/ErrorResponse.java create mode 100644 src/main/java/io/company/localhost/common/exception/ErrorResult.java create mode 100644 src/main/java/io/company/localhost/common/exception/GlobalExceptionHandler.java create mode 100644 src/main/java/io/company/localhost/common/exception/NotFoundHandler.java create mode 100644 src/main/java/io/company/localhost/common/exception/RestApiException.java create mode 100644 src/main/java/io/company/localhost/common/exception/code/CommonErrorCode.java create mode 100644 src/main/java/io/company/localhost/common/exception/code/ErrorCode.java create mode 100644 src/main/java/io/company/localhost/common/exception/code/UserErrorCode.java create mode 100644 src/main/java/io/company/localhost/common/filter/RequestCachingFilter.java create mode 100644 src/main/java/io/company/localhost/common/filter/SampleFilter.java create mode 100644 src/main/java/io/company/localhost/common/filter/WebCorsFilter.java create mode 100644 src/main/java/io/company/localhost/common/resolver/RequestToMapArgumentResolver.java create mode 100644 src/main/java/io/company/localhost/common/response/ApiResponse.java create mode 100644 src/main/java/io/company/localhost/common/security/details/MemberPrincipalDetails.java create mode 100644 src/main/java/io/company/localhost/common/security/dsl/RestApiDsl.java create mode 100644 src/main/java/io/company/localhost/common/security/filter/RestAuthenticationFilter.java create mode 100644 src/main/java/io/company/localhost/common/security/handler/MemberAuthFailureHandler.java create mode 100644 src/main/java/io/company/localhost/common/security/handler/MemberAuthSuccessHandler.java create mode 100644 src/main/java/io/company/localhost/common/security/handler/RestAccessDeniedHandler.java create mode 100644 src/main/java/io/company/localhost/common/security/handler/RestAuthenticationEntryPointHandler.java create mode 100644 src/main/java/io/company/localhost/common/security/manager/CustomDynamicAuthorizationManager.java create mode 100644 src/main/java/io/company/localhost/common/security/mapper/MapBasedUrlRoleMapper.java create mode 100644 src/main/java/io/company/localhost/common/security/mapper/PersistentUrlRoleMapper.java create mode 100644 src/main/java/io/company/localhost/common/security/mapper/UrlRoleMapper.java create mode 100644 src/main/java/io/company/localhost/common/security/provider/MemberAuthenticatorProvider.java create mode 100644 src/main/java/io/company/localhost/common/security/service/CustomRememberMeServices.java create mode 100644 src/main/java/io/company/localhost/common/security/service/DynamicAuthorizationService.java create mode 100644 src/main/java/io/company/localhost/common/security/service/MemberPrincipalDetailService.java create mode 100644 src/main/java/io/company/localhost/common/security/session/AuthenticationSessionControlStrategy.java create mode 100644 src/main/java/io/company/localhost/common/security/session/CustomSessionRegistryImpl.java create mode 100644 src/main/java/io/company/localhost/common/security/token/RestAuthenticationToken.java create mode 100644 src/main/java/io/company/localhost/common/webEnum/WebEnum.java create mode 100644 src/main/java/io/company/localhost/common/wrapper/CachedBodyRequestWrapper.java create mode 100644 src/main/java/io/company/localhost/common/wrapper/HTMLTagRequestWrapper.java create mode 100644 src/main/java/io/company/localhost/common/wrapper/RequestMappingWrapper.java create mode 100644 src/main/java/io/company/localhost/controller/common/TestController.java create mode 100644 src/main/java/io/company/localhost/controller/common/UserController.java create mode 100644 src/main/java/io/company/localhost/mapper/MemberMapper.java create mode 100644 src/main/java/io/company/localhost/mapper/TestMapper.java create mode 100644 src/main/java/io/company/localhost/service/TestService.java create mode 100644 src/main/java/io/company/localhost/utils/AuthUtil.java create mode 100644 src/main/java/io/company/localhost/utils/CamelUtil.java create mode 100644 src/main/java/io/company/localhost/utils/ContextUtil.java create mode 100644 src/main/java/io/company/localhost/utils/ConvertUtil.java create mode 100644 src/main/java/io/company/localhost/utils/ExceptionUtil.java create mode 100644 src/main/java/io/company/localhost/utils/JacksonUtil.java create mode 100644 src/main/java/io/company/localhost/utils/SessionListener.java create mode 100644 src/main/java/io/company/localhost/utils/SessionUtil.java create mode 100644 src/main/java/io/company/localhost/utils/WebUtil.java create mode 100644 src/main/java/io/company/localhost/vo/MemberVo.java create mode 100644 src/main/resources/application.yml create mode 100644 src/main/resources/banner.txt create mode 100644 src/main/resources/datasource.yml create mode 100644 src/main/resources/log4jdbc.log4j2.properties create mode 100644 src/main/resources/mapper/memberMapper.xml create mode 100644 src/main/resources/mapper/testMapper.xml create mode 100644 src/main/resources/sql/MEMBER_TB.sql create mode 100644 src/main/resources/static/index.html create mode 100644 src/test/java/io/company/localhost/LocalhostApplicationTests.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8af972c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..9fffc13 --- /dev/null +++ b/build.gradle @@ -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() +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..dd16a6c --- /dev/null +++ b/gradle.properties @@ -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 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..a4b76b9530d66f5e68d973ea569d8e19de379189 GIT binary patch literal 43583 zcma&N1CXTcmMvW9vTb(Rwr$&4wr$(C?dmSu>@vG-+vuvg^_??!{yS%8zW-#zn-LkA z5&1^$^{lnmUON?}LBF8_K|(?T0Ra(xUH{($5eN!MR#ZihR#HxkUPe+_R8Cn`RRs(P z_^*#_XlXmGv7!4;*Y%p4nw?{bNp@UZHv1?Um8r6)Fei3p@ClJn0ECfg1hkeuUU@Or zDaPa;U3fE=3L}DooL;8f;P0ipPt0Z~9P0)lbStMS)ag54=uL9ia-Lm3nh|@(Y?B`; zx_#arJIpXH!U{fbCbI^17}6Ri*H<>OLR%c|^mh8+)*h~K8Z!9)DPf zR2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exgPZ2@&c~+hxRi1;}+)-06)!#Mq<6GhP z-Q?qmgo${aFBApb5p}$1OJKTClfi8%PpnczyVKkoHw7Ml9e7ikrF0d~UB}i3vizos zXW4DN$SiEV9{faLt5bHy2a>33K%7Td-n5C*N;f&ZqAg#2hIqEb(y<&f4u5BWJ>2^4 z414GosL=Aom#m&=x_v<0-fp1r%oVJ{T-(xnomNJ(Dryv zh?vj+%=II_nV+@NR+(!fZZVM&(W6{6%9cm+o+Z6}KqzLw{(>E86uA1`_K$HqINlb1 zKelh3-jr2I9V?ych`{hta9wQ2c9=MM`2cC{m6^MhlL2{DLv7C^j z$xXBCnDl_;l|bPGMX@*tV)B!c|4oZyftUlP*?$YU9C_eAsuVHJ58?)zpbr30P*C`T z7y#ao`uE-SOG(Pi+`$=e^mle~)pRrdwL5)N;o{gpW21of(QE#U6w%*C~`v-z0QqBML!!5EeYA5IQB0 z^l01c;L6E(iytN!LhL}wfwP7W9PNAkb+)Cst?qg#$n;z41O4&v+8-zPs+XNb-q zIeeBCh#ivnFLUCwfS;p{LC0O7tm+Sf9Jn)~b%uwP{%69;QC)Ok0t%*a5M+=;y8j=v z#!*pp$9@!x;UMIs4~hP#pnfVc!%-D<+wsG@R2+J&%73lK|2G!EQC)O05TCV=&3g)C!lT=czLpZ@Sa%TYuoE?v8T8`V;e$#Zf2_Nj6nvBgh1)2 GZ~q4|mN%#X literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e2847c8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -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 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..635d0b4 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'localhost' diff --git a/src/main/java/io/company/localhost/LocalhostApplication.java b/src/main/java/io/company/localhost/LocalhostApplication.java new file mode 100644 index 0000000..e1b29eb --- /dev/null +++ b/src/main/java/io/company/localhost/LocalhostApplication.java @@ -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); + } + +} diff --git a/src/main/java/io/company/localhost/ServletInitializer.java b/src/main/java/io/company/localhost/ServletInitializer.java new file mode 100644 index 0000000..afd871e --- /dev/null +++ b/src/main/java/io/company/localhost/ServletInitializer.java @@ -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); + } +} diff --git a/src/main/java/io/company/localhost/common/annotation/ParameterCheck.java b/src/main/java/io/company/localhost/common/annotation/ParameterCheck.java new file mode 100644 index 0000000..f61db98 --- /dev/null +++ b/src/main/java/io/company/localhost/common/annotation/ParameterCheck.java @@ -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 { +} + diff --git a/src/main/java/io/company/localhost/common/annotation/ReqMap.java b/src/main/java/io/company/localhost/common/annotation/ReqMap.java new file mode 100644 index 0000000..84255dd --- /dev/null +++ b/src/main/java/io/company/localhost/common/annotation/ReqMap.java @@ -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 { + +} diff --git a/src/main/java/io/company/localhost/common/aop/ParameterAop.java b/src/main/java/io/company/localhost/common/aop/ParameterAop.java new file mode 100644 index 0000000..eca8880 --- /dev/null +++ b/src/main/java/io/company/localhost/common/aop/ParameterAop.java @@ -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); + } +} diff --git a/src/main/java/io/company/localhost/common/config/AuthConfig.java b/src/main/java/io/company/localhost/common/config/AuthConfig.java new file mode 100644 index 0000000..4640c94 --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/AuthConfig.java @@ -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 encoders = new HashMap<>(); + encoders.put(encodingId, new BCryptPasswordEncoder()); + DelegatingPasswordEncoder delegatingPasswordEncoder = new DelegatingPasswordEncoder(encodingId, encoders); + delegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(new BCryptPasswordEncoder()); + + return delegatingPasswordEncoder; + } +} diff --git a/src/main/java/io/company/localhost/common/config/ComponentScanConfig.java b/src/main/java/io/company/localhost/common/config/ComponentScanConfig.java new file mode 100644 index 0000000..9e9ad79 --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/ComponentScanConfig.java @@ -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()); + } + +} diff --git a/src/main/java/io/company/localhost/common/config/JacksonCommonConfig.java b/src/main/java/io/company/localhost/common/config/JacksonCommonConfig.java new file mode 100644 index 0000000..bec2756 --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/JacksonCommonConfig.java @@ -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; + } + +} diff --git a/src/main/java/io/company/localhost/common/config/SecurityConfig.java b/src/main/java/io/company/localhost/common/config/SecurityConfig.java new file mode 100644 index 0000000..7b31b2b --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/SecurityConfig.java @@ -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 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(); // 커스텀 세션 레지스트리 구현체 사용 + } + + +} diff --git a/src/main/java/io/company/localhost/common/config/WebMvcConfig.java b/src/main/java/io/company/localhost/common/config/WebMvcConfig.java new file mode 100644 index 0000000..d132ce4 --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/WebMvcConfig.java @@ -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 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; + } +} diff --git a/src/main/java/io/company/localhost/common/config/mybatis/DataSourceConfig.java b/src/main/java/io/company/localhost/common/config/mybatis/DataSourceConfig.java new file mode 100644 index 0000000..1e098bc --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/mybatis/DataSourceConfig.java @@ -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()); + } +} diff --git a/src/main/java/io/company/localhost/common/config/mybatis/DataSourceProperties.java b/src/main/java/io/company/localhost/common/config/mybatis/DataSourceProperties.java new file mode 100644 index 0000000..209ec7b --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/mybatis/DataSourceProperties.java @@ -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); + } + +} diff --git a/src/main/java/io/company/localhost/common/config/mybatis/MyBatisCustomLogger.java b/src/main/java/io/company/localhost/common/config/mybatis/MyBatisCustomLogger.java new file mode 100644 index 0000000..4219c7b --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/mybatis/MyBatisCustomLogger.java @@ -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); + } +} diff --git a/src/main/java/io/company/localhost/common/config/mybatis/MybatisConfig.java b/src/main/java/io/company/localhost/common/config/mybatis/MybatisConfig.java new file mode 100644 index 0000000..e605d8a --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/mybatis/MybatisConfig.java @@ -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); + } +} diff --git a/src/main/java/io/company/localhost/common/config/mybatis/TransactionConfig.java b/src/main/java/io/company/localhost/common/config/mybatis/TransactionConfig.java new file mode 100644 index 0000000..0e563a9 --- /dev/null +++ b/src/main/java/io/company/localhost/common/config/mybatis/TransactionConfig.java @@ -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 rollbackRules = new ArrayList(); + 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"); + }; + } + +} diff --git a/src/main/java/io/company/localhost/common/constants/LocalhostProject.java b/src/main/java/io/company/localhost/common/constants/LocalhostProject.java new file mode 100644 index 0000000..36868c0 --- /dev/null +++ b/src/main/java/io/company/localhost/common/constants/LocalhostProject.java @@ -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() { + // + } +} diff --git a/src/main/java/io/company/localhost/common/context/ApplicationContextProvider.java b/src/main/java/io/company/localhost/common/context/ApplicationContextProvider.java new file mode 100644 index 0000000..486c8e3 --- /dev/null +++ b/src/main/java/io/company/localhost/common/context/ApplicationContextProvider.java @@ -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; + } + +} diff --git a/src/main/java/io/company/localhost/common/dto/MapDto.java b/src/main/java/io/company/localhost/common/dto/MapDto.java new file mode 100644 index 0000000..7a33c14 --- /dev/null +++ b/src/main/java/io/company/localhost/common/dto/MapDto.java @@ -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 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)); + } + +} diff --git a/src/main/java/io/company/localhost/common/exception/ErrorResponse.java b/src/main/java/io/company/localhost/common/exception/ErrorResponse.java new file mode 100644 index 0000000..166deee --- /dev/null +++ b/src/main/java/io/company/localhost/common/exception/ErrorResponse.java @@ -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 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(); + } + + } +} diff --git a/src/main/java/io/company/localhost/common/exception/ErrorResult.java b/src/main/java/io/company/localhost/common/exception/ErrorResult.java new file mode 100644 index 0000000..6eb3bb0 --- /dev/null +++ b/src/main/java/io/company/localhost/common/exception/ErrorResult.java @@ -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 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 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 handleExceptionInternal(BindException e, ErrorCode errorCode) { + // BindException에서 에러가 발생한 필드와 오류 메시지를 가져와서 처리 + return ResponseEntity.status(errorCode.getHttpStatus()) + .body(makeErrorResponse(e, errorCode)); + } + + private ErrorResponse makeErrorResponse(BindException e, ErrorCode errorCode) { + // 폼 바인딩 에러에서 발생한 필드 오류들을 가져와서 ErrorResponse로 변환 + List validationErrorList = e.getBindingResult() + .getFieldErrors() + .stream() + .map(ErrorResponse.ValidationError::of) + .collect(Collectors.toList()); + + return ErrorResponse.builder() + .code(errorCode.name()) + .message(errorCode.getMessage()) + .errors(validationErrorList) // 필드 오류 목록을 추가 + .build(); + } + */ +} diff --git a/src/main/java/io/company/localhost/common/exception/GlobalExceptionHandler.java b/src/main/java/io/company/localhost/common/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..58bbb47 --- /dev/null +++ b/src/main/java/io/company/localhost/common/exception/GlobalExceptionHandler.java @@ -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 handleCustomException(RestApiException e) { + ErrorCode errorCode = e.getErrorCode(); + return ErrorResult.handleExceptionInternal(errorCode); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgument(IllegalArgumentException e) { + log.warn("handleIllegalArgument", e); + ErrorCode errorCode = CommonErrorCode.INVALID_PARAMETER; + return ErrorResult.handleExceptionInternal(errorCode, e.getMessage()); + } + + + @ExceptionHandler({Exception.class}) + public ResponseEntity handleAllException(Exception ex) { + log.warn("handleAllException", ex); + ErrorCode errorCode = CommonErrorCode.INTERNAL_SERVER_ERROR; + return ErrorResult.handleExceptionInternal(errorCode); + } + + +} diff --git a/src/main/java/io/company/localhost/common/exception/NotFoundHandler.java b/src/main/java/io/company/localhost/common/exception/NotFoundHandler.java new file mode 100644 index 0000000..6cf08e4 --- /dev/null +++ b/src/main/java/io/company/localhost/common/exception/NotFoundHandler.java @@ -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 noHandlerFoundArgument(NoHandlerFoundException e) { + log.warn("NoHandlerFoundException", e); + ErrorCode errorCode = CommonErrorCode.RESOURCE_NOT_FOUND; + return ErrorResult.handleExceptionInternal(errorCode, errorCode.getMessage()); + } +} diff --git a/src/main/java/io/company/localhost/common/exception/RestApiException.java b/src/main/java/io/company/localhost/common/exception/RestApiException.java new file mode 100644 index 0000000..dbe8bc1 --- /dev/null +++ b/src/main/java/io/company/localhost/common/exception/RestApiException.java @@ -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; +} diff --git a/src/main/java/io/company/localhost/common/exception/code/CommonErrorCode.java b/src/main/java/io/company/localhost/common/exception/code/CommonErrorCode.java new file mode 100644 index 0000000..139d7ce --- /dev/null +++ b/src/main/java/io/company/localhost/common/exception/code/CommonErrorCode.java @@ -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; + +} diff --git a/src/main/java/io/company/localhost/common/exception/code/ErrorCode.java b/src/main/java/io/company/localhost/common/exception/code/ErrorCode.java new file mode 100644 index 0000000..5aa6441 --- /dev/null +++ b/src/main/java/io/company/localhost/common/exception/code/ErrorCode.java @@ -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(); + +} diff --git a/src/main/java/io/company/localhost/common/exception/code/UserErrorCode.java b/src/main/java/io/company/localhost/common/exception/code/UserErrorCode.java new file mode 100644 index 0000000..fe59260 --- /dev/null +++ b/src/main/java/io/company/localhost/common/exception/code/UserErrorCode.java @@ -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()); + } +} diff --git a/src/main/java/io/company/localhost/common/filter/RequestCachingFilter.java b/src/main/java/io/company/localhost/common/filter/RequestCachingFilter.java new file mode 100644 index 0000000..d4eeab4 --- /dev/null +++ b/src/main/java/io/company/localhost/common/filter/RequestCachingFilter.java @@ -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() { + // 필터 종료 (필요한 경우) + } +} diff --git a/src/main/java/io/company/localhost/common/filter/SampleFilter.java b/src/main/java/io/company/localhost/common/filter/SampleFilter.java new file mode 100644 index 0000000..32b4c67 --- /dev/null +++ b/src/main/java/io/company/localhost/common/filter/SampleFilter.java @@ -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 어노테이션이 있으면 직렬화하지 않음(아무것도 하지 않음) + } +} diff --git a/src/main/java/io/company/localhost/common/filter/WebCorsFilter.java b/src/main/java/io/company/localhost/common/filter/WebCorsFilter.java new file mode 100644 index 0000000..288a71c --- /dev/null +++ b/src/main/java/io/company/localhost/common/filter/WebCorsFilter.java @@ -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); + } +} diff --git a/src/main/java/io/company/localhost/common/resolver/RequestToMapArgumentResolver.java b/src/main/java/io/company/localhost/common/resolver/RequestToMapArgumentResolver.java new file mode 100644 index 0000000..448e50d --- /dev/null +++ b/src/main/java/io/company/localhost/common/resolver/RequestToMapArgumentResolver.java @@ -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 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 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 반환 + } + } + +} diff --git a/src/main/java/io/company/localhost/common/response/ApiResponse.java b/src/main/java/io/company/localhost/common/response/ApiResponse.java new file mode 100644 index 0000000..b7ec0d2 --- /dev/null +++ b/src/main/java/io/company/localhost/common/response/ApiResponse.java @@ -0,0 +1,36 @@ +package io.company.localhost.common.response; + +import org.springframework.http.HttpStatus; + +import lombok.Getter; + +@Getter +public class ApiResponse { + 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 ApiResponse of(HttpStatus status, String message, T data) { + return new ApiResponse<>(status, message, data); + } + + public static ApiResponse of(HttpStatus status, T data) { + return ApiResponse.of(status, status.name(), data); + } + + public static ApiResponse ok(T data) { + return ApiResponse.of(HttpStatus.OK, HttpStatus.OK.name(), data); + } + + public static ApiResponse error(HttpStatus status, String message) { + return new ApiResponse<>(status, message, null); + } +} \ No newline at end of file diff --git a/src/main/java/io/company/localhost/common/security/details/MemberPrincipalDetails.java b/src/main/java/io/company/localhost/common/security/details/MemberPrincipalDetails.java new file mode 100644 index 0000000..f0aedbb --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/details/MemberPrincipalDetails.java @@ -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 getAuthorities() { + List 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; + } +} diff --git a/src/main/java/io/company/localhost/common/security/dsl/RestApiDsl.java b/src/main/java/io/company/localhost/common/security/dsl/RestApiDsl.java new file mode 100644 index 0000000..4d2de67 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/dsl/RestApiDsl.java @@ -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 > extends + AbstractAuthenticationFilterConfigurer, 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 loginSuccessHandler(AuthenticationSuccessHandler successHandler) { + this.successHandler = successHandler; + return this; + } + + // 로그인 실패 핸들러를 설정 + public RestApiDsl loginFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) { + this.failureHandler = authenticationFailureHandler; + return this; + } + + // 로그인 처리 URL을 설정 + public RestApiDsl loginProcessingUrl(String loginPage) { + return super.loginProcessingUrl(loginPage); + } + + // 로그인 처리 URL을 위한 RequestMatcher를 생성 + @Override + protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) { + return new AntPathRequestMatcher(loginProcessingUrl, HttpMethod.POST.name()); + } +} diff --git a/src/main/java/io/company/localhost/common/security/filter/RestAuthenticationFilter.java b/src/main/java/io/company/localhost/common/security/filter/RestAuthenticationFilter.java new file mode 100644 index 0000000..0d941b1 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/filter/RestAuthenticationFilter.java @@ -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); + } + } +} diff --git a/src/main/java/io/company/localhost/common/security/handler/MemberAuthFailureHandler.java b/src/main/java/io/company/localhost/common/security/handler/MemberAuthFailureHandler.java new file mode 100644 index 0000000..8d9061e --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/handler/MemberAuthFailureHandler.java @@ -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(), "인증 실패"); + } +} diff --git a/src/main/java/io/company/localhost/common/security/handler/MemberAuthSuccessHandler.java b/src/main/java/io/company/localhost/common/security/handler/MemberAuthSuccessHandler.java new file mode 100644 index 0000000..e29be16 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/handler/MemberAuthSuccessHandler.java @@ -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); + } +} diff --git a/src/main/java/io/company/localhost/common/security/handler/RestAccessDeniedHandler.java b/src/main/java/io/company/localhost/common/security/handler/RestAccessDeniedHandler.java new file mode 100644 index 0000000..e2cdc2d --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/handler/RestAccessDeniedHandler.java @@ -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())); + } +} diff --git a/src/main/java/io/company/localhost/common/security/handler/RestAuthenticationEntryPointHandler.java b/src/main/java/io/company/localhost/common/security/handler/RestAuthenticationEntryPointHandler.java new file mode 100644 index 0000000..2a24a99 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/handler/RestAuthenticationEntryPointHandler.java @@ -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())); + } +} diff --git a/src/main/java/io/company/localhost/common/security/manager/CustomDynamicAuthorizationManager.java b/src/main/java/io/company/localhost/common/security/manager/CustomDynamicAuthorizationManager.java new file mode 100644 index 0000000..d4c3222 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/manager/CustomDynamicAuthorizationManager.java @@ -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 { + List>> 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, RequestAuthorizationContext object) { + for (RequestMatcherEntry> mapping : this.mappings) { + + RequestMatcher matcher = mapping.getRequestMatcher(); + RequestMatcher.MatchResult matchResult = matcher.matcher(object.getRequest()); + + if (matchResult.isMatch()) { + AuthorizationManager manager = mapping.getEntry(); + return manager.authorize(authentication, + new RequestAuthorizationContext(object.getRequest(), matchResult.getVariables())); + } + } + return DENY; + } + + // 역할에 맞는 AuthorizationManager 반환 + private AuthorizationManager customAuthorizationManager(String role) { + if (role.startsWith("ROLE")) { + return AuthorityAuthorizationManager.hasAuthority(role); + }else{ + return new WebExpressionAuthorizationManager(role); + } + } + + @Override + public void verify(Supplier authentication, RequestAuthorizationContext object) { + AuthorizationManager.super.verify(authentication, object); + } + + + //deprecated 됬는디 값 안 넣으면 세팅이 안 됨 + @Deprecated + @Invoke + @Override + public AuthorizationDecision check(Supplier authentication, RequestAuthorizationContext object) { + return (AuthorizationDecision)authorize(authentication,object); + } + + +} diff --git a/src/main/java/io/company/localhost/common/security/mapper/MapBasedUrlRoleMapper.java b/src/main/java/io/company/localhost/common/security/mapper/MapBasedUrlRoleMapper.java new file mode 100644 index 0000000..91f7f10 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/mapper/MapBasedUrlRoleMapper.java @@ -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 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 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); + } +} \ No newline at end of file diff --git a/src/main/java/io/company/localhost/common/security/mapper/PersistentUrlRoleMapper.java b/src/main/java/io/company/localhost/common/security/mapper/PersistentUrlRoleMapper.java new file mode 100644 index 0000000..66893da --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/mapper/PersistentUrlRoleMapper.java @@ -0,0 +1,11 @@ +package io.company.localhost.common.security.mapper; + +import java.util.Map; + +//DB 정보로 권한 요청 할거면 여기서 설정하자 +public class PersistentUrlRoleMapper implements UrlRoleMapper{ + @Override + public Map getUrlRoleMappings() { + return null; + } +} diff --git a/src/main/java/io/company/localhost/common/security/mapper/UrlRoleMapper.java b/src/main/java/io/company/localhost/common/security/mapper/UrlRoleMapper.java new file mode 100644 index 0000000..c54e88c --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/mapper/UrlRoleMapper.java @@ -0,0 +1,7 @@ +package io.company.localhost.common.security.mapper; + +import java.util.Map; + +public interface UrlRoleMapper { + Map getUrlRoleMappings(); +} diff --git a/src/main/java/io/company/localhost/common/security/provider/MemberAuthenticatorProvider.java b/src/main/java/io/company/localhost/common/security/provider/MemberAuthenticatorProvider.java new file mode 100644 index 0000000..a8959a7 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/provider/MemberAuthenticatorProvider.java @@ -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); + } +} diff --git a/src/main/java/io/company/localhost/common/security/service/CustomRememberMeServices.java b/src/main/java/io/company/localhost/common/security/service/CustomRememberMeServices.java new file mode 100644 index 0000000..040784c --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/service/CustomRememberMeServices.java @@ -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; + } +} diff --git a/src/main/java/io/company/localhost/common/security/service/DynamicAuthorizationService.java b/src/main/java/io/company/localhost/common/security/service/DynamicAuthorizationService.java new file mode 100644 index 0000000..27d286d --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/service/DynamicAuthorizationService.java @@ -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 getUrlRoleMappings() { + return delegate.getUrlRoleMappings(); + } +} diff --git a/src/main/java/io/company/localhost/common/security/service/MemberPrincipalDetailService.java b/src/main/java/io/company/localhost/common/security/service/MemberPrincipalDetailService.java new file mode 100644 index 0000000..fc9926e --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/service/MemberPrincipalDetailService.java @@ -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); + } +} diff --git a/src/main/java/io/company/localhost/common/security/session/AuthenticationSessionControlStrategy.java b/src/main/java/io/company/localhost/common/security/session/AuthenticationSessionControlStrategy.java new file mode 100644 index 0000000..faf1df7 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/session/AuthenticationSessionControlStrategy.java @@ -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 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(); + } + } + +} diff --git a/src/main/java/io/company/localhost/common/security/session/CustomSessionRegistryImpl.java b/src/main/java/io/company/localhost/common/security/session/CustomSessionRegistryImpl.java new file mode 100644 index 0000000..1204f7e --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/session/CustomSessionRegistryImpl.java @@ -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 { + + private final Map> principals; + + private final Map 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 getAllPrincipals() { + return new ArrayList<>(principals.keySet()); + } + + // 특정 principal의 모든 세션 정보를 반환하는 메소드 + @Override + public List getAllSessions(Object principal, boolean includeExpiredSessions) { + String loginId = getLoginId(principal); + + final List sessionsUsedByPrincipal = principals.get(loginId); + if (sessionsUsedByPrincipal == null) { + return Collections.emptyList(); + } + + List 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 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 sessionListById = principals.get(info.getPrincipal()); + sessionListById.remove(sessionId); + + if (sessionListById.isEmpty()) { + sessionListById = null; + } + + // log.debug("remove {}", principals); + } + +} diff --git a/src/main/java/io/company/localhost/common/security/token/RestAuthenticationToken.java b/src/main/java/io/company/localhost/common/security/token/RestAuthenticationToken.java new file mode 100644 index 0000000..cfb00a3 --- /dev/null +++ b/src/main/java/io/company/localhost/common/security/token/RestAuthenticationToken.java @@ -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 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; + } +} diff --git a/src/main/java/io/company/localhost/common/webEnum/WebEnum.java b/src/main/java/io/company/localhost/common/webEnum/WebEnum.java new file mode 100644 index 0000000..491db73 --- /dev/null +++ b/src/main/java/io/company/localhost/common/webEnum/WebEnum.java @@ -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; + } + +} diff --git a/src/main/java/io/company/localhost/common/wrapper/CachedBodyRequestWrapper.java b/src/main/java/io/company/localhost/common/wrapper/CachedBodyRequestWrapper.java new file mode 100644 index 0000000..8fafbeb --- /dev/null +++ b/src/main/java/io/company/localhost/common/wrapper/CachedBodyRequestWrapper.java @@ -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>>() { + }); + } else { // Map + bodyObject = JacksonUtil.fromJson(requestBody, new TypeReference>() { + }); + } + + + 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(); + } + + } + +} diff --git a/src/main/java/io/company/localhost/common/wrapper/HTMLTagRequestWrapper.java b/src/main/java/io/company/localhost/common/wrapper/HTMLTagRequestWrapper.java new file mode 100644 index 0000000..ef1e5a5 --- /dev/null +++ b/src/main/java/io/company/localhost/common/wrapper/HTMLTagRequestWrapper.java @@ -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 getParameterMap() { + Map 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 */ + +} diff --git a/src/main/java/io/company/localhost/common/wrapper/RequestMappingWrapper.java b/src/main/java/io/company/localhost/common/wrapper/RequestMappingWrapper.java new file mode 100644 index 0000000..a4b580f --- /dev/null +++ b/src/main/java/io/company/localhost/common/wrapper/RequestMappingWrapper.java @@ -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 + * @return Annotation + */ + public T getAnnotation(HttpServletRequest request, Class 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 getAnnotation(HandlerMethod handlerMethod, Class annotationType) { + if (Objects.nonNull(handlerMethod)) { + Annotation methodAnnotation = handlerMethod.getMethodAnnotation(annotationType); + + return (T) methodAnnotation; + } + + return null; + } + + /** + * controller method 특정 annotation 선언 여부 + * @param HttpServletRequest + * @param Class[] + * @return boolean + */ + @SuppressWarnings("unchecked") + public boolean hasAnyAnnotation(HttpServletRequest request, Class... 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 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 boolean hasAnyAnnotation(HandlerMethod handlerMethod, Class... annotationTypes) { + if (Objects.nonNull(handlerMethod)) { + for (Class anno : annotationTypes) { + A methodAnnotation = handlerMethod.getMethodAnnotation(anno); + + if (Objects.nonNull(methodAnnotation)) { + return true; + } + } + } + + return false; + } + +} diff --git a/src/main/java/io/company/localhost/controller/common/TestController.java b/src/main/java/io/company/localhost/controller/common/TestController.java new file mode 100644 index 0000000..ab1c4a7 --- /dev/null +++ b/src/main/java/io/company/localhost/controller/common/TestController.java @@ -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 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"); + } + +} diff --git a/src/main/java/io/company/localhost/controller/common/UserController.java b/src/main/java/io/company/localhost/controller/common/UserController.java new file mode 100644 index 0000000..7bb3bf8 --- /dev/null +++ b/src/main/java/io/company/localhost/controller/common/UserController.java @@ -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 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 sessions = SessionListener.getSessions(); + Map sessionData = new HashMap<>(); + + for (Map.Entry 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 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); + } + + +} diff --git a/src/main/java/io/company/localhost/mapper/MemberMapper.java b/src/main/java/io/company/localhost/mapper/MemberMapper.java new file mode 100644 index 0000000..ca9c02b --- /dev/null +++ b/src/main/java/io/company/localhost/mapper/MemberMapper.java @@ -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); +} diff --git a/src/main/java/io/company/localhost/mapper/TestMapper.java b/src/main/java/io/company/localhost/mapper/TestMapper.java new file mode 100644 index 0000000..a6dd455 --- /dev/null +++ b/src/main/java/io/company/localhost/mapper/TestMapper.java @@ -0,0 +1,11 @@ +package io.company.localhost.mapper; + +import java.util.List; + +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface TestMapper { + + List getCong(); +} diff --git a/src/main/java/io/company/localhost/service/TestService.java b/src/main/java/io/company/localhost/service/TestService.java new file mode 100644 index 0000000..d0cca17 --- /dev/null +++ b/src/main/java/io/company/localhost/service/TestService.java @@ -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 getCong(){ + return testMapper.getCong(); + } +} diff --git a/src/main/java/io/company/localhost/utils/AuthUtil.java b/src/main/java/io/company/localhost/utils/AuthUtil.java new file mode 100644 index 0000000..a5fa7bc --- /dev/null +++ b/src/main/java/io/company/localhost/utils/AuthUtil.java @@ -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 authorities = authentication.getAuthorities(); + // log.debug("authorities {}", authorities); + return authorities.contains(new SimpleGrantedAuthority(role)); + } + +} diff --git a/src/main/java/io/company/localhost/utils/CamelUtil.java b/src/main/java/io/company/localhost/utils/CamelUtil.java new file mode 100644 index 0000000..9a73543 --- /dev/null +++ b/src/main/java/io/company/localhost/utils/CamelUtil.java @@ -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; + } + +} diff --git a/src/main/java/io/company/localhost/utils/ContextUtil.java b/src/main/java/io/company/localhost/utils/ContextUtil.java new file mode 100644 index 0000000..a6649b4 --- /dev/null +++ b/src/main/java/io/company/localhost/utils/ContextUtil.java @@ -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 getBean(Class 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 getBean(String beanName, Class 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); + } + +} diff --git a/src/main/java/io/company/localhost/utils/ConvertUtil.java b/src/main/java/io/company/localhost/utils/ConvertUtil.java new file mode 100644 index 0000000..0e26e5b --- /dev/null +++ b/src/main/java/io/company/localhost/utils/ConvertUtil.java @@ -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 convertToMap(Object obj) { + try { + if (Objects.isNull(obj)) { + return Collections.emptyMap(); + } + Map 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 convertToValueObject(Map map, Class 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 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 -> List + public static List> convertToMaps(List list) { + if (list == null || list.isEmpty()) { + return Collections.emptyList(); + } + return list.stream() + .map(ConvertUtil::convertToMap) + .collect(Collectors.toList()); + } + + //List -> List + public static List convertToValueObjects(List> list, Class type) { + if (list == null || list.isEmpty()) { + return Collections.emptyList(); + } + List convertList = new ArrayList<>(list.size()); + + for (Map 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; + }; + } +} diff --git a/src/main/java/io/company/localhost/utils/ExceptionUtil.java b/src/main/java/io/company/localhost/utils/ExceptionUtil.java new file mode 100644 index 0000000..0adfb6e --- /dev/null +++ b/src/main/java/io/company/localhost/utils/ExceptionUtil.java @@ -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); + } + +} diff --git a/src/main/java/io/company/localhost/utils/JacksonUtil.java b/src/main/java/io/company/localhost/utils/JacksonUtil.java new file mode 100644 index 0000000..55223f7 --- /dev/null +++ b/src/main/java/io/company/localhost/utils/JacksonUtil.java @@ -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 fromJson(String jsonString, Class 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 - ex) new TypeReference>() {} + * @return T + */ + public static T fromJson(String jsonString, TypeReference 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 + * + * @paramjsonString + * @param targetType + * @return List + */ + public static List listFromJson(String jsonString, Class 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 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 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 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 toMap(Object source) { + return to(source, Map.class); + } + + public static T to(Object source, Class targetType) { + if (Objects.isNull(source)) { + return null; + } + + ObjectMapper objectMapper = jacksonMapper(); + + return objectMapper.convertValue(source, targetType); + } + + public static T to(Object source, TypeReference targetType) { + String jsonStr = toJson(source); + + return fromJson(jsonStr, targetType); + } + + public static List toList(Object source, Class targetType) { + String jsonStr = toJson(source); + + return listFromJson(jsonStr, targetType); + } + +} diff --git a/src/main/java/io/company/localhost/utils/SessionListener.java b/src/main/java/io/company/localhost/utils/SessionListener.java new file mode 100644 index 0000000..91d10d3 --- /dev/null +++ b/src/main/java/io/company/localhost/utils/SessionListener.java @@ -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 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()); + } +} \ No newline at end of file diff --git a/src/main/java/io/company/localhost/utils/SessionUtil.java b/src/main/java/io/company/localhost/utils/SessionUtil.java new file mode 100644 index 0000000..615cb83 --- /dev/null +++ b/src/main/java/io/company/localhost/utils/SessionUtil.java @@ -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 getAttribute(String name, Class 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; + } + +} diff --git a/src/main/java/io/company/localhost/utils/WebUtil.java b/src/main/java/io/company/localhost/utils/WebUtil.java new file mode 100644 index 0000000..c7de030 --- /dev/null +++ b/src/main/java/io/company/localhost/utils/WebUtil.java @@ -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 + * @return Annotation + */ + public static T getAnnotation(HttpServletRequest request, Class annotationType) { + RequestMappingWrapper wrapper = ContextUtil.getBean(RequestMappingWrapper.class); + + return wrapper.getAnnotation(request, annotationType); + } + + public static T getAnnotation(HandlerMethod handlerMethod, Class annotationType) { + RequestMappingWrapper wrapper = ContextUtil.getBean(RequestMappingWrapper.class); + + return wrapper.getAnnotation(handlerMethod, annotationType); + } + + /** + * controller method annotation 있는지 여부 + * + * @param HttpServletRequest + * @param Class + * @return boolean + */ + @SuppressWarnings("unchecked") + public static boolean hasAnyAnnotation(HttpServletRequest request, + Class... annotationTypes) { + RequestMappingWrapper wrapper = ContextUtil.getBean(RequestMappingWrapper.class); + + return wrapper.hasAnyAnnotation(request, annotationTypes); + } + + @SuppressWarnings("unchecked") + public static boolean hasAnyAnnotation(HandlerMethod handlerMethod, + Class... 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 pathVariables = (Map) request + .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); + + if (pathVariables == null) { + return null; + } + return pathVariables.get(pathVariableName); + } +} diff --git a/src/main/java/io/company/localhost/vo/MemberVo.java b/src/main/java/io/company/localhost/vo/MemberVo.java new file mode 100644 index 0000000..f09315b --- /dev/null +++ b/src/main/java/io/company/localhost/vo/MemberVo.java @@ -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; +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..77d22c4 --- /dev/null +++ b/src/main/resources/application.yml @@ -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 + diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 0000000..c834d17 --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,13 @@ + ___ ________ ________ ________ ___ ___ ___ ________ ________ _________ +|\ \ |\ __ \|\ ____\|\ __ \|\ \ |\ \|\ \|\ __ \|\ ____\|\___ ___\ +\ \ \ \ \ \|\ \ \ \___|\ \ \|\ \ \ \ \ \ \\\ \ \ \|\ \ \ \___|\|___ \ \_| + \ \ \ \ \ \\\ \ \ \ \ \ __ \ \ \ \ \ __ \ \ \\\ \ \_____ \ \ \ \ + \ \ \____\ \ \\\ \ \ \____\ \ \ \ \ \ \____\ \ \ \ \ \ \\\ \|____|\ \ \ \ \ + \ \_______\ \_______\ \_______\ \__\ \__\ \_______\ \__\ \__\ \_______\____\_\ \ \ \__\ + \|_______|\|_______|\|_______|\|__|\|__|\|_______|\|__|\|__|\|_______|\_________\ \|__| + \|_________| + + + +Spring Boot Version : ${spring-boot.version} +Spring Boot Formatted Version : ${spring-boot.formatted-version} \ No newline at end of file diff --git a/src/main/resources/datasource.yml b/src/main/resources/datasource.yml new file mode 100644 index 0000000..3c3dde6 --- /dev/null +++ b/src/main/resources/datasource.yml @@ -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 + diff --git a/src/main/resources/log4jdbc.log4j2.properties b/src/main/resources/log4jdbc.log4j2.properties new file mode 100644 index 0000000..41f2210 --- /dev/null +++ b/src/main/resources/log4jdbc.log4j2.properties @@ -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 diff --git a/src/main/resources/mapper/memberMapper.xml b/src/main/resources/mapper/memberMapper.xml new file mode 100644 index 0000000..6113de9 --- /dev/null +++ b/src/main/resources/mapper/memberMapper.xml @@ -0,0 +1,24 @@ + + + + + + + diff --git a/src/main/resources/mapper/testMapper.xml b/src/main/resources/mapper/testMapper.xml new file mode 100644 index 0000000..94073ae --- /dev/null +++ b/src/main/resources/mapper/testMapper.xml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/src/main/resources/sql/MEMBER_TB.sql b/src/main/resources/sql/MEMBER_TB.sql new file mode 100644 index 0000000..164f76f --- /dev/null +++ b/src/main/resources/sql/MEMBER_TB.sql @@ -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', ''); diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html new file mode 100644 index 0000000..d197325 --- /dev/null +++ b/src/main/resources/static/index.html @@ -0,0 +1,12 @@ + + + + + Title + + + +localhost bo test page + + + \ No newline at end of file diff --git a/src/test/java/io/company/localhost/LocalhostApplicationTests.java b/src/test/java/io/company/localhost/LocalhostApplicationTests.java new file mode 100644 index 0000000..e228118 --- /dev/null +++ b/src/test/java/io/company/localhost/LocalhostApplicationTests.java @@ -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() { + } + +}