commit
ba74a00a06
|
|
@ -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/
|
||||
Binary file not shown.
|
|
@ -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
|
||||
|
|
@ -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.
|
||||
|
|
@ -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.
|
||||
|
|
@ -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:
|
||||
|
|
@ -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 "$@"
|
||||
|
|
@ -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%
|
||||
|
|
@ -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>hcm-rest-api</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>Customer Service</name>
|
||||
<description>Human Capital Management 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>
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package com.goi.erp.common.permission;
|
||||
|
||||
public class PermissionChecker {
|
||||
|
||||
public static boolean canCreateCRM(PermissionSet set) {
|
||||
if (set.hasAll()) return true;
|
||||
return set.has(PermissionEnums.Module.C, PermissionEnums.Action.C);
|
||||
}
|
||||
|
||||
public static boolean canReadCRM(PermissionSet set) {
|
||||
if (set.hasAll()) return true;
|
||||
return set.has(PermissionEnums.Module.C, PermissionEnums.Action.R);
|
||||
}
|
||||
|
||||
public static boolean canUpdateCRM(PermissionSet set) {
|
||||
if (set.hasAll()) return true;
|
||||
return set.has(PermissionEnums.Module.C, PermissionEnums.Action.U);
|
||||
}
|
||||
|
||||
public static boolean canDeleteCRM(PermissionSet set) {
|
||||
if (set.hasAll()) return true;
|
||||
return set.has(PermissionEnums.Module.C, PermissionEnums.Action.D);
|
||||
}
|
||||
|
||||
// 범위까지 체크
|
||||
public static boolean canReadCRMAll(PermissionSet set) {
|
||||
if (set.hasAll()) return true;
|
||||
return set.hasFull(
|
||||
PermissionEnums.Module.C,
|
||||
PermissionEnums.Action.R,
|
||||
PermissionEnums.Scope.A
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
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, 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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 {
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
package com.goi.erp.controller;
|
||||
|
||||
import com.goi.erp.dto.EmployeeRequestDto;
|
||||
import com.goi.erp.dto.EmployeeResponseDto;
|
||||
import com.goi.erp.service.EmployeeService;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/employee")
|
||||
@RequiredArgsConstructor
|
||||
public class EmployeeController {
|
||||
|
||||
private final EmployeeService employeeService;
|
||||
|
||||
/**
|
||||
* CREATE
|
||||
*/
|
||||
@PostMapping
|
||||
public ResponseEntity<EmployeeResponseDto> createEmployee(
|
||||
@RequestBody EmployeeRequestDto requestDto) {
|
||||
|
||||
EmployeeResponseDto response = employeeService.createEmployee(requestDto);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* READ - detail
|
||||
*/
|
||||
@GetMapping("/{empUuid}")
|
||||
public ResponseEntity<EmployeeResponseDto> getEmployee(
|
||||
@PathVariable UUID empUuid) {
|
||||
|
||||
EmployeeResponseDto response = employeeService.getEmployeeByUuid(empUuid);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* READ - list
|
||||
*/
|
||||
@GetMapping
|
||||
public ResponseEntity<List<EmployeeResponseDto>> getAllEmployees() {
|
||||
|
||||
List<EmployeeResponseDto> employees = employeeService.getAllEmployees();
|
||||
return ResponseEntity.ok(employees);
|
||||
}
|
||||
|
||||
/**
|
||||
* READ - active employees only
|
||||
*/
|
||||
@GetMapping("/active")
|
||||
public ResponseEntity<List<EmployeeResponseDto>> getActiveEmployees() {
|
||||
|
||||
List<EmployeeResponseDto> employees = employeeService.getActiveEmployees();
|
||||
return ResponseEntity.ok(employees);
|
||||
}
|
||||
|
||||
/**
|
||||
* UPDATE (PATCH ONLY)
|
||||
*/
|
||||
@PatchMapping("/{empUuid}")
|
||||
public ResponseEntity<EmployeeResponseDto> updateEmployee(
|
||||
@PathVariable UUID empUuid,
|
||||
@RequestBody EmployeeRequestDto requestDto) {
|
||||
|
||||
EmployeeResponseDto updated = employeeService.updateEmployee(empUuid, requestDto);
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
|
||||
/**
|
||||
* INACTIVATE (soft delete)
|
||||
*/
|
||||
@PatchMapping("/{empUuid}/inactive")
|
||||
public ResponseEntity<EmployeeResponseDto> inactivateEmployee(
|
||||
@PathVariable UUID empUuid) {
|
||||
|
||||
EmployeeResponseDto updated = employeeService.inactivateEmployee(empUuid);
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
package com.goi.erp.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
public class EmployeeRequestDto {
|
||||
|
||||
private String empNo;
|
||||
private String empLoginId;
|
||||
private String empLoginPassword;
|
||||
|
||||
private String empFirstName;
|
||||
private String empMiddleName;
|
||||
private String empLastName;
|
||||
|
||||
private String empPreferredFirstName;
|
||||
private String empPreferredLastName;
|
||||
|
||||
private String empStatus;
|
||||
private String empFulltime;
|
||||
private String empEmploymentType;
|
||||
private String empLeaveStatus;
|
||||
|
||||
private LocalDate empOfferAcceptedDate;
|
||||
|
||||
private String empNationality;
|
||||
private String empCitizenshipStatus;
|
||||
|
||||
private String empPassportNo;
|
||||
private String empPassportCountry;
|
||||
private LocalDate empPassportIssueDate;
|
||||
private LocalDate empPassportExpiryDate;
|
||||
|
||||
private String empVisaType;
|
||||
private LocalDate empVisaIssueDate;
|
||||
private LocalDate empVisaExpiryDate;
|
||||
private String empVisaCountry;
|
||||
|
||||
private LocalDate empDateOfBirth;
|
||||
private String empSex;
|
||||
|
||||
private String empSin;
|
||||
private String empAccountNo;
|
||||
private String empDriverLicenseNo;
|
||||
|
||||
private String empPersonalEmail;
|
||||
private String empPersonalPhone;
|
||||
|
||||
private String empAddress1;
|
||||
private String empAddress2;
|
||||
private String empPostalCode;
|
||||
private String empCity;
|
||||
private String empProvince;
|
||||
|
||||
private LocalDate empContractStartDate;
|
||||
private LocalDate empProbationStartDate;
|
||||
private LocalDate empProbationEndDate;
|
||||
private String empProbationStatus;
|
||||
|
||||
private LocalDate empJobStartDate;
|
||||
private LocalDate empJobEndDate;
|
||||
|
||||
private LocalDate empTerminationDate;
|
||||
private String empTerminationReason;
|
||||
|
||||
private Long empDeptId;
|
||||
|
||||
private BigDecimal empRate;
|
||||
private BigDecimal empRateOt;
|
||||
private BigDecimal empRateDot;
|
||||
|
||||
private String empOfficeEmail;
|
||||
private String empOfficeMobile;
|
||||
private String empOfficePhone;
|
||||
|
||||
private String empExtensionNo;
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
package com.goi.erp.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Data
|
||||
public class EmployeeResponseDto {
|
||||
|
||||
private Long empId;
|
||||
private UUID empUuid;
|
||||
|
||||
private String empNo;
|
||||
private String empLoginId;
|
||||
|
||||
private String empFirstName;
|
||||
private String empMiddleName;
|
||||
private String empLastName;
|
||||
|
||||
private String empPreferredFirstName;
|
||||
private String empPreferredLastName;
|
||||
|
||||
private String empStatus;
|
||||
private String empFulltime;
|
||||
private String empEmploymentType;
|
||||
private String empLeaveStatus;
|
||||
|
||||
private LocalDate empOfferAcceptedDate;
|
||||
|
||||
private LocalDateTime empCreatedAt;
|
||||
private LocalDateTime empUpdatedAt;
|
||||
private String empCreatedBy;
|
||||
private String empUpdatedBy;
|
||||
|
||||
private String empNationality;
|
||||
private String empCitizenshipStatus;
|
||||
|
||||
private String empPassportNo;
|
||||
private String empPassportCountry;
|
||||
private LocalDate empPassportIssueDate;
|
||||
private LocalDate empPassportExpiryDate;
|
||||
|
||||
private String empVisaType;
|
||||
private LocalDate empVisaIssueDate;
|
||||
private LocalDate empVisaExpiryDate;
|
||||
private String empVisaCountry;
|
||||
|
||||
private LocalDate empDateOfBirth;
|
||||
private String empSex;
|
||||
|
||||
private String empSin;
|
||||
private String empAccountNo;
|
||||
private String empDriverLicenseNo;
|
||||
|
||||
private String empPersonalEmail;
|
||||
private String empPersonalPhone;
|
||||
|
||||
private String empAddress1;
|
||||
private String empAddress2;
|
||||
private String empPostalCode;
|
||||
private String empCity;
|
||||
private String empProvince;
|
||||
|
||||
private LocalDate empContractStartDate;
|
||||
private LocalDate empProbationStartDate;
|
||||
private LocalDate empProbationEndDate;
|
||||
private String empProbationStatus;
|
||||
|
||||
private LocalDate empJobStartDate;
|
||||
private LocalDate empJobEndDate;
|
||||
|
||||
private LocalDate empTerminationDate;
|
||||
private String empTerminationReason;
|
||||
|
||||
private Long empDeptId;
|
||||
|
||||
private BigDecimal empRate;
|
||||
private BigDecimal empRateOt;
|
||||
private BigDecimal empRateDot;
|
||||
|
||||
private String empOfficeEmail;
|
||||
private String empOfficeMobile;
|
||||
private String empOfficePhone;
|
||||
|
||||
private String empExtensionNo;
|
||||
}
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
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.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "employee")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class Employee {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long empId;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private UUID empUuid;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String empNo;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 100)
|
||||
private String empLoginId;
|
||||
|
||||
@Column(nullable = false, length = 255)
|
||||
private String empLoginPassword;
|
||||
|
||||
private String empFirstName;
|
||||
private String empMiddleName;
|
||||
private String empLastName;
|
||||
|
||||
private String empPreferredFirstName;
|
||||
private String empPreferredLastName;
|
||||
|
||||
@Column(length = 1)
|
||||
private String empStatus; // A / I
|
||||
|
||||
@Column(length = 1)
|
||||
private String empFulltime; // F / P
|
||||
|
||||
@Column(length = 1)
|
||||
private String empEmploymentType; // R / C / I
|
||||
|
||||
@Column(length = 1)
|
||||
private String empLeaveStatus; // N / L / S / O
|
||||
|
||||
private LocalDate empOfferAcceptedDate;
|
||||
|
||||
private LocalDateTime empCreatedAt;
|
||||
private LocalDateTime empUpdatedAt;
|
||||
|
||||
@CreatedBy
|
||||
private String empCreatedBy;
|
||||
|
||||
@LastModifiedBy
|
||||
private String empUpdatedBy;
|
||||
|
||||
private String empNationality;
|
||||
private String empCitizenshipStatus;
|
||||
|
||||
private String empPassportNo;
|
||||
private String empPassportCountry;
|
||||
private LocalDate empPassportIssueDate;
|
||||
private LocalDate empPassportExpiryDate;
|
||||
|
||||
private String empVisaType;
|
||||
private LocalDate empVisaIssueDate;
|
||||
private LocalDate empVisaExpiryDate;
|
||||
private String empVisaCountry;
|
||||
|
||||
private LocalDate empDateOfBirth;
|
||||
|
||||
@Column(length = 1)
|
||||
private String empSex;
|
||||
|
||||
private String empSin;
|
||||
private String empAccountNo;
|
||||
private String empDriverLicenseNo;
|
||||
|
||||
private String empPersonalEmail;
|
||||
private String empPersonalPhone;
|
||||
|
||||
private String empAddress1;
|
||||
private String empAddress2;
|
||||
private String empPostalCode;
|
||||
private String empCity;
|
||||
private String empProvince;
|
||||
|
||||
private LocalDate empContractStartDate;
|
||||
private LocalDate empProbationStartDate;
|
||||
private LocalDate empProbationEndDate;
|
||||
private String empProbationStatus;
|
||||
|
||||
private LocalDate empJobStartDate;
|
||||
private LocalDate empJobEndDate;
|
||||
|
||||
private LocalDate empTerminationDate;
|
||||
private String empTerminationReason;
|
||||
|
||||
private Long empDeptId;
|
||||
|
||||
private BigDecimal empRate;
|
||||
private BigDecimal empRateOt;
|
||||
private BigDecimal empRateDot;
|
||||
|
||||
private String empOfficeEmail;
|
||||
private String empOfficeMobile;
|
||||
private String empOfficePhone;
|
||||
|
||||
private String empExtensionNo;
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package com.goi.erp.repository;
|
||||
|
||||
import com.goi.erp.entity.Employee;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Repository
|
||||
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
|
||||
|
||||
// UUID로 조회
|
||||
Optional<Employee> findByEmpUuid(UUID empUuid);
|
||||
|
||||
// Login ID로 조회 (로그인 용)
|
||||
Optional<Employee> findByEmpLoginId(String empLoginId);
|
||||
|
||||
// emp_no 로 조회
|
||||
Optional<Employee> findByEmpNo(String empNo);
|
||||
|
||||
// 부서별
|
||||
List<Employee> findByEmpDeptId(Integer empDeptId);
|
||||
|
||||
// Active 직원만 가져오는 경우 필요할 때 사용 가능
|
||||
boolean existsByEmpLoginId(String empLoginId);
|
||||
}
|
||||
|
|
@ -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> {
|
||||
}
|
||||
|
|
@ -0,0 +1,278 @@
|
|||
package com.goi.erp.service;
|
||||
|
||||
import com.goi.erp.dto.EmployeeRequestDto;
|
||||
import com.goi.erp.dto.EmployeeResponseDto;
|
||||
import com.goi.erp.entity.Employee;
|
||||
import com.goi.erp.repository.EmployeeRepository;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional
|
||||
public class EmployeeService {
|
||||
|
||||
private final EmployeeRepository employeeRepository;
|
||||
private final PasswordEncoder passwordEncoder; // 비밀번호 암호화 (auth-service처럼)
|
||||
|
||||
/**
|
||||
* CREATE
|
||||
*/
|
||||
public EmployeeResponseDto createEmployee(EmployeeRequestDto dto) {
|
||||
|
||||
Employee employee = Employee.builder()
|
||||
.empUuid(UUID.randomUUID())
|
||||
.empNo(dto.getEmpNo())
|
||||
.empLoginId(dto.getEmpLoginId())
|
||||
.empLoginPassword(passwordEncoder.encode(dto.getEmpLoginPassword()))
|
||||
.empFirstName(dto.getEmpFirstName())
|
||||
.empMiddleName(dto.getEmpMiddleName())
|
||||
.empLastName(dto.getEmpLastName())
|
||||
.empPreferredFirstName(dto.getEmpPreferredFirstName())
|
||||
.empPreferredLastName(dto.getEmpPreferredLastName())
|
||||
.empStatus(dto.getEmpStatus())
|
||||
.empFulltime(dto.getEmpFulltime())
|
||||
.empEmploymentType(dto.getEmpEmploymentType())
|
||||
.empLeaveStatus(dto.getEmpLeaveStatus())
|
||||
.empOfferAcceptedDate(dto.getEmpOfferAcceptedDate())
|
||||
.empNationality(dto.getEmpNationality())
|
||||
.empCitizenshipStatus(dto.getEmpCitizenshipStatus())
|
||||
.empPassportNo(dto.getEmpPassportNo())
|
||||
.empPassportCountry(dto.getEmpPassportCountry())
|
||||
.empPassportIssueDate(dto.getEmpPassportIssueDate())
|
||||
.empPassportExpiryDate(dto.getEmpPassportExpiryDate())
|
||||
.empVisaType(dto.getEmpVisaType())
|
||||
.empVisaIssueDate(dto.getEmpVisaIssueDate())
|
||||
.empVisaExpiryDate(dto.getEmpVisaExpiryDate())
|
||||
.empVisaCountry(dto.getEmpVisaCountry())
|
||||
.empDateOfBirth(dto.getEmpDateOfBirth())
|
||||
.empSex(dto.getEmpSex())
|
||||
.empSin(dto.getEmpSin())
|
||||
.empAccountNo(dto.getEmpAccountNo())
|
||||
.empDriverLicenseNo(dto.getEmpDriverLicenseNo())
|
||||
.empPersonalEmail(dto.getEmpPersonalEmail())
|
||||
.empPersonalPhone(dto.getEmpPersonalPhone())
|
||||
.empAddress1(dto.getEmpAddress1())
|
||||
.empAddress2(dto.getEmpAddress2())
|
||||
.empPostalCode(dto.getEmpPostalCode())
|
||||
.empCity(dto.getEmpCity())
|
||||
.empProvince(dto.getEmpProvince())
|
||||
.empContractStartDate(dto.getEmpContractStartDate())
|
||||
.empProbationStartDate(dto.getEmpProbationStartDate())
|
||||
.empProbationEndDate(dto.getEmpProbationEndDate())
|
||||
.empProbationStatus(dto.getEmpProbationStatus())
|
||||
.empJobStartDate(dto.getEmpJobStartDate())
|
||||
.empJobEndDate(dto.getEmpJobEndDate())
|
||||
.empTerminationDate(dto.getEmpTerminationDate())
|
||||
.empTerminationReason(dto.getEmpTerminationReason())
|
||||
.empDeptId(dto.getEmpDeptId())
|
||||
.empRate(dto.getEmpRate())
|
||||
.empRateOt(dto.getEmpRateOt())
|
||||
.empRateDot(dto.getEmpRateDot())
|
||||
.empOfficeEmail(dto.getEmpOfficeEmail())
|
||||
.empOfficeMobile(dto.getEmpOfficeMobile())
|
||||
.empOfficePhone(dto.getEmpOfficePhone())
|
||||
.empExtensionNo(dto.getEmpExtensionNo())
|
||||
.build();
|
||||
|
||||
employeeRepository.save(employee);
|
||||
|
||||
return mapToDto(employee);
|
||||
}
|
||||
|
||||
/**
|
||||
* READ - detail
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public EmployeeResponseDto getEmployeeByUuid(UUID empUuid) {
|
||||
Employee employee = employeeRepository.findByEmpUuid(empUuid)
|
||||
.orElseThrow(() -> new RuntimeException("Employee not found"));
|
||||
|
||||
return mapToDto(employee);
|
||||
}
|
||||
|
||||
/**
|
||||
* READ - list
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<EmployeeResponseDto> getAllEmployees() {
|
||||
return employeeRepository.findAll().stream()
|
||||
.map(this::mapToDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* READ - active
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<EmployeeResponseDto> getActiveEmployees() {
|
||||
return employeeRepository.findAll().stream()
|
||||
.filter(e -> "A".equals(e.getEmpStatus()))
|
||||
.map(this::mapToDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* READ - inactive
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<EmployeeResponseDto> getInactiveEmployees() {
|
||||
return employeeRepository.findAll().stream()
|
||||
.filter(e -> "I".equals(e.getEmpStatus()))
|
||||
.map(this::mapToDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* UPDATE
|
||||
*/
|
||||
public EmployeeResponseDto updateEmployee(UUID empUuid, EmployeeRequestDto dto) {
|
||||
|
||||
Employee employee = employeeRepository.findByEmpUuid(empUuid)
|
||||
.orElseThrow(() -> new RuntimeException("Employee not found"));
|
||||
|
||||
// PATCH: 값이 있는 것만 적용
|
||||
if (dto.getEmpNo() != null) employee.setEmpNo(dto.getEmpNo());
|
||||
if (dto.getEmpLoginId() != null) employee.setEmpLoginId(dto.getEmpLoginId());
|
||||
if (dto.getEmpLoginPassword() != null && !dto.getEmpLoginPassword().isEmpty()) employee.setEmpLoginPassword(passwordEncoder.encode(dto.getEmpLoginPassword()));
|
||||
if (dto.getEmpFirstName() != null) employee.setEmpFirstName(dto.getEmpFirstName());
|
||||
if (dto.getEmpMiddleName() != null) employee.setEmpMiddleName(dto.getEmpMiddleName());
|
||||
if (dto.getEmpLastName() != null) employee.setEmpLastName(dto.getEmpLastName());
|
||||
if (dto.getEmpPreferredFirstName() != null) employee.setEmpPreferredFirstName(dto.getEmpPreferredFirstName());
|
||||
if (dto.getEmpPreferredLastName() != null) employee.setEmpPreferredLastName(dto.getEmpPreferredLastName());
|
||||
if (dto.getEmpStatus() != null) employee.setEmpStatus(dto.getEmpStatus());
|
||||
if (dto.getEmpFulltime() != null) employee.setEmpFulltime(dto.getEmpFulltime());
|
||||
if (dto.getEmpEmploymentType() != null) employee.setEmpEmploymentType(dto.getEmpEmploymentType());
|
||||
if (dto.getEmpLeaveStatus() != null) employee.setEmpLeaveStatus(dto.getEmpLeaveStatus());
|
||||
if (dto.getEmpOfferAcceptedDate() != null) employee.setEmpOfferAcceptedDate(dto.getEmpOfferAcceptedDate());
|
||||
if (dto.getEmpNationality() != null) employee.setEmpNationality(dto.getEmpNationality());
|
||||
if (dto.getEmpCitizenshipStatus() != null) employee.setEmpCitizenshipStatus(dto.getEmpCitizenshipStatus());
|
||||
if (dto.getEmpPassportNo() != null) employee.setEmpPassportNo(dto.getEmpPassportNo());
|
||||
if (dto.getEmpPassportCountry() != null) employee.setEmpPassportCountry(dto.getEmpPassportCountry());
|
||||
if (dto.getEmpPassportIssueDate() != null) employee.setEmpPassportIssueDate(dto.getEmpPassportIssueDate());
|
||||
if (dto.getEmpPassportExpiryDate() != null) employee.setEmpPassportExpiryDate(dto.getEmpPassportExpiryDate());
|
||||
if (dto.getEmpVisaType() != null) employee.setEmpVisaType(dto.getEmpVisaType());
|
||||
if (dto.getEmpVisaIssueDate() != null) employee.setEmpVisaIssueDate(dto.getEmpVisaIssueDate());
|
||||
if (dto.getEmpVisaExpiryDate() != null) employee.setEmpVisaExpiryDate(dto.getEmpVisaExpiryDate());
|
||||
if (dto.getEmpVisaCountry() != null) employee.setEmpVisaCountry(dto.getEmpVisaCountry());
|
||||
if (dto.getEmpDateOfBirth() != null) employee.setEmpDateOfBirth(dto.getEmpDateOfBirth());
|
||||
if (dto.getEmpSex() != null) employee.setEmpSex(dto.getEmpSex());
|
||||
if (dto.getEmpSin() != null) employee.setEmpSin(dto.getEmpSin());
|
||||
if (dto.getEmpAccountNo() != null) employee.setEmpAccountNo(dto.getEmpAccountNo());
|
||||
if (dto.getEmpDriverLicenseNo() != null) employee.setEmpDriverLicenseNo(dto.getEmpDriverLicenseNo());
|
||||
if (dto.getEmpPersonalEmail() != null) employee.setEmpPersonalEmail(dto.getEmpPersonalEmail());
|
||||
if (dto.getEmpPersonalPhone() != null) employee.setEmpPersonalPhone(dto.getEmpPersonalPhone());
|
||||
if (dto.getEmpAddress1() != null) employee.setEmpAddress1(dto.getEmpAddress1());
|
||||
if (dto.getEmpAddress2() != null) employee.setEmpAddress2(dto.getEmpAddress2());
|
||||
if (dto.getEmpPostalCode() != null) employee.setEmpPostalCode(dto.getEmpPostalCode());
|
||||
if (dto.getEmpCity() != null) employee.setEmpCity(dto.getEmpCity());
|
||||
if (dto.getEmpProvince() != null) employee.setEmpProvince(dto.getEmpProvince());
|
||||
if (dto.getEmpContractStartDate() != null) employee.setEmpContractStartDate(dto.getEmpContractStartDate());
|
||||
if (dto.getEmpProbationStartDate() != null) employee.setEmpProbationStartDate(dto.getEmpProbationStartDate());
|
||||
if (dto.getEmpProbationEndDate() != null) employee.setEmpProbationEndDate(dto.getEmpProbationEndDate());
|
||||
if (dto.getEmpProbationStatus() != null) employee.setEmpProbationStatus(dto.getEmpProbationStatus());
|
||||
if (dto.getEmpJobStartDate() != null) employee.setEmpJobStartDate(dto.getEmpJobStartDate());
|
||||
if (dto.getEmpJobEndDate() != null) employee.setEmpJobEndDate(dto.getEmpJobEndDate());
|
||||
if (dto.getEmpTerminationDate() != null) employee.setEmpTerminationDate(dto.getEmpTerminationDate());
|
||||
if (dto.getEmpTerminationReason() != null) employee.setEmpTerminationReason(dto.getEmpTerminationReason());
|
||||
if (dto.getEmpDeptId() != null) employee.setEmpDeptId(dto.getEmpDeptId());
|
||||
if (dto.getEmpRate() != null) employee.setEmpRate(dto.getEmpRate());
|
||||
if (dto.getEmpRateOt() != null) employee.setEmpRateOt(dto.getEmpRateOt());
|
||||
if (dto.getEmpRateDot() != null) employee.setEmpRateDot(dto.getEmpRateDot());
|
||||
if (dto.getEmpOfficeEmail() != null) employee.setEmpOfficeEmail(dto.getEmpOfficeEmail());
|
||||
if (dto.getEmpOfficeMobile() != null) employee.setEmpOfficeMobile(dto.getEmpOfficeMobile());
|
||||
if (dto.getEmpOfficePhone() != null) employee.setEmpOfficePhone(dto.getEmpOfficePhone());
|
||||
if (dto.getEmpExtensionNo() != null) employee.setEmpExtensionNo(dto.getEmpExtensionNo());
|
||||
|
||||
return mapToDto(employee);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* INACTIVATE (Soft Delete)
|
||||
* 직원 삭제하지 않고 emp_status = 'I' 로 비활성화
|
||||
*/
|
||||
public EmployeeResponseDto inactivateEmployee(UUID empUuid) {
|
||||
|
||||
Employee employee = employeeRepository.findByEmpUuid(empUuid)
|
||||
.orElseThrow(() -> new RuntimeException("Employee not found"));
|
||||
|
||||
employee.setEmpStatus("I"); // Inactive
|
||||
|
||||
return mapToDto(employee);
|
||||
}
|
||||
|
||||
/**
|
||||
* ENTITY → DTO 변환
|
||||
*/
|
||||
private EmployeeResponseDto mapToDto(Employee e) {
|
||||
EmployeeResponseDto dto = new EmployeeResponseDto();
|
||||
|
||||
dto.setEmpId(e.getEmpId());
|
||||
dto.setEmpUuid(e.getEmpUuid());
|
||||
dto.setEmpNo(e.getEmpNo());
|
||||
dto.setEmpLoginId(e.getEmpLoginId());
|
||||
dto.setEmpFirstName(e.getEmpFirstName());
|
||||
dto.setEmpMiddleName(e.getEmpMiddleName());
|
||||
dto.setEmpLastName(e.getEmpLastName());
|
||||
dto.setEmpPreferredFirstName(e.getEmpPreferredFirstName());
|
||||
dto.setEmpPreferredLastName(e.getEmpPreferredLastName());
|
||||
dto.setEmpStatus(e.getEmpStatus());
|
||||
dto.setEmpFulltime(e.getEmpFulltime());
|
||||
dto.setEmpEmploymentType(e.getEmpEmploymentType());
|
||||
dto.setEmpLeaveStatus(e.getEmpLeaveStatus());
|
||||
dto.setEmpOfferAcceptedDate(e.getEmpOfferAcceptedDate());
|
||||
dto.setEmpCreatedAt(e.getEmpCreatedAt());
|
||||
dto.setEmpUpdatedAt(e.getEmpUpdatedAt());
|
||||
dto.setEmpCreatedBy(e.getEmpCreatedBy());
|
||||
dto.setEmpUpdatedBy(e.getEmpUpdatedBy());
|
||||
dto.setEmpNationality(e.getEmpNationality());
|
||||
dto.setEmpCitizenshipStatus(e.getEmpCitizenshipStatus());
|
||||
dto.setEmpPassportNo(e.getEmpPassportNo());
|
||||
dto.setEmpPassportCountry(e.getEmpPassportCountry());
|
||||
dto.setEmpPassportIssueDate(e.getEmpPassportIssueDate());
|
||||
dto.setEmpPassportExpiryDate(e.getEmpPassportExpiryDate());
|
||||
dto.setEmpVisaType(e.getEmpVisaType());
|
||||
dto.setEmpVisaIssueDate(e.getEmpVisaIssueDate());
|
||||
dto.setEmpVisaExpiryDate(e.getEmpVisaExpiryDate());
|
||||
dto.setEmpVisaCountry(e.getEmpVisaCountry());
|
||||
dto.setEmpDateOfBirth(e.getEmpDateOfBirth());
|
||||
dto.setEmpSex(e.getEmpSex());
|
||||
dto.setEmpSin(e.getEmpSin());
|
||||
dto.setEmpAccountNo(e.getEmpAccountNo());
|
||||
dto.setEmpDriverLicenseNo(e.getEmpDriverLicenseNo());
|
||||
dto.setEmpPersonalEmail(e.getEmpPersonalEmail());
|
||||
dto.setEmpPersonalPhone(e.getEmpPersonalPhone());
|
||||
dto.setEmpAddress1(e.getEmpAddress1());
|
||||
dto.setEmpAddress2(e.getEmpAddress2());
|
||||
dto.setEmpPostalCode(e.getEmpPostalCode());
|
||||
dto.setEmpCity(e.getEmpCity());
|
||||
dto.setEmpProvince(e.getEmpProvince());
|
||||
dto.setEmpContractStartDate(e.getEmpContractStartDate());
|
||||
dto.setEmpProbationStartDate(e.getEmpProbationStartDate());
|
||||
dto.setEmpProbationEndDate(e.getEmpProbationEndDate());
|
||||
dto.setEmpProbationStatus(e.getEmpProbationStatus());
|
||||
dto.setEmpJobStartDate(e.getEmpJobStartDate());
|
||||
dto.setEmpJobEndDate(e.getEmpJobEndDate());
|
||||
dto.setEmpTerminationDate(e.getEmpTerminationDate());
|
||||
dto.setEmpTerminationReason(e.getEmpTerminationReason());
|
||||
dto.setEmpDeptId(e.getEmpDeptId());
|
||||
dto.setEmpRate(e.getEmpRate());
|
||||
dto.setEmpRateOt(e.getEmpRateOt());
|
||||
dto.setEmpRateDot(e.getEmpRateDot());
|
||||
dto.setEmpOfficeEmail(e.getEmpOfficeEmail());
|
||||
dto.setEmpOfficeMobile(e.getEmpOfficeMobile());
|
||||
dto.setEmpOfficePhone(e.getEmpOfficePhone());
|
||||
dto.setEmpExtensionNo(e.getEmpExtensionNo());
|
||||
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
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;
|
||||
|
||||
public PermissionAuthenticationToken(String principal, PermissionSet permissionSet, Collection<? extends GrantedAuthority> authorities) {
|
||||
super(principal, null, authorities);
|
||||
this.permissionSet = permissionSet;
|
||||
}
|
||||
|
||||
public PermissionSet getPermissionSet() {
|
||||
return permissionSet;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
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: 8081
|
||||
servlet:
|
||||
context-path: /hcm-rest-api
|
||||
|
|
@ -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() {
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue