This commit is contained in:
Hyojin Ahn 2025-12-17 09:30:03 -05:00
commit 5a22c38ee7
38 changed files with 2660 additions and 0 deletions

33
.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

2
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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
http://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.

34
README.md Normal file
View File

@ -0,0 +1,34 @@
# Spring Boot 3.0 Security with JWT Implementation
This project demonstrates the implementation of security using Spring Boot 3.0 and JSON Web Tokens (JWT). It includes the following features:
## Features
* User registration and login with JWT authentication
* Password encryption using BCrypt
* Role-based authorization with Spring Security
* Customized access denied handling
* Logout mechanism
* Refresh token
## Technologies
* Spring Boot 3.0
* Spring Security
* JSON Web Tokens (JWT)
* BCrypt
* Maven
## Getting Started
To get started with this project, you will need to have the following installed on your local machine:
* JDK 17+
* Maven 3+
To build and run the project, follow these steps:
* Clone the repository: `git clone https://github.com/ali-bouali/spring-boot-3-jwt-security.git`
* Navigate to the project directory: cd spring-boot-security-jwt
* Add database "jwt_security" to postgres
* Build the project: mvn clean install
* Run the project: mvn spring-boot:run
-> The application will be available at http://localhost:8080.

38
docker-compose.yml Normal file
View File

@ -0,0 +1,38 @@
services:
postgres:
container_name: postgres-sql
image: postgres
environment:
POSTGRES_USER: username
POSTGRES_PASSWORD: password
PGDATA: /data/postgres
volumes:
- postgres:/data/postgres
ports:
- "5432:5432"
networks:
- postgres
restart: unless-stopped
pgadmin:
container_name: pgadmin
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
PGADMIN_CONFIG_SERVER_MODE: 'False'
volumes:
- pgadmin:/var/lib/pgadmin
ports:
- "5050:80"
networks:
- postgres
restart: unless-stopped
networks:
postgres:
driver: bridge
volumes:
postgres:
pgadmin:

316
mvnw vendored Normal file
View File

@ -0,0 +1,316 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`\\unset -f command; \\command -v java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

188
mvnw.cmd vendored Normal file
View File

@ -0,0 +1,188 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. 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,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%

102
pom.xml Normal file
View File

@ -0,0 +1,102 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.goi</groupId>
<artifactId>opr-rest-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Operation</name>
<description>Operation REST Api</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>template</groupId>
<artifactId>layered-architecture-template</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,18 @@
package com.goi.erp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication(scanBasePackages = {"com.goi.erp"})
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
@EntityScan(basePackages = {"com.goi.erp.entity"})
@EnableJpaRepositories(basePackages = {"com.goi.erp.repository"})
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}

View File

@ -0,0 +1,62 @@
package com.goi.erp.common.exception;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<?> handleRuntimeException(RuntimeException ex) {
Map<String, Object> body = new HashMap<>();
body.put("error", ex.getMessage());
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.BAD_REQUEST.value());
return ResponseEntity.badRequest().body(body);
}
// 모든 예외 처리
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleAllExceptions(Exception ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
body.put("error", "Internal Server Error");
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
// 권한 없음
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<Map<String, Object>> handleAccessDenied(AccessDeniedException ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.FORBIDDEN.value());
body.put("error", "Forbidden");
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.FORBIDDEN);
}
//
@ExceptionHandler(JwtExpiredException.class)
public ResponseEntity<Map<String, String>> handleJwtExpired(JwtExpiredException ex) {
Map<String, String> body = Map.of("error", "JWT expired", "message", ex.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
}
@ExceptionHandler(JwtInvalidException.class)
public ResponseEntity<Map<String, String>> handleJwtInvalid(JwtInvalidException ex) {
Map<String, String> body = Map.of("error", "Invalid JWT", "message", ex.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
}
}

View File

@ -0,0 +1,27 @@
package com.goi.erp.common.exception;
public class JwtExpiredException extends RuntimeException {
private static final long serialVersionUID = 1L;
public JwtExpiredException() {
super();
}
public JwtExpiredException(String message) {
super(message);
}
public JwtExpiredException(String message, Throwable cause) {
super(message, cause);
}
public JwtExpiredException(Throwable cause) {
super(cause);
}
protected JwtExpiredException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -0,0 +1,27 @@
package com.goi.erp.common.exception;
public class JwtInvalidException extends RuntimeException {
private static final long serialVersionUID = 1L;
public JwtInvalidException() {
super();
}
public JwtInvalidException(String message) {
super(message);
}
public JwtInvalidException(String message, Throwable cause) {
super(message, cause);
}
public JwtInvalidException(Throwable cause) {
super(cause);
}
protected JwtInvalidException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -0,0 +1,18 @@
package com.goi.erp.common.permission;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class Permission {
private PermissionEnums.Module module;
private PermissionEnums.Action action;
private PermissionEnums.Scope scope;
private final boolean all;
public boolean isAll() {
return all || module == PermissionEnums.Module.ALL;
}
}

View File

@ -0,0 +1,36 @@
package com.goi.erp.common.permission;
public class PermissionChecker {
public static boolean canCreateOPR(PermissionSet set) {
if (set.hasAll()) return true;
return set.has(PermissionEnums.Module.O, PermissionEnums.Action.C);
}
public static boolean canReadOPR(PermissionSet set) {
if (set.hasAll()) return true;
return set.has(PermissionEnums.Module.O, PermissionEnums.Action.R);
}
public static boolean canUpdateOPR(PermissionSet set) {
if (set.hasAll()) return true;
return set.has(PermissionEnums.Module.O, PermissionEnums.Action.U);
}
public static boolean canDeleteOPR(PermissionSet set) {
if (set.hasAll()) return true;
return set.has(PermissionEnums.Module.O, PermissionEnums.Action.D);
}
// 범위까지 체크
public static boolean canReadOPRAll(PermissionSet set) {
if (set.hasAll()) return true;
return set.hasFull(
PermissionEnums.Module.O,
PermissionEnums.Action.R,
PermissionEnums.Scope.A
);
}
}

View File

@ -0,0 +1,22 @@
package com.goi.erp.common.permission;
public class PermissionEnums {
public enum Module {
H, // HCM
C, // CRM
A, // ACC
O, // OPERATION
S, // SYSTEM
ALL // ADMIN
}
public enum Action {
C, R, U, D
}
public enum Scope {
S, P, A
}
}

View File

@ -0,0 +1,32 @@
package com.goi.erp.common.permission;
import java.util.ArrayList;
import java.util.List;
public class PermissionParser {
public static PermissionSet parse(List<String> permissionStrings) {
List<Permission> list = new ArrayList<>();
for (String str : permissionStrings) {
// ALL 권한 추가
if ("ALL".equalsIgnoreCase(str)) {
list.add(new Permission(PermissionEnums.Module.ALL, null, null, true));
continue;
}
// 문자 세개 조합 인지 확인
String[] parts = str.split(":");
if (parts.length != 3) continue;
PermissionEnums.Module module = PermissionEnums.Module.valueOf(parts[0]);
PermissionEnums.Action action = PermissionEnums.Action.valueOf(parts[1]);
PermissionEnums.Scope scope = PermissionEnums.Scope.valueOf(parts[2]);
//
list.add(new Permission(module, action, scope, false));
}
return new PermissionSet(list);
}
}

View File

@ -0,0 +1,26 @@
package com.goi.erp.common.permission;
import java.util.List;
public record PermissionSet(List<Permission> permissions) {
public boolean has(PermissionEnums.Module module,
PermissionEnums.Action action) {
return permissions.stream()
.anyMatch(p -> p.getModule() == module &&
p.getAction() == action);
}
public boolean hasFull(PermissionEnums.Module module,
PermissionEnums.Action action,
PermissionEnums.Scope scope) {
return permissions.stream()
.anyMatch(p -> p.getModule() == module &&
p.getAction() == action &&
p.getScope().ordinal() >= scope.ordinal());
}
public boolean hasAll() {
return permissions.stream().anyMatch(p -> p.isAll());
}
}

View File

@ -0,0 +1,21 @@
package com.goi.erp.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import com.goi.erp.token.ApplicationAuditAware;
@Configuration
public class ApplicationConfig {
@Value("${application.security.jwt.secret-key}")
private String jwtSecret;
@Bean
public AuditorAware<String> auditorAware() {
return new ApplicationAuditAware(jwtSecret);
}
}

View File

@ -0,0 +1,98 @@
package com.goi.erp.config;
import com.goi.erp.common.permission.PermissionSet;
import com.goi.erp.token.JwtService;
import com.goi.erp.token.PermissionAuthenticationToken;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
@Override
protected void doFilterInternal(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain
) throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
final String jwt = authHeader.substring(7);
try {
// 기존 인증 정보 확인
var authentication = SecurityContextHolder.getContext().getAuthentication();
boolean needsAuthentication = true;
if (authentication instanceof PermissionAuthenticationToken token) {
// PermissionSet이 이미 존재하면 새로 세팅할 필요 없음
needsAuthentication = token.getPermissionSet() == null;
} else if (authentication != null) {
// 다른 타입의 Authentication이 존재하면 덮어쓰지 않음
needsAuthentication = false;
}
if (needsAuthentication && jwtService.isTokenValid(jwt)) {
// 토큰에서 loginId와 PermissionSet 추출
String loginId = jwtService.extractLoginId(jwt);
PermissionSet permissionSet = jwtService.getPermissions(jwt);
if (permissionSet == null) {
permissionSet = new PermissionSet(List.of()); // PermissionSet으로 초기화
}
// SimpleGrantedAuthority 생성
List<SimpleGrantedAuthority> authorities = permissionSet.permissions().stream()
.map(p -> new SimpleGrantedAuthority(p.toString())) // 필요시 커스텀 문자열로 변경
.collect(Collectors.toList());
// PermissionAuthenticationToken 생성
PermissionAuthenticationToken authToken =
new PermissionAuthenticationToken(
loginId,
jwt, // 토큰 저장
permissionSet,
authorities
);
// SecurityContextHolder에 세팅
SecurityContextHolder.getContext().setAuthentication(authToken);
}
} catch (ExpiredJwtException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"error\":\"Session has expired.\"}");
return;
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"error\":\"Invalid login information.\"}");
return;
}
filterChain.doFilter(request, response);
}
}

View File

@ -0,0 +1,54 @@
package com.goi.erp.config;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.info.License;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.annotations.servers.Server;
@OpenAPIDefinition(
info = @Info(
contact = @Contact(
name = "Alibou",
email = "contact@aliboucoding.com",
url = "https://aliboucoding.com/course"
),
description = "OpenApi documentation for Spring Security",
title = "OpenApi specification - Alibou",
version = "1.0",
license = @License(
name = "Licence name",
url = "https://some-url.com"
),
termsOfService = "Terms of service"
),
servers = {
@Server(
description = "Local ENV",
url = "http://localhost:8080"
),
@Server(
description = "PROD ENV",
url = "https://aliboucoding.com/course"
)
},
security = {
@SecurityRequirement(
name = "bearerAuth"
)
}
)
@SecurityScheme(
name = "bearerAuth",
description = "JWT auth description",
scheme = "bearer",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
in = SecuritySchemeIn.HEADER
)
public class OpenApiConfig {
}

View File

@ -0,0 +1,14 @@
package com.goi.erp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

View File

@ -0,0 +1,66 @@
package com.goi.erp.config;
import lombok.RequiredArgsConstructor;
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
@EnableMethodSecurity // @PreAuthorize 사용 가능
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthFilter; // JWT 인증 필터
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // CSRF 비활성화 (API 서버라면 stateless)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // 세션 사용 안함
.authorizeHttpRequests(auth -> auth
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
.anyRequest().authenticated()
) // 요청 권한 설정
.addFilterBefore(new CorsFilter(corsConfigurationSource()), UsernamePasswordAuthenticationFilter.class) // JWT 필터 전에 CorsFilter 등록
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); // JWT 필터
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList(
"http://192.168.2.172:8000",
"http://localhost:8000",
"http://127.0.0.1:8000",
"https://homotypical-bowen-unlanguid.ngrok-free.dev"
));
configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Authorization","Content-Type"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,189 @@
package com.goi.erp.controller;
import com.goi.erp.common.permission.PermissionChecker;
import com.goi.erp.common.permission.PermissionSet;
import com.goi.erp.dto.VehicleRequestDto;
import com.goi.erp.dto.VehicleResponseDto;
import com.goi.erp.service.VehicleService;
import com.goi.erp.token.PermissionAuthenticationToken;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
@RestController
@RequestMapping("/vehicle")
@RequiredArgsConstructor
public class VehicleController {
@Value("${pagination.default-page:0}")
private int defaultPage;
@Value("${pagination.default-size:20}")
private int defaultSize;
@Value("${pagination.max-size:100}")
private int maxSize;
private final VehicleService vehicleService;
/* ============================================================
CREATE
============================================================ */
@PostMapping
public ResponseEntity<VehicleResponseDto> createVehicle(
@RequestBody VehicleRequestDto requestDto) {
PermissionAuthenticationToken auth =
(PermissionAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if (auth == null || auth.getPermissionSet() == null) {
throw new AccessDeniedException("Permission information is missing");
}
PermissionSet permissionSet = auth.getPermissionSet();
if (!PermissionChecker.canCreateOPR(permissionSet)) {
throw new AccessDeniedException("You do not have permission to create vehicle");
}
VehicleResponseDto response =
vehicleService.createVehicle(requestDto);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
/* ============================================================
READ ALL
============================================================ */
@GetMapping
public ResponseEntity<Page<VehicleResponseDto>> getAllVehicles(
@RequestParam(required = false) Integer page,
@RequestParam(required = false) Integer size) {
PermissionAuthenticationToken auth =
(PermissionAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if (auth == null || auth.getPermissionSet() == null) {
throw new AccessDeniedException("Permission information is missing");
}
PermissionSet permissionSet = auth.getPermissionSet();
if (!PermissionChecker.canReadOPRAll(permissionSet)) {
throw new AccessDeniedException("You do not have permission to read vehicle data");
}
int p = (page == null) ? defaultPage : page;
int s = (size == null) ? defaultSize : size;
if (s > maxSize) s = maxSize;
return ResponseEntity.ok(
vehicleService.getAllVehicles(p, s)
);
}
/* ============================================================
READ ONE (UUID)
============================================================ */
@GetMapping("/uuid/{uuid}")
public ResponseEntity<VehicleResponseDto> getVehicleByUuid(
@PathVariable UUID uuid) {
PermissionAuthenticationToken auth =
(PermissionAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if (auth == null || auth.getPermissionSet() == null) {
throw new AccessDeniedException("Permission information is missing");
}
PermissionSet permissionSet = auth.getPermissionSet();
if (!PermissionChecker.canReadOPR(permissionSet)) {
throw new AccessDeniedException("You do not have permission to read vehicle data");
}
return ResponseEntity.ok(
vehicleService.getVehicleByUuid(uuid)
);
}
/* ============================================================
UPDATE (UUID)
============================================================ */
@PatchMapping("/uuid/{uuid}")
public ResponseEntity<VehicleResponseDto> updateVehicleByUuid(
@PathVariable UUID uuid,
@RequestBody VehicleRequestDto requestDto) {
PermissionAuthenticationToken auth =
(PermissionAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if (auth == null || auth.getPermissionSet() == null) {
throw new AccessDeniedException("Permission information is missing");
}
PermissionSet permissionSet = auth.getPermissionSet();
if (!PermissionChecker.canUpdateOPR(permissionSet)) {
throw new AccessDeniedException("You do not have permission to update vehicle");
}
return ResponseEntity.ok(
vehicleService.updateVehicle(uuid, requestDto)
);
}
/* ============================================================
FROM MIS - READ BY VEHICLE NUMBER
============================================================ */
@GetMapping("/no/{vehNumber}")
public ResponseEntity<VehicleResponseDto> getVehicleByNumber(
@PathVariable String vehNumber) {
PermissionAuthenticationToken auth =
(PermissionAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if (auth == null || auth.getPermissionSet() == null) {
throw new AccessDeniedException("Permission information is missing");
}
PermissionSet permissionSet = auth.getPermissionSet();
if (!PermissionChecker.canReadOPR(permissionSet)) {
throw new AccessDeniedException("You do not have permission to read vehicle data");
}
return ResponseEntity.ok(
vehicleService.getVehicleByNumber(vehNumber)
);
}
/* ============================================================
FROM MIS - UPDATE BY VEHICLE NUMBER
============================================================ */
@PatchMapping("/no/{vehNumber}")
public ResponseEntity<VehicleResponseDto> updateVehicleByNumber(
@PathVariable String vehNumber,
@RequestBody VehicleRequestDto requestDto) {
PermissionAuthenticationToken auth =
(PermissionAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if (auth == null || auth.getPermissionSet() == null) {
throw new AccessDeniedException("Permission information is missing");
}
PermissionSet permissionSet = auth.getPermissionSet();
if (!PermissionChecker.canUpdateOPR(permissionSet)) {
throw new AccessDeniedException("You do not have permission to update vehicle");
}
return ResponseEntity.ok(
vehicleService.updateVehicleByNumber(vehNumber, requestDto)
);
}
}

View File

@ -0,0 +1,38 @@
package com.goi.erp.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data
@NoArgsConstructor
public class VehicleRequestDto {
private String vehNumber; // vehicle internal number
private String vehVin; // VIN
private String vehModel; // model
private String vehManufacturer; // manufacturer
private Integer vehYear; // year
private String vehLicensePlate; // license plate
private String vehLicensePlateSticker; // sticker
private LocalDate vehStartDate; // service start date
private String vehStatus; // A / I
private Integer vehOdometer; // current odometer
private String vehTankMaker; // tank manufacturer
private String vehTankSize; // tank size
private String vehTireSize; // tire size
private Boolean vehOverweightPermit; // overweight permit flag
private String vehHoistWeight; // hoist weight
private String vehWeightAfterLoading; // weight after loading
private String vehGps; // GPS device info
private String vehInsurancePolicyNumber; // insurance policy #
private LocalDate vehInsuranceHandoutDate; // insurance issued date
private LocalDate vehInsuranceExpireDate; // insurance expiry date
private Long vehTransponderId; // transponder ID
private String vehOwnership; // owned / leased
private String vehAnnualInspection; // annual inspection ref
private LocalDate vehLastAnnualInspectionDate;
private Long vehDefaultDriverId; // default driver (employee id)
private String vehLoginUser; // 요청 사용자 (audit/log용)
}

View File

@ -0,0 +1,43 @@
package com.goi.erp.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.util.UUID;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class VehicleResponseDto {
private UUID vehUuid;
private String vehNumber;
private String vehVin;
private String vehModel;
private String vehManufacturer;
private Integer vehYear;
private String vehLicensePlate;
private String vehLicensePlateSticker;
private LocalDate vehStartDate;
private String vehStatus;
private Integer vehOdometer;
private String vehTankMaker;
private String vehTankSize;
private String vehTireSize;
private Boolean vehOverweightPermit;
private String vehHoistWeight;
private String vehWeightAfterLoading;
private String vehGps;
private String vehInsurancePolicyNumber;
private LocalDate vehInsuranceHandoutDate;
private LocalDate vehInsuranceExpireDate;
private Long vehTransponderId;
private String vehOwnership;
private String vehAnnualInspection;
private LocalDate vehLastAnnualInspectionDate;
private Long vehDefaultDriverId;
}

View File

@ -0,0 +1,37 @@
package com.goi.erp.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "employee")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "emp_id")
private Long empId; // 내부 PK, 외부 노출 X
@Column(name = "emp_uuid", unique = true, nullable = false)
private UUID empUuid; // 외부 키로 사용
@Column(name = "emp_first_name")
private String empFirstName;
@Column(name = "emp_last_name")
private String empLastName;
}

View File

@ -0,0 +1,65 @@
package com.goi.erp.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDate;
import java.time.LocalDateTime;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "entity_change_log")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class EntityChangeLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ecl_id")
private Long eclId;
@Column(name = "ecl_entity_type")
private String eclEntityType;
@Column(name = "ecl_entity_id")
private Long eclEntityId;
@Column(name = "ecl_field_name")
private String eclFieldName;
@Column(name = "ecl_column_name")
private String eclColumnName;
@Column(name = "ecl_old_value")
private String eclOldValue;
@Column(name = "ecl_new_value")
private String eclNewValue;
@Column(name = "ecl_effective_date")
private LocalDate eclEffectiveDate;
@LastModifiedBy
@Column(name = "ecl_changed_by")
private String eclChangedBy;
@Column(name = "ecl_changed_at")
private LocalDateTime eclChangedAt;
@CreatedBy
@Column(name = "ecl_created_by")
private String eclCreatedBy;
}

View File

@ -0,0 +1,108 @@
package com.goi.erp.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "vehicle")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EntityListeners(AuditingEntityListener.class)
public class Vehicle {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long vehId;
@Column(nullable = false, unique = true)
private UUID vehUuid;
@Column(length = 20)
private String vehNumber;
@Column(length = 50)
private String vehVin;
@Column(length = 100)
private String vehModel;
@Column(length = 100)
private String vehManufacturer;
private Integer vehYear;
@Column(length = 20)
private String vehLicensePlate;
@Column(length = 20)
private String vehLicensePlateSticker;
private LocalDate vehStartDate;
@Column(length = 1)
private String vehStatus; // A / I
private Integer vehOdometer;
@Column(length = 50)
private String vehTankMaker;
@Column(length = 20)
private String vehTankSize;
@Column(length = 20)
private String vehTireSize;
private Boolean vehOverweightPermit;
@Column(length = 20)
private String vehHoistWeight;
@Column(length = 20)
private String vehWeightAfterLoading;
@Column(length = 20)
private String vehGps;
@Column(length = 50)
private String vehInsurancePolicyNumber;
private LocalDate vehInsuranceHandoutDate;
private LocalDate vehInsuranceExpireDate;
private Long vehTransponderId;
@Column(length = 50)
private String vehOwnership;
private LocalDateTime vehCreatedAt;
private LocalDateTime vehUpdatedAt;
@CreatedBy
private String vehCreatedBy;
@LastModifiedBy
private String vehUpdatedBy;
@Column(length = 20)
private String vehAnnualInspection;
private LocalDate vehLastAnnualInspectionDate;
private Long vehDefaultDriverId;
}

View File

@ -0,0 +1,10 @@
package com.goi.erp.repository;
import com.goi.erp.entity.EntityChangeLog;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EntityChangeLogRepository extends JpaRepository<EntityChangeLog, Long> {
}

View File

@ -0,0 +1,24 @@
package com.goi.erp.repository;
import com.goi.erp.entity.Vehicle;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface VehicleRepository extends JpaRepository<Vehicle, Long> {
Page<Vehicle> findAll(Pageable pageable);
Optional<Vehicle> findByVehUuid(UUID vehUuid);
Optional<Vehicle> findByVehNumber(String vehNumber);
Optional<Vehicle> findByVehVin(String vehVin);
boolean existsByVehNumber(String vehNumber);
boolean existsByVehVin(String vehVin);
}

View File

@ -0,0 +1,124 @@
package com.goi.erp.service;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.goi.erp.token.PermissionAuthenticationToken;
import java.util.Map;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class HcmEmployeeClient {
private final RestTemplate restTemplate;
@Value("${hcm.api.base-url}")
private String hcmBaseUrl;
public Long getEmpIdFromExternalId(String externalId) {
String url = hcmBaseUrl + "/employee/external" + "?solutionType=MIS&externalId=" + externalId;
try {
// set token in header
String jwt = getCurrentJwt();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + jwt);
HttpEntity<Void> entity = new HttpEntity<>(headers);
// GET
ResponseEntity<Map<String, Object>> response =
restTemplate.exchange(
url,
HttpMethod.GET,
entity,
new ParameterizedTypeReference<Map<String, Object>>() {}
);
Map<String, Object> body = response.getBody();
//System.out.println("RESPONSE ➜ " + body);
if (body != null && body.get("eexEmpId") != null) {
Object raw = body.get("eexEmpId");
if (raw instanceof Number) {
return ((Number) raw).longValue(); // 🔥 모든 숫자를 Long 변환
}
// 예상 타입일 경우
}
return null;
} catch (Exception e) {
// 필요하면 logging
System.out.println("externalId lookup error: " + e.getMessage());
return null;
}
}
public Long getEmpIdFromUuid(UUID uuid) {
String url = hcmBaseUrl + "/employee/" + uuid;
try {
// set token in header
String jwt = getCurrentJwt();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + jwt);
HttpEntity<Void> entity = new HttpEntity<>(headers);
// GET
ResponseEntity<Map<String, Object>> response =
restTemplate.exchange(
url,
HttpMethod.GET,
entity,
new ParameterizedTypeReference<Map<String, Object>>() {}
);
Map<String, Object> body = response.getBody();
//System.out.println("RESPONSE(UUID) ➜ " + body);
if (body != null && body.get("empId") != null) {
Object raw = body.get("empId");
if (raw instanceof Number) {
return ((Number) raw).longValue(); // 🔥 모든 숫자를 Long 변환
}
// 예상 타입일 경우
}
return null;
} catch (Exception e) {
// 필요하면 로깅
System.out.println("UUID lookup error: " + e.getMessage());
return null;
}
}
private String getCurrentJwt() {
var auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof PermissionAuthenticationToken token) {
return token.getJwt();
}
return null;
}
}

View File

@ -0,0 +1,257 @@
package com.goi.erp.service;
import com.goi.erp.dto.VehicleRequestDto;
import com.goi.erp.dto.VehicleResponseDto;
import com.goi.erp.entity.EntityChangeLog;
import com.goi.erp.entity.Vehicle;
import com.goi.erp.repository.EntityChangeLogRepository;
import com.goi.erp.repository.VehicleRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class VehicleService {
private final VehicleRepository vehicleRepository;
private final EntityChangeLogRepository entityChangeLogRepository;
/* ============================================================
CREATE
============================================================ */
public VehicleResponseDto createVehicle(VehicleRequestDto dto) {
// VIN 중복 체크 (강력 )
if (dto.getVehVin() != null && vehicleRepository.existsByVehVin(dto.getVehVin())) {
throw new RuntimeException("Vehicle with VIN already exists");
}
// Vehicle Number 중복 체크 (업무 )
if (dto.getVehNumber() != null && vehicleRepository.existsByVehNumber(dto.getVehNumber())) {
throw new RuntimeException("Vehicle number already exists");
}
Vehicle vehicle = Vehicle.builder()
.vehUuid(UUID.randomUUID())
.vehNumber(dto.getVehNumber())
.vehVin(dto.getVehVin())
.vehModel(dto.getVehModel())
.vehManufacturer(dto.getVehManufacturer())
.vehYear(dto.getVehYear())
.vehLicensePlate(dto.getVehLicensePlate())
.vehLicensePlateSticker(dto.getVehLicensePlateSticker())
.vehStartDate(dto.getVehStartDate())
.vehStatus(dto.getVehStatus())
.vehOdometer(dto.getVehOdometer())
.vehTankMaker(dto.getVehTankMaker())
.vehTankSize(dto.getVehTankSize())
.vehTireSize(dto.getVehTireSize())
.vehOverweightPermit(dto.getVehOverweightPermit())
.vehHoistWeight(dto.getVehHoistWeight())
.vehWeightAfterLoading(dto.getVehWeightAfterLoading())
.vehGps(dto.getVehGps())
.vehInsurancePolicyNumber(dto.getVehInsurancePolicyNumber())
.vehInsuranceHandoutDate(dto.getVehInsuranceHandoutDate())
.vehInsuranceExpireDate(dto.getVehInsuranceExpireDate())
.vehTransponderId(dto.getVehTransponderId())
.vehOwnership(dto.getVehOwnership())
.vehAnnualInspection(dto.getVehAnnualInspection())
.vehLastAnnualInspectionDate(dto.getVehLastAnnualInspectionDate())
.vehDefaultDriverId(dto.getVehDefaultDriverId())
.build();
vehicle = vehicleRepository.save(vehicle);
return mapToDto(vehicle);
}
/* ============================================================
READ
============================================================ */
public Page<VehicleResponseDto> getAllVehicles(int page, int size) {
Pageable pageable = PageRequest.of(page, size);
return vehicleRepository.findAll(pageable).map(this::mapToDto);
}
public VehicleResponseDto getVehicleByUuid(UUID uuid) {
Vehicle vehicle = vehicleRepository.findByVehUuid(uuid)
.orElseThrow(() -> new RuntimeException("Vehicle not found"));
return mapToDto(vehicle);
}
public VehicleResponseDto getVehicleByNumber(String vehNumber) {
Vehicle vehicle = vehicleRepository.findByVehNumber(vehNumber)
.orElseThrow(() -> new RuntimeException("Vehicle not found"));
return mapToDto(vehicle);
}
/* ============================================================
UPDATE
============================================================ */
public VehicleResponseDto updateVehicle(UUID uuid, VehicleRequestDto dto) {
Vehicle vehicle = vehicleRepository.findByVehUuid(uuid)
.orElseThrow(() -> new RuntimeException("Vehicle not found"));
return updateVehicleInternal(vehicle, dto);
}
@Transactional
public VehicleResponseDto updateVehicleByNumber(String vehNumber, VehicleRequestDto dto) {
Vehicle oldVehicle = vehicleRepository.findByVehNumber(vehNumber)
.orElseThrow(() -> new RuntimeException("Vehicle not found"));
// 1. OLD VALUE 백업
Vehicle beforeUpdate = new Vehicle();
BeanUtils.copyProperties(oldVehicle, beforeUpdate);
// 2. 실제 업데이트
VehicleResponseDto response = updateVehicleInternal(oldVehicle, dto);
// 3. 변경 로그
compareAndLogChanges(beforeUpdate, oldVehicle, dto.getVehLoginUser());
return response;
}
private VehicleResponseDto updateVehicleInternal(Vehicle vehicle, VehicleRequestDto dto) {
if (dto.getVehNumber() != null) vehicle.setVehNumber(dto.getVehNumber());
if (dto.getVehModel() != null) vehicle.setVehModel(dto.getVehModel());
if (dto.getVehManufacturer() != null) vehicle.setVehManufacturer(dto.getVehManufacturer());
if (dto.getVehYear() != null) vehicle.setVehYear(dto.getVehYear());
if (dto.getVehLicensePlate() != null) vehicle.setVehLicensePlate(dto.getVehLicensePlate());
if (dto.getVehLicensePlateSticker() != null) vehicle.setVehLicensePlateSticker(dto.getVehLicensePlateSticker());
if (dto.getVehStartDate() != null) vehicle.setVehStartDate(dto.getVehStartDate());
if (dto.getVehStatus() != null) vehicle.setVehStatus(dto.getVehStatus());
if (dto.getVehOdometer() != null) vehicle.setVehOdometer(dto.getVehOdometer());
if (dto.getVehTankMaker() != null) vehicle.setVehTankMaker(dto.getVehTankMaker());
if (dto.getVehTankSize() != null) vehicle.setVehTankSize(dto.getVehTankSize());
if (dto.getVehTireSize() != null) vehicle.setVehTireSize(dto.getVehTireSize());
if (dto.getVehOverweightPermit() != null) vehicle.setVehOverweightPermit(dto.getVehOverweightPermit());
if (dto.getVehHoistWeight() != null) vehicle.setVehHoistWeight(dto.getVehHoistWeight());
if (dto.getVehWeightAfterLoading() != null) vehicle.setVehWeightAfterLoading(dto.getVehWeightAfterLoading());
if (dto.getVehGps() != null) vehicle.setVehGps(dto.getVehGps());
if (dto.getVehInsurancePolicyNumber() != null) vehicle.setVehInsurancePolicyNumber(dto.getVehInsurancePolicyNumber());
if (dto.getVehInsuranceHandoutDate() != null) vehicle.setVehInsuranceHandoutDate(dto.getVehInsuranceHandoutDate());
if (dto.getVehInsuranceExpireDate() != null) vehicle.setVehInsuranceExpireDate(dto.getVehInsuranceExpireDate());
if (dto.getVehTransponderId() != null) vehicle.setVehTransponderId(dto.getVehTransponderId());
if (dto.getVehOwnership() != null) vehicle.setVehOwnership(dto.getVehOwnership());
if (dto.getVehAnnualInspection() != null) vehicle.setVehAnnualInspection(dto.getVehAnnualInspection());
if (dto.getVehLastAnnualInspectionDate() != null) vehicle.setVehLastAnnualInspectionDate(dto.getVehLastAnnualInspectionDate());
if (dto.getVehDefaultDriverId() != null) vehicle.setVehDefaultDriverId(dto.getVehDefaultDriverId());
vehicleRepository.save(vehicle);
return mapToDto(vehicle);
}
/* ============================================================
DTO MAPPER
============================================================ */
public VehicleResponseDto mapToDto(Vehicle vehicle) {
if (vehicle == null) return null;
return VehicleResponseDto.builder()
.vehUuid(vehicle.getVehUuid())
.vehNumber(vehicle.getVehNumber())
.vehVin(vehicle.getVehVin())
.vehModel(vehicle.getVehModel())
.vehManufacturer(vehicle.getVehManufacturer())
.vehYear(vehicle.getVehYear())
.vehLicensePlate(vehicle.getVehLicensePlate())
.vehLicensePlateSticker(vehicle.getVehLicensePlateSticker())
.vehStartDate(vehicle.getVehStartDate())
.vehStatus(vehicle.getVehStatus())
.vehOdometer(vehicle.getVehOdometer())
.vehTankMaker(vehicle.getVehTankMaker())
.vehTankSize(vehicle.getVehTankSize())
.vehTireSize(vehicle.getVehTireSize())
.vehOverweightPermit(vehicle.getVehOverweightPermit())
.vehHoistWeight(vehicle.getVehHoistWeight())
.vehWeightAfterLoading(vehicle.getVehWeightAfterLoading())
.vehGps(vehicle.getVehGps())
.vehInsurancePolicyNumber(vehicle.getVehInsurancePolicyNumber())
.vehInsuranceHandoutDate(vehicle.getVehInsuranceHandoutDate())
.vehInsuranceExpireDate(vehicle.getVehInsuranceExpireDate())
.vehTransponderId(vehicle.getVehTransponderId())
.vehOwnership(vehicle.getVehOwnership())
.vehAnnualInspection(vehicle.getVehAnnualInspection())
.vehLastAnnualInspectionDate(vehicle.getVehLastAnnualInspectionDate())
.vehDefaultDriverId(vehicle.getVehDefaultDriverId())
.build();
}
/* ============================================================
CHANGE LOG
============================================================ */
private void compareAndLogChanges(Vehicle oldData, Vehicle newData, String changedBy) {
Map<String, String> fieldToColumn = Map.ofEntries(
Map.entry("vehNumber", "veh_number"),
Map.entry("vehModel", "veh_model"),
Map.entry("vehManufacturer", "veh_manufacturer"),
Map.entry("vehYear", "veh_year"),
Map.entry("vehLicensePlate", "veh_license_plate"),
Map.entry("vehStatus", "veh_status"),
Map.entry("vehOdometer", "veh_odometer"),
Map.entry("vehInsurancePolicyNumber", "veh_insurance_policy_number"),
Map.entry("vehInsuranceExpireDate", "veh_insurance_expire_date"),
Map.entry("vehDefaultDriverId", "veh_default_driver_id")
);
for (var entry : fieldToColumn.entrySet()) {
try {
Field field = Vehicle.class.getDeclaredField(entry.getKey());
field.setAccessible(true);
Object oldVal = field.get(oldData);
Object newVal = field.get(newData);
if (valuesAreDifferent(oldVal, newVal)) {
entityChangeLogRepository.save(
EntityChangeLog.builder()
.eclEntityType("Vehicle")
.eclEntityId(newData.getVehId())
.eclFieldName(entry.getKey())
.eclColumnName(entry.getValue())
.eclOldValue(oldVal == null ? null : oldVal.toString())
.eclNewValue(newVal == null ? null : newVal.toString())
.eclEffectiveDate(LocalDate.now())
.eclChangedBy(changedBy)
.eclChangedAt(LocalDateTime.now())
.build()
);
}
} catch (Exception e) {
throw new RuntimeException("Failed to compare field: " + entry.getKey(), e);
}
}
}
private boolean valuesAreDifferent(Object oldVal, Object newVal) {
if (oldVal == null && newVal == null) return false;
if (oldVal == null || newVal == null) return true;
if (oldVal instanceof LocalDate d1 && newVal instanceof LocalDate d2) {
return !d1.isEqual(d2);
}
if (oldVal instanceof LocalDateTime t1 && newVal instanceof LocalDateTime t2) {
return !t1.equals(t2);
}
return !oldVal.equals(newVal);
}
}

View File

@ -0,0 +1,90 @@
package com.goi.erp.token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.data.domain.AuditorAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
import java.security.Key;
/**
* auth-service에서 발급한 JWT 토큰 기반으로 현재 사용자(empId) 가져오는 AuditorAware 구현체
*
* - JPA auditing에서 사용자가 누군지 기록할 사용
* - SecurityContextHolder 없이도 동작 가능
* - HttpServletRequest에서 Authorization 헤더를 읽어 토큰 파싱
*/
public class ApplicationAuditAware implements AuditorAware<String> {
private final String jwtSecret;
public ApplicationAuditAware(String jwtSecret) {
this.jwtSecret = jwtSecret;
}
/**
* 현재 요청을 수행하는 사용자의 empId 반환
* @return Optional<Integer> - empId가 없거나 토큰이 유효하지 않으면 Optional.empty()
*/
@Override
public Optional<String> getCurrentAuditor() {
HttpServletRequest request = getCurrentHttpRequest();
if (request == null) {
return Optional.empty();
}
String token = resolveToken(request);
if (token == null) {
return Optional.empty();
}
try {
// JWT 파싱
byte[] keyBytes = Decoders.BASE64.decode(jwtSecret);
Key key = Keys.hmacShaKeyFor(keyBytes);
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
// 토큰에 loginId 클레임이 있어야
String loginId = claims.get("loginId", String.class);
return Optional.ofNullable(loginId);
} catch (Exception e) {
// 토큰 파싱/검증 실패 Optional.empty() 반환
e.printStackTrace(); // 🔥 예외 확인
System.out.println("JWT Error: " + e.getMessage());
return Optional.empty();
}
}
/**
* 현재 스레드의 HttpServletRequest 가져오기
* @return HttpServletRequest 또는 null
*/
private HttpServletRequest getCurrentHttpRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attrs == null) return null;
return attrs.getRequest();
}
/**
* HttpServletRequest에서 Authorization 헤더의 Bearer 토큰 추출
* @param request 현재 HttpServletRequest
* @return JWT 문자열 또는 null
*/
private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
}

View File

@ -0,0 +1,149 @@
package com.goi.erp.token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.goi.erp.common.permission.PermissionParser;
import com.goi.erp.common.permission.PermissionSet;
import java.security.Key;
import java.util.List;
import java.util.function.Function;
/**
* - DB 접근 없음
* - JWT에 포함된 empUuid, 이름, roles, permissions 추출
* - 토큰 유효기간 체크 가능
*/
@Service
public class JwtService {
@Value("${application.security.jwt.secret-key}")
private String secretKey;
@Value("${application.security.jwt.expiration}")
private long jwtExpiration;
/**
* empUuid(sub) 추출
*/
public String extractEmpUuid(String token) {
return extractClaim(token, Claims::getSubject);
}
/**
* loginId 추출
*/
public String extractLoginId(String token) {
return extractClaim(token, claims -> claims.get("loginId", String.class));
}
/**
* firstName 추출
*/
public String extractFirstName(String token) {
return extractClaim(token, claims -> claims.get("firstName", String.class));
}
/**
* lastName 추출
*/
public String extractLastName(String token) {
return extractClaim(token, claims -> claims.get("lastName", String.class));
}
/**
* roles 리스트 추출
*/
@SuppressWarnings("unchecked")
public List<String> extractRoles(String token) {
return extractClaim(token, claims -> (List<String>) claims.get("roles"));
}
/**
* permissions 리스트 추출
*/
@SuppressWarnings("unchecked")
public List<String> extractPermissions(String token) {
return extractClaim(token, claims -> (List<String>) claims.get("permissions"));
}
/**
* 토큰 만료 여부 확인
*/
public boolean isTokenExpired(String token) {
return extractClaim(token, Claims::getExpiration).before(new java.util.Date());
}
/**
* 토큰 유효성 검사 (만료 체크)
*/
public boolean isTokenValid(String token) {
return !isTokenExpired(token);
}
/**
* JWT에서 Claims 추출
*/
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
/**
* JWT 전체 Claims 추출
*/
private Claims extractAllClaims(String token) {
return Jwts.parserBuilder()
.setSigningKey(getSignInKey())
.build()
.parseClaimsJws(token)
.getBody();
}
/**
* Permission Set 변환
*/
@SuppressWarnings("unchecked")
public PermissionSet getPermissions(String token) {
Claims claims = extractAllClaims(token);
List<String> permissions = claims.get("permissions", List.class);
return PermissionParser.parse(permissions);
}
private Key getSignInKey() {
byte[] keyBytes = Decoders.BASE64.decode(secretKey); // auth-service와 동일한 Base64 secret
return Keys.hmacShaKeyFor(keyBytes);
}
public static void main(String[] args) {
JwtService jwtService = new JwtService();
jwtService.secretKey = "D0HaHnTPKLkUO9ULL1Ulm6XDZjhzuFtvTCcxTxSoCS8=";
String token = "eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJNSVMiLCJsYXN0TmFtZSI6IkNTIiwibG9naW5JZCI6ImNzX21pcyIsInBlcm1pc3Npb25zIjpbIkg6UjpTIiwiQzpDOkEiLCJDOlI6QSIsIkM6VTpBIiwiQzpEOkEiXSwicm9sZXMiOlsiQ1MgU3RhZmYiXSwic3ViIjoiMWU3NTU4YzYtOTFhZC00ZDcxLTg3ZTUtZGJjZmZiYjk5Zjg1IiwiaWF0IjoxNzY0MzQ3Nzg1LCJleHAiOjIwNzk3MDc3ODV9.lL-ZHEpiribxIrNmeYp6LAeU11z-KuRbgELkWjHCCSc";
// user 정보
Claims claims = jwtService.extractAllClaims(token);
System.out.println("Subject (emp_uuid): " + claims.getSubject());
System.out.println("Roles: " + claims.get("roles"));
System.out.println("Roles: " + claims.get("permissions"));
System.out.println("IssuedAt: " + claims.getIssuedAt());
System.out.println("Expiration: " + claims.getExpiration());
System.out.println("FirstName: " + claims.get("firstName", String.class));
System.out.println("LastName: " + claims.get("lastName", String.class));
// 모든 Claims 확인
// Claims claims = Jwts.parserBuilder()
// .setSigningKey(Keys.hmacShaKeyFor("<secret_key>".getBytes()))
// .build()
// .parseClaimsJws(token)
// .getBody();
System.out.println("Claims: " + claims);
}
}

View File

@ -0,0 +1,40 @@
package com.goi.erp.token;
import java.util.Collection;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import com.goi.erp.common.permission.PermissionSet;
public class PermissionAuthenticationToken extends UsernamePasswordAuthenticationToken {
private static final long serialVersionUID = 1L;
private final PermissionSet permissionSet;
private final String jwt; // JWT 저장
/**
* @param principal 로그인 ID 또는 emp_uuid
* @param jwt 실제 JWT 토큰 문자열
* @param permissionSet 권한 정보
* @param authorities Spring Security Authority
*/
public PermissionAuthenticationToken(
String principal,
String jwt,
PermissionSet permissionSet,
Collection<? extends GrantedAuthority> authorities
) {
super(principal, jwt, authorities); // credentials jwt 넣어줌
this.permissionSet = permissionSet;
this.jwt = jwt; // 여기 저장
}
public PermissionSet getPermissionSet() {
return permissionSet;
}
public String getJwt() {
return jwt;
}
}

View File

@ -0,0 +1,38 @@
spring:
datasource:
url: jdbc:postgresql://${DB_HOST}:${DB_PORT:5432}/${DB_NAME:goi}
username: ${DB_USER}
password: ${DB_PASSWORD}
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: validate
show-sql: false
properties:
hibernate:
format_sql: true
database: postgresql
database-platform: org.hibernate.dialect.PostgreSQLDialect
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
application:
security:
jwt:
secret-key: ${SECRET_KEY}
expiration: 86400000 # a day
refresh-token:
expiration: 604800000 # 7 days
pagination:
default-page: 0
default-size: 20
max-size: 100
server:
port: 8083
servlet:
context-path: /opr-rest-api
# ================================
# ADD THIS
# ================================
hcm:
api:
base-url: http://localhost:8081/hcm-rest-api

View File

@ -0,0 +1,13 @@
package com.goi.security;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SecurityApplicationTests {
@Test
void contextLoads() {
}
}