├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── README.md
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── jazzybruno
│ │ └── example
│ │ ├── SpringApplication.java
│ │ └── v1
│ │ ├── config
│ │ ├── SecurityConfig.java
│ │ ├── SwaggerApiDoc.java
│ │ └── WebConfig.java
│ │ ├── controllers
│ │ └── UserController.java
│ │ ├── dto
│ │ ├── requests
│ │ │ ├── CreateUserDTO.java
│ │ │ ├── UpdateRoleDTO.java
│ │ │ └── UserLoginDTO.java
│ │ └── responses
│ │ │ ├── CustomAuthError.java
│ │ │ ├── ErrorResponse.java
│ │ │ ├── LoginResponse.java
│ │ │ ├── Response.java
│ │ │ ├── UserDTO.java
│ │ │ └── UserDTOMapper.java
│ │ ├── enums
│ │ ├── ResponseType.java
│ │ └── Roles.java
│ │ ├── exceptions
│ │ ├── JWTVerificationException.java
│ │ ├── LoginFailedException.java
│ │ └── TokenException.java
│ │ ├── models
│ │ ├── Role.java
│ │ └── User.java
│ │ ├── payload
│ │ └── ApiResponse.java
│ │ ├── repositories
│ │ ├── RoleRepository.java
│ │ └── UserRepository.java
│ │ ├── security
│ │ ├── jwt
│ │ │ ├── JwtAuthFilter.java
│ │ │ ├── JwtUserInfo.java
│ │ │ └── JwtUtils.java
│ │ └── user
│ │ │ ├── UserAuthority.java
│ │ │ ├── UserSecurityDetails.java
│ │ │ └── UserSecurityDetailsService.java
│ │ ├── serviceImpls
│ │ └── UserServiceImpl.java
│ │ ├── services
│ │ └── UserService.java
│ │ └── utils
│ │ └── Hash.java
└── resources
│ ├── application-dev.properties
│ └── application.properties
└── test
└── java
└── com
└── jazzybruno
└── example
└── BoilerplateSwaggerApplicationTests.java
/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jazzybruno/springBoot_bolierplate_with_springSecurity/ce9af2f0d4d2f9b1744e206d60e55dbac7bb91b3/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spring Boot Boiler Plate
2 |
3 | ## A spring boot boiler plate for spring security 6 and swagger!!
4 | ##### Star it [](https://github.com/jazzybruno/springBoot_bolierplate_with_springSecurity.git/) , Fork it [](https://github.com/jazzybruno/springBoot_bolierplate_with_springSecurity.git/fork) , Contribute to it
5 | ### Spring Boot boiler plate containing :
6 | #### 1. Spring Security 6
7 | #### 2. Swagger Api Documentation
8 | #### 3. User Apis preconfigured
9 | #### 4. User Endpoints ( Get All , Ceate , Login , etc)
10 | #### 5. Folder Structure
11 |
12 | ### How to access this boiler plate ang get started
13 |
14 | ##### Step 1 : Clone the boiler plate repository
15 | ```bash
16 | git clone https://github.com/jazzybruno/springBoot_bolierplate_with_springSecurity.git
17 | ```
18 | ##### Step 2 : Go to the cloned repository and delete the existing git folder
19 | ##### Step 3 : Add your own Repository and start working
20 | ```bash
21 | git init
22 | ```
23 | ##### Step 4 : You can edit the configuration of the authorization of the different routes in the security configuration file
24 |
25 | ## Contributing
26 |
27 | We welcome contributions from the community! If you'd like to contribute to this repository, please follow these steps:
28 | 1. Fork the repository
29 | 2. Make your changes
30 | 3. Submit a pull request
31 |
32 |
--------------------------------------------------------------------------------
/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # https://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /usr/local/etc/mavenrc ] ; then
40 | . /usr/local/etc/mavenrc
41 | fi
42 |
43 | if [ -f /etc/mavenrc ] ; then
44 | . /etc/mavenrc
45 | fi
46 |
47 | if [ -f "$HOME/.mavenrc" ] ; then
48 | . "$HOME/.mavenrc"
49 | fi
50 |
51 | fi
52 |
53 | # OS specific support. $var _must_ be set to either true or false.
54 | cygwin=false;
55 | darwin=false;
56 | mingw=false
57 | case "`uname`" in
58 | CYGWIN*) cygwin=true ;;
59 | MINGW*) mingw=true;;
60 | Darwin*) darwin=true
61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
63 | if [ -z "$JAVA_HOME" ]; then
64 | if [ -x "/usr/libexec/java_home" ]; then
65 | export JAVA_HOME="`/usr/libexec/java_home`"
66 | else
67 | export JAVA_HOME="/Library/Java/Home"
68 | fi
69 | fi
70 | ;;
71 | esac
72 |
73 | if [ -z "$JAVA_HOME" ] ; then
74 | if [ -r /etc/gentoo-release ] ; then
75 | JAVA_HOME=`java-config --jre-home`
76 | fi
77 | fi
78 |
79 | if [ -z "$M2_HOME" ] ; then
80 | ## resolve links - $0 may be a link to maven's home
81 | PRG="$0"
82 |
83 | # need this for relative symlinks
84 | while [ -h "$PRG" ] ; do
85 | ls=`ls -ld "$PRG"`
86 | link=`expr "$ls" : '.*-> \(.*\)$'`
87 | if expr "$link" : '/.*' > /dev/null; then
88 | PRG="$link"
89 | else
90 | PRG="`dirname "$PRG"`/$link"
91 | fi
92 | done
93 |
94 | saveddir=`pwd`
95 |
96 | M2_HOME=`dirname "$PRG"`/..
97 |
98 | # make it fully qualified
99 | M2_HOME=`cd "$M2_HOME" && pwd`
100 |
101 | cd "$saveddir"
102 | # echo Using m2 at $M2_HOME
103 | fi
104 |
105 | # For Cygwin, ensure paths are in UNIX format before anything is touched
106 | if $cygwin ; then
107 | [ -n "$M2_HOME" ] &&
108 | M2_HOME=`cygpath --unix "$M2_HOME"`
109 | [ -n "$JAVA_HOME" ] &&
110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
111 | [ -n "$CLASSPATH" ] &&
112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
113 | fi
114 |
115 | # For Mingw, ensure paths are in UNIX format before anything is touched
116 | if $mingw ; then
117 | [ -n "$M2_HOME" ] &&
118 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
119 | [ -n "$JAVA_HOME" ] &&
120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
121 | fi
122 |
123 | if [ -z "$JAVA_HOME" ]; then
124 | javaExecutable="`which javac`"
125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
126 | # readlink(1) is not available as standard on Solaris 10.
127 | readLink=`which readlink`
128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
129 | if $darwin ; then
130 | javaHome="`dirname \"$javaExecutable\"`"
131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
132 | else
133 | javaExecutable="`readlink -f \"$javaExecutable\"`"
134 | fi
135 | javaHome="`dirname \"$javaExecutable\"`"
136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
137 | JAVA_HOME="$javaHome"
138 | export JAVA_HOME
139 | fi
140 | fi
141 | fi
142 |
143 | if [ -z "$JAVACMD" ] ; then
144 | if [ -n "$JAVA_HOME" ] ; then
145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
146 | # IBM's JDK on AIX uses strange locations for the executables
147 | JAVACMD="$JAVA_HOME/jre/sh/java"
148 | else
149 | JAVACMD="$JAVA_HOME/bin/java"
150 | fi
151 | else
152 | JAVACMD="`\\unset -f command; \\command -v java`"
153 | fi
154 | fi
155 |
156 | if [ ! -x "$JAVACMD" ] ; then
157 | echo "Error: JAVA_HOME is not defined correctly." >&2
158 | echo " We cannot execute $JAVACMD" >&2
159 | exit 1
160 | fi
161 |
162 | if [ -z "$JAVA_HOME" ] ; then
163 | echo "Warning: JAVA_HOME environment variable is not set."
164 | fi
165 |
166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
167 |
168 | # traverses directory structure from process work directory to filesystem root
169 | # first directory with .mvn subdirectory is considered project base directory
170 | find_maven_basedir() {
171 |
172 | if [ -z "$1" ]
173 | then
174 | echo "Path not specified to find_maven_basedir"
175 | return 1
176 | fi
177 |
178 | basedir="$1"
179 | wdir="$1"
180 | while [ "$wdir" != '/' ] ; do
181 | if [ -d "$wdir"/.mvn ] ; then
182 | basedir=$wdir
183 | break
184 | fi
185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
186 | if [ -d "${wdir}" ]; then
187 | wdir=`cd "$wdir/.."; pwd`
188 | fi
189 | # end of workaround
190 | done
191 | echo "${basedir}"
192 | }
193 |
194 | # concatenates all lines of a file
195 | concat_lines() {
196 | if [ -f "$1" ]; then
197 | echo "$(tr -s '\n' ' ' < "$1")"
198 | fi
199 | }
200 |
201 | BASE_DIR=`find_maven_basedir "$(pwd)"`
202 | if [ -z "$BASE_DIR" ]; then
203 | exit 1;
204 | fi
205 |
206 | ##########################################################################################
207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
208 | # This allows using the maven wrapper in projects that prohibit checking in binary data.
209 | ##########################################################################################
210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
211 | if [ "$MVNW_VERBOSE" = true ]; then
212 | echo "Found .mvn/wrapper/maven-wrapper.jar"
213 | fi
214 | else
215 | if [ "$MVNW_VERBOSE" = true ]; then
216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
217 | fi
218 | if [ -n "$MVNW_REPOURL" ]; then
219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
220 | else
221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
222 | fi
223 | while IFS="=" read key value; do
224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
225 | esac
226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
227 | if [ "$MVNW_VERBOSE" = true ]; then
228 | echo "Downloading from: $jarUrl"
229 | fi
230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
231 | if $cygwin; then
232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
233 | fi
234 |
235 | if command -v wget > /dev/null; then
236 | if [ "$MVNW_VERBOSE" = true ]; then
237 | echo "Found wget ... using wget"
238 | fi
239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
241 | else
242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
243 | fi
244 | elif command -v curl > /dev/null; then
245 | if [ "$MVNW_VERBOSE" = true ]; then
246 | echo "Found curl ... using curl"
247 | fi
248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
249 | curl -o "$wrapperJarPath" "$jarUrl" -f
250 | else
251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
252 | fi
253 |
254 | else
255 | if [ "$MVNW_VERBOSE" = true ]; then
256 | echo "Falling back to using Java to download"
257 | fi
258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
259 | # For Cygwin, switch paths to Windows format before running javac
260 | if $cygwin; then
261 | javaClass=`cygpath --path --windows "$javaClass"`
262 | fi
263 | if [ -e "$javaClass" ]; then
264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
265 | if [ "$MVNW_VERBOSE" = true ]; then
266 | echo " - Compiling MavenWrapperDownloader.java ..."
267 | fi
268 | # Compiling the Java class
269 | ("$JAVA_HOME/bin/javac" "$javaClass")
270 | fi
271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
272 | # Running the downloader
273 | if [ "$MVNW_VERBOSE" = true ]; then
274 | echo " - Running MavenWrapperDownloader.java ..."
275 | fi
276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
277 | fi
278 | fi
279 | fi
280 | fi
281 | ##########################################################################################
282 | # End of extension
283 | ##########################################################################################
284 |
285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
286 | if [ "$MVNW_VERBOSE" = true ]; then
287 | echo $MAVEN_PROJECTBASEDIR
288 | fi
289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
290 |
291 | # For Cygwin, switch paths to Windows format before running java
292 | if $cygwin; then
293 | [ -n "$M2_HOME" ] &&
294 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
295 | [ -n "$JAVA_HOME" ] &&
296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
297 | [ -n "$CLASSPATH" ] &&
298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
299 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
301 | fi
302 |
303 | # Provide a "standardized" way to retrieve the CLI args that will
304 | # work with both Windows and non-Windows executions.
305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
306 | export MAVEN_CMD_LINE_ARGS
307 |
308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
309 |
310 | exec "$JAVACMD" \
311 | $MAVEN_OPTS \
312 | $MAVEN_DEBUG_OPTS \
313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
314 | "-Dmaven.home=${M2_HOME}" \
315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
317 |
--------------------------------------------------------------------------------
/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM https://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM set title of command window
39 | title %0
40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
42 |
43 | @REM set %HOME% to equivalent of $HOME
44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
45 |
46 | @REM Execute a user defined script before this one
47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
51 | :skipRcPre
52 |
53 | @setlocal
54 |
55 | set ERROR_CODE=0
56 |
57 | @REM To isolate internal variables from possible post scripts, we use another setlocal
58 | @setlocal
59 |
60 | @REM ==== START VALIDATION ====
61 | if not "%JAVA_HOME%" == "" goto OkJHome
62 |
63 | echo.
64 | echo Error: JAVA_HOME not found in your environment. >&2
65 | echo Please set the JAVA_HOME variable in your environment to match the >&2
66 | echo location of your Java installation. >&2
67 | echo.
68 | goto error
69 |
70 | :OkJHome
71 | if exist "%JAVA_HOME%\bin\java.exe" goto init
72 |
73 | echo.
74 | echo Error: JAVA_HOME is set to an invalid directory. >&2
75 | echo JAVA_HOME = "%JAVA_HOME%" >&2
76 | echo Please set the JAVA_HOME variable in your environment to match the >&2
77 | echo location of your Java installation. >&2
78 | echo.
79 | goto error
80 |
81 | @REM ==== END VALIDATION ====
82 |
83 | :init
84 |
85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
86 | @REM Fallback to current working directory if not found.
87 |
88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
90 |
91 | set EXEC_DIR=%CD%
92 | set WDIR=%EXEC_DIR%
93 | :findBaseDir
94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
95 | cd ..
96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
97 | set WDIR=%CD%
98 | goto findBaseDir
99 |
100 | :baseDirFound
101 | set MAVEN_PROJECTBASEDIR=%WDIR%
102 | cd "%EXEC_DIR%"
103 | goto endDetectBaseDir
104 |
105 | :baseDirNotFound
106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
107 | cd "%EXEC_DIR%"
108 |
109 | :endDetectBaseDir
110 |
111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
112 |
113 | @setlocal EnableExtensions EnableDelayedExpansion
114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
116 |
117 | :endReadAdditionalConfig
118 |
119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
122 |
123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
124 |
125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
127 | )
128 |
129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data.
131 | if exist %WRAPPER_JAR% (
132 | if "%MVNW_VERBOSE%" == "true" (
133 | echo Found %WRAPPER_JAR%
134 | )
135 | ) else (
136 | if not "%MVNW_REPOURL%" == "" (
137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
138 | )
139 | if "%MVNW_VERBOSE%" == "true" (
140 | echo Couldn't find %WRAPPER_JAR%, downloading it ...
141 | echo Downloading from: %DOWNLOAD_URL%
142 | )
143 |
144 | powershell -Command "&{"^
145 | "$webclient = new-object System.Net.WebClient;"^
146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
148 | "}"^
149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
150 | "}"
151 | if "%MVNW_VERBOSE%" == "true" (
152 | echo Finished downloading %WRAPPER_JAR%
153 | )
154 | )
155 | @REM End of extension
156 |
157 | @REM Provide a "standardized" way to retrieve the CLI args that will
158 | @REM work with both Windows and non-Windows executions.
159 | set MAVEN_CMD_LINE_ARGS=%*
160 |
161 | %MAVEN_JAVA_EXE% ^
162 | %JVM_CONFIG_MAVEN_PROPS% ^
163 | %MAVEN_OPTS% ^
164 | %MAVEN_DEBUG_OPTS% ^
165 | -classpath %WRAPPER_JAR% ^
166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
168 | if ERRORLEVEL 1 goto error
169 | goto end
170 |
171 | :error
172 | set ERROR_CODE=1
173 |
174 | :end
175 | @endlocal & set ERROR_CODE=%ERROR_CODE%
176 |
177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
181 | :skipRcPost
182 |
183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause
185 |
186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
187 |
188 | cmd /C exit /B %ERROR_CODE%
189 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.7.0
9 |
10 |
11 | rw.pacis_nkubito
12 | boilerplateSwagger
13 | 0.0.1-SNAPSHOT
14 | war
15 | boilerplateSwagger
16 | Boilerplate With Swagger
17 |
18 | 1.8
19 | 2.9.2
20 |
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-web
25 |
26 |
27 | org.apache.poi
28 | poi-ooxml
29 | 4.1.2
30 |
31 |
32 | org.springframework.boot
33 | spring-boot-starter-security
34 |
35 |
36 | io.jsonwebtoken
37 | jjwt
38 | 0.9.1
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-starter-test
43 | test
44 |
45 |
46 | org.springframework.boot
47 | spring-boot-devtools
48 | runtime
49 |
50 |
51 | org.springframework.boot
52 | spring-boot-starter-data-jdbc
53 |
54 |
55 |
56 | com.cloudinary
57 | cloudinary-core
58 | 1.33.0
59 |
60 |
61 | mysql
62 | mysql-connector-java
63 | 8.0.28
64 |
65 |
66 | org.springframework.boot
67 | spring-boot-starter-data-jpa
68 |
69 |
70 | io.springfox
71 | springfox-swagger2
72 | ${springfox.swagger.version}
73 |
74 |
75 |
76 | io.springfox
77 | springfox-swagger-ui
78 | ${springfox.swagger.version}
79 |
80 |
81 | javax.xml.bind
82 | jaxb-api
83 |
84 |
85 | org.projectlombok
86 | lombok
87 | true
88 |
89 |
90 | org.apache.commons
91 | commons-lang3
92 |
93 |
94 |
95 |
96 |
97 |
98 | org.springframework.boot
99 | spring-boot-maven-plugin
100 |
101 |
102 | org.apache.maven.plugins
103 | maven-compiler-plugin
104 |
105 | 16
106 | 16
107 |
108 |
109 |
110 |
111 |
112 |
113 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/SpringApplication.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example;
2 |
3 | import org.springframework.boot.autoconfigure.SpringBootApplication;
4 |
5 | @SpringBootApplication
6 | public class SpringApplication {
7 |
8 | public static void main(String[] args) {
9 | org.springframework.boot.SpringApplication.run(SpringApplication.class, args);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/config/SecurityConfig.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.config;
2 |
3 | import com.jazzybruno.example.v1.dto.responses.CustomAuthError;
4 | import com.jazzybruno.example.v1.security.jwt.JwtAuthFilter;
5 | import com.jazzybruno.example.v1.security.user.UserSecurityDetailsService;
6 | import lombok.RequiredArgsConstructor;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.http.HttpMethod;
9 | import org.springframework.security.authentication.AuthenticationManager;
10 | import org.springframework.security.authentication.AuthenticationProvider;
11 | import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
12 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
15 | import org.springframework.security.config.http.SessionCreationPolicy;
16 | import org.springframework.security.core.userdetails.UserDetailsService;
17 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
18 | import org.springframework.security.crypto.password.PasswordEncoder;
19 | import org.springframework.security.web.SecurityFilterChain;
20 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
21 |
22 | @EnableWebSecurity
23 | @RequiredArgsConstructor
24 | public class SecurityConfig {
25 | private final JwtAuthFilter jwtAuthFilter;
26 | private final UserSecurityDetailsService userSecurityDetailsService;
27 | private final CustomAuthError customAuthError;
28 | @Bean
29 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
30 | http
31 | .csrf().disable()
32 | .exceptionHandling()
33 | .authenticationEntryPoint(customAuthError)
34 | .and()
35 | .authorizeHttpRequests()
36 | .antMatchers(HttpMethod.POST, "/api/v1/users/login" , "/api/v1/users/create")
37 | .permitAll()
38 | .antMatchers(
39 | "/v2/api-docs",
40 | "/configuration/ui",
41 | "/swagger-resources/**",
42 | "/configuration/security",
43 | "/swagger-ui.html",
44 | "/webjars/**"
45 | ).permitAll() // the above are the endpoints to the swagger documentation
46 | .anyRequest().authenticated()
47 | .and()
48 | .sessionManagement()
49 | .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
50 | .and()
51 | .authenticationProvider(authenticationProvider())
52 | .addFilterBefore(jwtAuthFilter , UsernamePasswordAuthenticationFilter.class);
53 | return http.build();
54 | }
55 | @Bean
56 | public AuthenticationProvider authenticationProvider() {
57 | final DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
58 | daoAuthenticationProvider.setUserDetailsService(userDetailsService());
59 | daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
60 | return daoAuthenticationProvider;
61 | }
62 |
63 | @Bean
64 | public PasswordEncoder passwordEncoder() {
65 | return new BCryptPasswordEncoder();
66 | }
67 |
68 | @Bean
69 | public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
70 | return config.getAuthenticationManager();
71 | }
72 |
73 | @Bean
74 | public UserDetailsService userDetailsService(){
75 | return userSecurityDetailsService::loadUserByUsername;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/config/SwaggerApiDoc.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.config;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.beans.factory.annotation.Value;
5 | import org.springframework.context.annotation.Bean;
6 | import org.springframework.context.annotation.Configuration;
7 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
8 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
9 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
11 | import springfox.documentation.builders.ApiInfoBuilder;
12 | import springfox.documentation.builders.PathSelectors;
13 | import springfox.documentation.builders.RequestHandlerSelectors;
14 | import springfox.documentation.service.ApiInfo;
15 | import springfox.documentation.service.ApiKey;
16 | import springfox.documentation.service.AuthorizationScope;
17 | import springfox.documentation.service.SecurityReference;
18 | import springfox.documentation.spi.DocumentationType;
19 | import springfox.documentation.spi.service.contexts.SecurityContext;
20 | import springfox.documentation.spring.web.paths.RelativePathProvider;
21 | import springfox.documentation.spring.web.plugins.Docket;
22 | import springfox.documentation.swagger2.annotations.EnableSwagger2;
23 |
24 | import javax.servlet.ServletContext;
25 | import java.time.LocalDate;
26 | import java.util.Arrays;
27 | import java.util.Collections;
28 | import java.util.Date;
29 | import java.util.List;
30 |
31 | @Configuration
32 | @EnableSwagger2
33 | public class SwaggerApiDoc extends WebMvcConfigurationSupport {
34 |
35 | private final ServletContext servletContext;
36 |
37 | @Autowired
38 | public SwaggerApiDoc(ServletContext servletContext) {
39 | this.servletContext = servletContext;
40 | }
41 |
42 | @Value("${server.host}")
43 | private String host;
44 |
45 | @Value("${swagger.app_name}")
46 | private String appName;
47 |
48 | @Value("${swagger.app_description}")
49 | private String appDescription;
50 |
51 | @Value("${swagger.end_point}")
52 | private String swaggerEndpoint;
53 |
54 | @Value("${swagger.base_controller_path}")
55 | private String baseControllerPath;
56 |
57 | @Override
58 | protected void addResourceHandlers(ResourceHandlerRegistry registry) {
59 | registry.addResourceHandler(swaggerEndpoint).addResourceLocations("classpath:/META-INF/resources/");
60 |
61 | registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
62 | }
63 |
64 | @Bean
65 | public WebMvcConfigurer webMvcConfigurer() {
66 | return new WebMvcConfigurer() {
67 | @Override
68 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
69 | registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
70 | registry.addResourceHandler("/webjars/**")
71 | .addResourceLocations("classpath:/META-INF/resources/webjars/");
72 | }
73 | };
74 | }
75 |
76 | @Bean
77 | public Docket api() {
78 | return new Docket(DocumentationType.SWAGGER_2).directModelSubstitute(LocalDate.class, Date.class)
79 | .pathProvider(new RelativePathProvider(servletContext) {
80 | }).select().apis(RequestHandlerSelectors.basePackage(baseControllerPath))
81 | .paths(PathSelectors.any()).build().apiInfo(apiInfo()).securitySchemes(Arrays.asList(apiKey()))
82 | .securityContexts(Collections.singletonList(securityContext()));
83 | }
84 |
85 | private ApiKey apiKey() {
86 | return new ApiKey("Bearer", "Authorization", "header");
87 | }
88 |
89 | private SecurityContext securityContext() {
90 | return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/.*")).build();
91 | }
92 |
93 | private List defaultAuth() {
94 | final AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
95 | final AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
96 | return Collections.singletonList(new SecurityReference("Bearer", authorizationScopes));
97 | }
98 |
99 | private ApiInfo apiInfo() {
100 | return new ApiInfoBuilder().title(appName).description(appDescription)
101 | .termsOfServiceUrl("http://www.rca.ac.rw/") .version("1.0").build();
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/config/WebConfig.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.config;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 | import org.springframework.web.servlet.config.annotation.CorsRegistry;
5 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
7 |
8 | @Configuration
9 | public class WebConfig implements WebMvcConfigurer {
10 |
11 | @Override
12 | public void addCorsMappings(CorsRegistry registry) {
13 | registry.addMapping("/**").allowedMethods("*");
14 | }
15 |
16 | @Override
17 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
18 | registry.addResourceHandler("/**").addResourceLocations("classpath:/static/").addResourceLocations("classpath:/static");
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/controllers/UserController.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.controllers;
2 |
3 |
4 | import com.jazzybruno.example.v1.dto.requests.CreateUserDTO;
5 | import com.jazzybruno.example.v1.dto.requests.UpdateRoleDTO;
6 | import com.jazzybruno.example.v1.dto.requests.UserLoginDTO;
7 | import com.jazzybruno.example.v1.exceptions.LoginFailedException;
8 | import com.jazzybruno.example.v1.payload.ApiResponse;
9 | import com.jazzybruno.example.v1.serviceImpls.UserServiceImpl;
10 | import lombok.RequiredArgsConstructor;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.security.access.prepost.PreAuthorize;
13 | import org.springframework.security.authentication.BadCredentialsException;
14 | import org.springframework.web.bind.annotation.*;
15 | import org.springframework.web.client.HttpServerErrorException;
16 |
17 | @RestController
18 | @RequestMapping("api/v1/users")
19 | @RequiredArgsConstructor
20 | public class UserController {
21 | private final UserServiceImpl userService;
22 | private final CreateUserDTO createUserDTO;
23 |
24 | @GetMapping
25 | @PreAuthorize("hasAuthority('Admin')")
26 | public ResponseEntity getAllUser() throws Exception{
27 | return userService.getAllUsers();
28 | }
29 | @GetMapping("id/{user_id}")
30 | @PreAuthorize("#user_id == authentication.principal.grantedAuthorities[0].userId or hasAuthority('Admin')")
31 | public ResponseEntity getUserById(@PathVariable Long user_id) throws Exception{
32 | return userService.getUserById(user_id);
33 | }
34 | @PutMapping("update/{user_id}")
35 | @PreAuthorize("#user_id == authentication.principal.grantedAuthorities[0].userId or hasAuthority('Admin')")
36 | public ResponseEntity updateUser(@PathVariable Long user_id , @RequestBody CreateUserDTO createUserDTO) throws Exception{
37 | return userService.updateUser(user_id , createUserDTO);
38 | }
39 | @DeleteMapping("delete/{user_id}")
40 | @PreAuthorize("#user_id == authentication.principal.grantedAuthorities[0].userId or hasAuthority('Admin')")
41 | public ResponseEntity deleteUser(@PathVariable Long user_id) throws Exception{
42 | return userService.deleteUser(user_id);
43 | }
44 |
45 | // Api endpoints which are not authenticated
46 | @PostMapping("/create")
47 | public ResponseEntity createUser(@RequestBody CreateUserDTO createUserDTO) throws Exception{
48 | return userService.createUser(createUserDTO);
49 | }
50 |
51 | @PostMapping("/login")
52 | public ResponseEntity authenticateUser(@RequestBody UserLoginDTO userLoginDTO) throws BadCredentialsException , LoginFailedException {
53 | return userService.authenticateUser(userLoginDTO);
54 | }
55 |
56 | @PutMapping("/role")
57 | @PreAuthorize("hasAuthority('Admin')")
58 | public ResponseEntity updateUserRole(@RequestBody UpdateRoleDTO updateRoleDTO) throws Exception{
59 | return userService.updateUserRole(updateRoleDTO);
60 | }
61 |
62 | @PutMapping("/changePass/{user_id}")
63 | public ResponseEntity updatePassword(@PathVariable Long user_id , @RequestBody String newPassword) throws Exception{
64 | return userService.updatePassword( user_id , newPassword);
65 | }
66 |
67 | public ResponseEntity uploadPhoto(){
68 | return ResponseEntity.ok().body("Function to upload a picture");
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/requests/CreateUserDTO.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.requests;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.NoArgsConstructor;
6 | import lombok.Setter;
7 | import org.springframework.stereotype.Component;
8 |
9 | import javax.management.relation.Role;
10 |
11 | @Getter
12 | @Setter
13 | @NoArgsConstructor
14 | @AllArgsConstructor
15 | @Component
16 | public class CreateUserDTO {
17 | private String email;
18 | private String username;
19 | private String Gender;
20 | private String national_id;
21 | private String password;
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/requests/UpdateRoleDTO.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.requests;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.NoArgsConstructor;
6 | import lombok.Setter;
7 |
8 | @Getter
9 | @Setter
10 | @AllArgsConstructor
11 | @NoArgsConstructor
12 | public class UpdateRoleDTO {
13 | private Long userId;
14 | private Long roleId;
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/requests/UserLoginDTO.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.requests;
2 |
3 | import lombok.Getter;
4 | import lombok.NoArgsConstructor;
5 | import lombok.Setter;
6 |
7 | @Getter
8 | @Setter
9 | @NoArgsConstructor
10 | public class UserLoginDTO {
11 | private String email;
12 | private String password;
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/responses/CustomAuthError.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.responses;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.http.MediaType;
6 | import org.springframework.security.core.AuthenticationException;
7 | import org.springframework.security.web.AuthenticationEntryPoint;
8 | import org.springframework.security.web.authentication.AuthenticationFailureHandler;
9 | import org.springframework.stereotype.Component;
10 |
11 | import javax.servlet.ServletException;
12 | import javax.servlet.http.HttpServletRequest;
13 | import javax.servlet.http.HttpServletResponse;
14 | import java.io.IOException;
15 |
16 | @Component
17 | public class CustomAuthError implements AuthenticationEntryPoint {
18 |
19 | @Override
20 | public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
21 | response.setStatus(HttpStatus.UNAUTHORIZED.value());
22 | response.setContentType(MediaType.APPLICATION_JSON_VALUE);
23 | response.getWriter().write("{ \"error\": \"Unauthorized\" }");
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/responses/ErrorResponse.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.responses;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.NoArgsConstructor;
6 | import lombok.Setter;
7 | import lombok.experimental.Accessors;
8 |
9 | import java.util.List;
10 |
11 | @Getter
12 | @Setter
13 | @AllArgsConstructor
14 | @NoArgsConstructor
15 | @Accessors(chain = true)
16 | public class ErrorResponse {
17 | private String message;
18 | private List details;
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/responses/LoginResponse.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.responses;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.Setter;
6 |
7 | @AllArgsConstructor
8 | @Getter
9 | @Setter
10 | public class LoginResponse {
11 |
12 | public String token;
13 | public UserDTO userData;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/responses/Response.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.responses;
2 |
3 | import com.jazzybruno.example.v1.enums.ResponseType;
4 | import lombok.AllArgsConstructor;
5 | import lombok.Getter;
6 | import lombok.NoArgsConstructor;
7 | import lombok.Setter;
8 | import lombok.experimental.Accessors;
9 |
10 | @Getter
11 | @Setter
12 | @AllArgsConstructor
13 | @NoArgsConstructor
14 | @Accessors(chain = true)
15 | public class Response {
16 | private ResponseType type;
17 | private T payload;
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/responses/UserDTO.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.responses;
2 |
3 | import javax.xml.crypto.Data;
4 | import java.util.Date;
5 |
6 | public record UserDTO(
7 | Long userId,
8 | String email,
9 | String username,
10 | String national_id,
11 | String role,
12 | Date lastLogin
13 | ) {
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/dto/responses/UserDTOMapper.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.dto.responses;
2 |
3 |
4 | import org.springframework.stereotype.Component;
5 | import com.jazzybruno.example.v1.models.User;
6 |
7 | import java.text.SimpleDateFormat;
8 | import java.util.function.Function;
9 |
10 | @Component
11 | public class UserDTOMapper implements Function {
12 | @Override
13 | public UserDTO apply(User user) {
14 | return new UserDTO(
15 | user.getUser_id(),
16 | user.getEmail(),
17 | user.getUsername(),
18 | user.getNational_id(),
19 | user.getRole().roleName,
20 | user.getLastLogin()
21 | );
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/enums/ResponseType.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.enums;
2 |
3 | public enum ResponseType {
4 | SUCCESS , LOGIN_FAILED ,UNAUTHORIZED ,VALIDATION_ERROR ,EXCEPTION ,RESOURCE_NOT_FOUND, DUPLICATE_ENTITY
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/enums/Roles.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.enums;
2 |
3 | public enum Roles {
4 | USER , ADMIN
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/exceptions/JWTVerificationException.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.exceptions;
2 |
3 | public class JWTVerificationException extends RuntimeException {
4 | public JWTVerificationException(String message) {
5 | this(message, null);
6 | }
7 |
8 | public JWTVerificationException(String message, Throwable cause) {
9 | super(message, cause);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/exceptions/LoginFailedException.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.exceptions;
2 |
3 | import com.jazzybruno.example.v1.dto.responses.ErrorResponse;
4 | import com.jazzybruno.example.v1.dto.responses.Response;
5 | import com.jazzybruno.example.v1.enums.ResponseType;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | public class LoginFailedException extends Exception{
13 | private final HttpStatus httpStatus = HttpStatus.UNAUTHORIZED;
14 |
15 | public LoginFailedException(String message){
16 | super(message);
17 | }
18 |
19 | ResponseEntity getResponseEntity(){
20 | List details = new ArrayList<>();
21 | details.add(super.getMessage());
22 | ErrorResponse errorResponse = new ErrorResponse().setMessage("Login Failed").setDetails(details);
23 | Response response = new Response<>();
24 | response.setType(ResponseType.LOGIN_FAILED);
25 | response.setPayload(errorResponse);
26 | return new ResponseEntity(response , HttpStatus.UNAUTHORIZED);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/exceptions/TokenException.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.exceptions;
2 |
3 | import com.jazzybruno.example.v1.dto.responses.ErrorResponse;
4 | import com.jazzybruno.example.v1.dto.responses.Response;
5 | import com.jazzybruno.example.v1.enums.ResponseType;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | public class TokenException extends Exception{
13 | private final HttpStatus httpStatus = HttpStatus.UNAUTHORIZED;
14 |
15 | public TokenException(String message){
16 | super(message);
17 | }
18 |
19 | public ResponseEntity getResponseEntity() {
20 | List details = new ArrayList<>();
21 | details.add(super.getMessage());
22 | ErrorResponse errorResponse = new ErrorResponse().setMessage("You do not have authority to access this resources").setDetails(details);
23 | Response response = new Response<>();
24 | response.setPayload(errorResponse);
25 | response.setType(ResponseType.UNAUTHORIZED);
26 | return new ResponseEntity(response , httpStatus);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/models/Role.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.models;
2 |
3 | import com.sun.istack.NotNull;
4 | import lombok.AllArgsConstructor;
5 | import lombok.NoArgsConstructor;
6 | import lombok.experimental.Accessors;
7 |
8 | import javax.persistence.*;
9 |
10 | @Entity
11 | @Table(name = "roles")
12 | @NoArgsConstructor
13 | @AllArgsConstructor
14 | @Accessors(chain = true)
15 | public class Role {
16 | @Id
17 | @GeneratedValue(strategy = GenerationType.AUTO)
18 | @Column
19 | @NotNull
20 | public Long roleId;
21 | @Column
22 | @NotNull
23 | public String roleName;
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/models/User.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.models;
2 |
3 |
4 | import com.sun.istack.NotNull;
5 | import lombok.AllArgsConstructor;
6 | import lombok.Getter;
7 | import lombok.NoArgsConstructor;
8 | import lombok.Setter;
9 | import lombok.experimental.Accessors;
10 | import org.hibernate.annotations.LazyToOne;
11 |
12 | import javax.persistence.*;
13 | import java.util.Date;
14 |
15 | @Getter
16 | @Setter
17 | @Accessors(chain = true)
18 | @NoArgsConstructor
19 | @AllArgsConstructor
20 | @Entity(name = "users")
21 | public class User {
22 | @Id
23 | @GeneratedValue(strategy = GenerationType.AUTO)
24 | private Long user_id;
25 | @NotNull
26 | private String email;
27 | @NotNull
28 | private String username;
29 | @NotNull
30 | private String national_id;
31 |
32 | @NotNull
33 | @ManyToOne
34 | @JoinColumn(name = "role")
35 | private Role role;
36 |
37 | @Column
38 | private Date lastLogin;
39 |
40 | @Column
41 | @NotNull
42 | private String gender;
43 |
44 | @Column
45 | @NotNull
46 | private String profilePicture;
47 | @NotNull
48 | private String password;
49 |
50 | public User(String email, String username, String national_id, String profilePicture ,String password) {
51 | this.email = email;
52 | this.username = username;
53 | this.national_id = national_id;
54 | this.password = password;
55 | this.profilePicture = profilePicture;
56 | }
57 | }
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/payload/ApiResponse.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.payload;
2 |
3 | import lombok.AllArgsConstructor;
4 |
5 | @AllArgsConstructor
6 | public class ApiResponse {
7 | public boolean success;
8 | public String message;
9 |
10 | public Object data;
11 |
12 | public ApiResponse(boolean success, String message) {
13 | this.success = success;
14 | this.message = message;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/repositories/RoleRepository.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.repositories;
2 |
3 | import com.jazzybruno.example.v1.models.Role;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 |
6 | public interface RoleRepository extends JpaRepository {
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/repositories/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.repositories;
2 |
3 | import com.jazzybruno.example.v1.models.User;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 | import org.springframework.stereotype.Component;
6 |
7 |
8 | import java.util.Optional;
9 |
10 | public interface UserRepository extends JpaRepository {
11 | Optional findUserByEmail(String email);
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/security/jwt/JwtAuthFilter.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.security.jwt;
2 |
3 | import com.fasterxml.jackson.core.JsonProcessingException;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 | import com.jazzybruno.example.v1.exceptions.JWTVerificationException;
6 | import com.jazzybruno.example.v1.exceptions.TokenException;
7 | import com.jazzybruno.example.v1.repositories.UserRepository;
8 | import com.jazzybruno.example.v1.security.user.UserSecurityDetails;
9 | import com.jazzybruno.example.v1.security.user.UserSecurityDetailsService;
10 | import lombok.RequiredArgsConstructor;
11 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
12 | import org.springframework.security.core.context.SecurityContextHolder;
13 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
14 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
15 | import org.springframework.stereotype.Component;
16 | import org.springframework.web.filter.OncePerRequestFilter;
17 |
18 | import javax.servlet.FilterChain;
19 | import javax.servlet.ServletException;
20 | import javax.servlet.http.HttpServletRequest;
21 | import javax.servlet.http.HttpServletResponse;
22 | import java.io.IOException;
23 |
24 | import static org.springframework.http.HttpHeaders.AUTHORIZATION;
25 |
26 | @Component
27 | @RequiredArgsConstructor
28 | public class JwtAuthFilter extends OncePerRequestFilter {
29 | private final UserSecurityDetailsService userSecurityDetailsService;
30 | private final JwtUtils jwtUtils;
31 |
32 | public void throwErrors(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain , Exception e) throws IOException, ServletException {
33 | TokenException exception = new TokenException(e.getMessage());
34 |
35 | // the repsonse type and status
36 | response.setStatus(exception.getResponseEntity().getStatusCodeValue());
37 | response.setContentType("application/json");
38 |
39 | // set a new response object as a json one
40 | ObjectMapper objectMapper = new ObjectMapper();
41 | response.getWriter().write(objectMapper.writeValueAsString(exception.getResponseEntity().getBody()));
42 |
43 | // exit the filter chain
44 | filterChain.doFilter(request, response);
45 | return;
46 | }
47 |
48 | @Override
49 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
50 | final String authHeader = request.getHeader("Authorization");
51 | JwtUserInfo jwtUserInfo = null;
52 | String jwtToken = null;
53 |
54 | if (authHeader == null || !authHeader.startsWith("Bearer")) {
55 | filterChain.doFilter(request, response);
56 | return;
57 | }
58 |
59 | jwtToken = authHeader.substring(7);
60 |
61 | try {
62 | jwtUserInfo = jwtUtils.decodeToken(jwtToken);
63 | } catch (JWTVerificationException e) {
64 | throwErrors(request , response , filterChain , e);
65 | }
66 |
67 | if (jwtUserInfo.getEmail() != null && SecurityContextHolder.getContext().getAuthentication() == null) {
68 |
69 | try {
70 | UserSecurityDetails userSecurityDetails = (UserSecurityDetails) userSecurityDetailsService.loadUserByUsername(jwtUserInfo.getEmail());
71 | if (jwtUtils.isTokenValid(jwtToken, userSecurityDetails)) {
72 | UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
73 | userSecurityDetails, jwtToken, userSecurityDetails.getGrantedAuthorities()
74 | );
75 | authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
76 | SecurityContextHolder.getContext().setAuthentication(authToken);
77 | }
78 | filterChain.doFilter(request, response);
79 | } catch (UsernameNotFoundException e) {
80 | throwErrors(request , response , filterChain , e);
81 | }
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/security/jwt/JwtUserInfo.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.security.jwt;
2 |
3 | import lombok.Getter;
4 | import lombok.NoArgsConstructor;
5 | import lombok.Setter;
6 | import lombok.experimental.Accessors;
7 |
8 | @Getter
9 | @Setter
10 | @Accessors(chain = true)
11 | @NoArgsConstructor
12 | public class JwtUserInfo {
13 | private Long userId;
14 | private String email;
15 | private String role;
16 |
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/security/jwt/JwtUtils.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.security.jwt;
2 |
3 | import com.jazzybruno.example.v1.exceptions.JWTVerificationException;
4 | import com.jazzybruno.example.v1.security.user.UserSecurityDetails;
5 | import io.jsonwebtoken.SignatureAlgorithm;
6 | import org.springframework.beans.factory.annotation.Value;
7 | import org.springframework.security.core.userdetails.UserDetails;
8 |
9 | import java.util.Calendar;
10 | import java.util.Date;
11 | import io.jsonwebtoken.Claims;
12 | import io.jsonwebtoken.Jwts;
13 | import org.springframework.stereotype.Component;
14 |
15 | import java.util.HashMap;
16 | import java.util.Map;
17 | import java.util.concurrent.TimeUnit;
18 | import java.util.function.Function;
19 |
20 | @Component
21 | public class JwtUtils {
22 |
23 | @Value("${jwt.secret}")
24 | private String jwtSecretKey;
25 | private static final String CLAIM_KEY_USER_ID = "userId";
26 | private static final String CLAIM_KEY_EMAIL = "email";
27 | private static final String CLAIM_KEY_ROLE = "role";
28 |
29 | public String extractUsername(String token){
30 | return extractClaim(token , Claims::getSubject);
31 | }
32 |
33 | public Date extractExpiration(String token){
34 | return extractClaim(token , Claims::getExpiration);
35 | }
36 |
37 | public boolean hasClaim(String token , String claimName ){
38 | final Claims claims = extractAllClaims(token);
39 | return claims.get(claimName) != null;
40 | }
41 |
42 | public T extractClaim(String token , Function claimsResolver){
43 | final Claims claims = extractAllClaims(token);
44 | return claimsResolver.apply(claims);
45 | }
46 |
47 | public Claims extractAllClaims(String token) {
48 | return Jwts.parser().setSigningKey(jwtSecretKey).parseClaimsJws(token).getBody();
49 | }
50 |
51 | public Boolean isTokenExpired(String token){
52 | Date expirationDate = extractExpiration(token);
53 | Date currentTime = new Date(System.currentTimeMillis());
54 | if(currentTime.before(expirationDate)){
55 | return false;
56 | }else{
57 | return true;
58 | }
59 | }
60 |
61 | public String createToken(Long userId , String email , String role){
62 |
63 | Calendar calendar = Calendar.getInstance();
64 | calendar.add(Calendar.DATE , 1);
65 |
66 | return Jwts.builder()
67 | .claim(CLAIM_KEY_USER_ID , userId)
68 | .claim(CLAIM_KEY_EMAIL , email)
69 | .claim(CLAIM_KEY_ROLE , role)
70 | .setIssuedAt(new Date(System.currentTimeMillis()))
71 | .setExpiration(calendar.getTime())
72 | .signWith(SignatureAlgorithm.HS256 , jwtSecretKey).compact();
73 | }
74 |
75 | public JwtUserInfo decodeToken(String token) throws JWTVerificationException {
76 | Claims claims = extractAllClaims(token);
77 | Long userId = (long) ( (int) claims.get(CLAIM_KEY_USER_ID));
78 | String email = (String) claims.get(CLAIM_KEY_EMAIL);
79 | String role = (String) claims.get(CLAIM_KEY_ROLE);
80 | return new JwtUserInfo().setEmail(email)
81 | .setRole(role)
82 | .setUserId(userId);
83 | }
84 |
85 | public Boolean isTokenValid(String token , UserSecurityDetails userSecurityDetails){
86 | Claims claims = extractAllClaims(token);
87 | String email = (String) claims.get(CLAIM_KEY_EMAIL);
88 | final String username = email;
89 | return (username.equals(userSecurityDetails.getUsername()) && !isTokenExpired(token));
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/security/user/UserAuthority.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.security.user;
2 |
3 | import org.springframework.security.core.GrantedAuthority;
4 |
5 | public class UserAuthority implements GrantedAuthority {
6 |
7 | public Long userId;
8 | public String authority;
9 |
10 | public UserAuthority(Long userId, String authority) {
11 | this.userId = userId;
12 | this.authority = authority;
13 | }
14 |
15 | public Long getUserId() {
16 | return userId;
17 | }
18 |
19 | @Override
20 | public String getAuthority() {
21 | return authority;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/security/user/UserSecurityDetails.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.security.user;
2 |
3 | import com.jazzybruno.example.v1.models.User;
4 | import org.springframework.security.core.GrantedAuthority;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Collection;
9 | import java.util.List;
10 |
11 | public class UserSecurityDetails implements UserDetails {
12 | public String username;
13 | public String password;
14 | public List grantedAuthorities = new ArrayList<>();
15 |
16 | public UserSecurityDetails(User user){
17 | this.username = user.getEmail();
18 | this.password = user.getPassword();
19 | UserAuthority userAuthority = new UserAuthority(user.getUser_id() , user.getRole().roleName);
20 | grantedAuthorities.add(userAuthority);
21 | }
22 |
23 | public List getGrantedAuthorities() {
24 | return grantedAuthorities;
25 | }
26 |
27 | @Override
28 | public Collection extends GrantedAuthority> getAuthorities() {
29 | return null;
30 | }
31 |
32 | @Override
33 | public String getPassword() {
34 | return null;
35 | }
36 |
37 | @Override
38 | public String getUsername() {
39 | return username;
40 | }
41 |
42 | @Override
43 | public boolean isAccountNonExpired() {
44 | return false;
45 | }
46 |
47 | @Override
48 | public boolean isAccountNonLocked() {
49 | return false;
50 | }
51 |
52 | @Override
53 | public boolean isCredentialsNonExpired() {
54 | return false;
55 | }
56 |
57 | @Override
58 | public boolean isEnabled() {
59 | return false;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/security/user/UserSecurityDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.security.user;
2 |
3 | import com.jazzybruno.example.v1.models.User;
4 | import com.jazzybruno.example.v1.repositories.UserRepository;
5 | import lombok.RequiredArgsConstructor;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.security.core.userdetails.UserDetails;
8 | import org.springframework.security.core.userdetails.UserDetailsService;
9 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
10 | import org.springframework.stereotype.Component;
11 | import org.springframework.stereotype.Service;
12 |
13 | import java.util.Optional;
14 |
15 | @RequiredArgsConstructor
16 | @Component
17 | public class UserSecurityDetailsService implements UserDetailsService {
18 | private final UserRepository userRepository;
19 | public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
20 | Optional userOptional = userRepository.findUserByEmail(email);
21 | if(userOptional.isPresent()){
22 | return new UserSecurityDetails(userOptional.get());
23 | }else{
24 | throw new UsernameNotFoundException("" + email + " was not found");
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/serviceImpls/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.serviceImpls;
2 |
3 | import com.jazzybruno.example.v1.dto.requests.CreateUserDTO;
4 | import com.jazzybruno.example.v1.dto.requests.UpdateRoleDTO;
5 | import com.jazzybruno.example.v1.dto.responses.LoginResponse;
6 | import com.jazzybruno.example.v1.dto.responses.UserDTOMapper;
7 | import com.jazzybruno.example.v1.dto.requests.UserLoginDTO;
8 | import com.jazzybruno.example.v1.exceptions.LoginFailedException;
9 | import com.jazzybruno.example.v1.models.Role;
10 | import com.jazzybruno.example.v1.models.User;
11 | import com.jazzybruno.example.v1.payload.ApiResponse;
12 | import com.jazzybruno.example.v1.repositories.RoleRepository;
13 | import com.jazzybruno.example.v1.repositories.UserRepository;
14 | import com.jazzybruno.example.v1.security.jwt.JwtUtils;
15 | import com.jazzybruno.example.v1.security.user.UserAuthority;
16 | import com.jazzybruno.example.v1.security.user.UserSecurityDetails;
17 | import com.jazzybruno.example.v1.security.user.UserSecurityDetailsService;
18 | import com.jazzybruno.example.v1.services.UserService;
19 | import com.jazzybruno.example.v1.utils.Hash;
20 | import lombok.RequiredArgsConstructor;
21 | import org.springframework.http.ResponseEntity;
22 | import org.springframework.security.access.prepost.PreAuthorize;
23 | import org.springframework.security.authentication.AuthenticationManager;
24 | import org.springframework.security.authentication.BadCredentialsException;
25 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
26 | import org.springframework.security.core.GrantedAuthority;
27 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
28 | import org.springframework.stereotype.Component;
29 | import org.springframework.stereotype.Service;
30 | import org.springframework.transaction.annotation.Transactional;
31 | import org.springframework.web.client.HttpServerErrorException;
32 |
33 | import java.sql.SQLException;
34 | import java.util.Date;
35 | import java.util.List;
36 | import java.util.Optional;
37 | import java.util.stream.Collectors;
38 |
39 | @Component
40 | @Service
41 | @RequiredArgsConstructor
42 | public class UserServiceImpl implements UserService {
43 | private final UserRepository userRepository;
44 | private final UserDTOMapper userDTOMapper;
45 | private final RoleRepository roleRepository;
46 | private final AuthenticationManager authenticationManager;
47 | private final UserSecurityDetailsService userSecurityDetailsService;
48 | private final JwtUtils jwtUtils;
49 |
50 | @PreAuthorize("hasAuthority('Admin')")
51 | public ResponseEntity getAllUsers() throws Exception{
52 | try {
53 | List users = userRepository.findAll();
54 | return ResponseEntity.ok().body(new ApiResponse(
55 | true,
56 | "Successfully fetched the users",
57 | users.stream().map(userDTOMapper).collect(Collectors.toList())
58 | ));
59 | }catch (Exception e){
60 | return ResponseEntity.status(500).body(new ApiResponse(
61 | false,
62 | "Failed to fetch the users"
63 | ));
64 | }
65 | }
66 |
67 | @PreAuthorize("hasAuthority('Admin') or #user_id == authentication.principal.grantedAuthorities[0].userId")
68 | public ResponseEntity getUserById(Long user_id) throws Exception{
69 | if(userRepository.existsById(user_id)){
70 | try {
71 | Optional user = userRepository.findById(user_id);
72 | return ResponseEntity.ok().body(new ApiResponse(
73 | true,
74 | "Successfully fetched the users",
75 | user.map(userDTOMapper)
76 | ));
77 | }catch (Exception e){
78 | return ResponseEntity.status(500).body(new ApiResponse(
79 | false,
80 | "Failed to fetch the user"
81 | ));
82 | }
83 | }else{
84 | return ResponseEntity.status(404).body(new ApiResponse(
85 | false,
86 | "The user with the id:" + user_id + " does not exist"
87 | ));
88 | }
89 | }
90 |
91 | public ResponseEntity createUser(CreateUserDTO createUserDTO) throws Exception{
92 | Optional user1 = userRepository.findUserByEmail(createUserDTO.getEmail());
93 | if(!user1.isPresent()){
94 | User user = new User(
95 | createUserDTO.getEmail(),
96 | createUserDTO.getUsername(),
97 | createUserDTO.getNational_id(),
98 | createUserDTO.getGender(),
99 | createUserDTO.getPassword()
100 | );
101 |
102 | Long id = 4l;
103 | Optional roleOptional = roleRepository.findById(id);
104 | user.setRole(roleOptional.get());
105 |
106 | // setting a default avatar
107 | if(user.getGender().equals("Male")){
108 | user.setGender("https://www.google.com/imgres?imgurl=https%3A%2F%2Fus.123rf.com%2F450wm%2Fyupiramos%2Fyupiramos1610%2Fyupiramos161007352%2F64369849-young-man-avatar-isolated-icon-vector-illustration-design.jpg&tbnid=ilUgygO9TcHl4M&vet=12ahUKEwj5x5G_oZv-AhVlmycCHTAsBCkQMygKegUIARDdAQ..i&imgrefurl=https%3A%2F%2Fwww.123rf.com%2Fphoto_64369849_young-man-avatar-isolated-icon-vector-illustration-design.html&docid=_AAMeHi1dhj_1M&w=450&h=450&q=a%20man%20avatar&ved=2ahUKEwj5x5G_oZv-AhVlmycCHTAsBCkQMygKegUIARDdAQ");
109 | }else{
110 | user.setGender(" data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHYAAAB/CAMAAAANdsbrAAAA9lBMVEX////d5u0dGDjYjGgREiQAAAC/v7/IeViyYUTj6/DekGrbjmkbFjcaFDYODyIAACcAACoAACIAADMAABQACTXOfFn29vcLAC6CgIsAABoAAB0NEDbQgmAAABe5aUu/cFGamaFoRUjOhmUAAAjd3OBsa3dUU2Gka1l2TUvCfmFELz+IWVApHjoxIjqybFO+akR+Rj6mW0NdNDlxPz2ytb7Wu7LUxsXJloTM0dnJkHl1dX49PkhKSlRfX2tNS16op64sKkGVYlQ5NU1XOkN2VVZaRlP008X/8erpvqzlqI2ZcGfZqZWYXEzNpJe7gGzv2dAeHi4uLzqosug1AAAGcElEQVRoge2ZaXPaSBCGsQALCQ3ikEAwHAIjQOKKEx9EIGOb3U2yTnbh//+ZbQ3otF0VcGN/WN7CBZZceui3e3oOJxInnXTSSSchSuh2u+V3Jc50p5C+KJUu0hd3+ux9mF1tJOcrErcVzcsjrXt8qEFl4jG3IjI1jgsu6/l8lMkk5fP6EdPc7dVegDJwrXe0gGe08jLUVYUcqbbOa+R1KqS4dn4M6qwQp9I49wjxlivPqO04VxbQsb14Xmm7r8Tze4ddz8tGDCFRUxzFDajpuFSBxAhS8UEU+8X4eJJxh5Gdjz5eUfpiMin2aSy9FQeT2qWRsEhx0AEqcE0rml+pgDmKtEiwimWK2SRTNtkuHi3c8n04s0o7uYOygAdK2AmJ4mX3XA5TB2IyLHEY4co6GtYJjdniMEoF7kPYZyKhYeUgnHisjNsPcwtYLs8Cj6n1nBqLN68jYZd+HUu0k30BC/kNuLSHhLX91LIm8SI3NC3UkLCP3vChq1eoMIAtn5tGSu6FZzExX7SYYU1/YVe4QqGW057FMHZE9yWG6SJTNihnpJrqlnYjcgz1NBxTzhpM/D4ldvrt8Wg8gHbppbeioWDPa8xgDqa6TnswHLYtRbE6O2/7RWW0gouDfrZDJMmtgoqBgr0quJFaFILtMEuTphkk2TQ7zOWO2yXHK9eVOxTsUuYkadJyu2IW5DqbDZKbFYMrSlsFp8k9ytJGB+yYV4vw3I7Zb98XyR9qqKL6VpH++ck03clooP5UOInDwhJLVR8gnk7eFh5J/uomCPYWLsjLWQFuZ82f6gSwBAULJpOVytdZbH8JHJWX34JovycoLeiJLGskLR6wBB+bzP74uz34EW4U7oWnXei8i5UqKFioZDB5h03Gu0XkAo8YLYxbyeJ5/rW+GKgO2CJWbqFLQSX/HlZ9gGhxKlm4cMftb2LdcfuIsyWBqUD5GST3dfG8ahGOIq1Z0+4+6/ewk5GE1ZPd+VYavZjcaEmDx9Ck0LDuxEeHKh9jbH9C36HOPEbDuuckEu2rfDi4Tr2TrEd877R4NuVWbBzs9kyoqHAvLxt3EgfFIpvosbDekZvyEFrBZd1XJPzR7s+wsBzxVjV+YqfTzFZTbw6ESZ5DXdQkJG/Bquz2P1nz+tc/E5B5e/0UDxYfK3nZVc1/YUVZLie+PaleZv39NTo2WJ/zU/7p+vr71+l0l2kz2G3iY7mitxuB7LryBq4Y+hssLBc8UlL8NSPMcv64FVehoxMsbCW0W2dr9GdDdhje4GJhI0fIdPWMK0aP47DGbfQQWVnFZgCgSsfAlriI/J2I3yeiZ3FY2HQUy9FMGNuMnwBizUAxLLGmmZZndD0ztchRsOUYln6CXtysw4YoWW/Bx0+xc0ekRY1wEXmqxF1uZ4Fmc/t+yUnHwHajJUU/Z2L6HA2X4mw0Z9ETbHIZx15Gk4u0YGW7eV/Klzg1k/kSaRdkhLP1KoQdtJrPsU0rbLMk4exvQ4fJhGvxfAzc5PkWF/Y5j4LVgvNVQicqLJj5ZjMMhc3AhIa4DZTzMKMSxNpnVFctJu83tR+Kt4SC7XmJq4wnPjUudTL2v10V4/8F5V03kEqOOX2NyvNT0ynt2kZhiYFlhUzk0ZUgXL8GnprXgnA1kpnTeYx5fgZNiuQl7Uw4A93c8nHydGre3rj3hDONyxOkmW9ZIIV7bcagrro3v76a/HQn3vz666br3RNm2n2BoDRlu3C3DKA7dPdmp243ekeYLR8rCG2qrENOz/YQ5Nh+6wjaj+iTgf2GQA9BBjrQ6TdSD+S+mXoY96CsRnVIgt9OPTvbn4rg8SEuI3h8iMsY1P1dRvF4f5dRPN7f5Q/C4lD3Tu7/CotUyPuW8gdhkQp531I+Yd8Di6a9sCeddNJJ/3Odf4gS6Q9RIhVVLpfbvqdyqSMKsLl1NVV1cblqrrFJpaqNXLW6rs2PjK325s5ivnDsuTO3l/Zyrm1sQzec9eFPhe8NMVSrDQinBBHBR/jcKJVYSFtsbuPYht3bOM7CXmu6pi2u7HWZ3T2U6j4LIlnYvcXcXs/nix58NmxbM+y5YTQYNlW1F26kDmhu6xq89J6uNQ7HplK2YRiOtrDhXVs4htbT5rbjQHDwRTa5LRaSu9ms5+s1XJhDijcl+LR5C9U11S2VHHjKasatnNzWX1azrJLZtRwrYvaTynkFfSzFB9A76T/ZndRU112heQAAAABJRU5ErkJggg==");
111 | }
112 | Hash hash = new Hash();
113 | user.setPassword(hash.hashPassword(user.getPassword()));
114 | user.setLastLogin(null);
115 | try {
116 | userRepository.save(user);
117 | return ResponseEntity.ok().body(new ApiResponse(
118 | true,
119 | "Successfully saved the user",
120 | user
121 | ));
122 | }catch (HttpServerErrorException.InternalServerError e){
123 | return ResponseEntity.status(500).body(new ApiResponse(
124 | false,
125 | "Failed to create the user"
126 | ));
127 | }
128 | }else{
129 | return ResponseEntity.status(404).body(new ApiResponse(
130 | false,
131 | "The user with the email:" + createUserDTO.getEmail() + " already exists"
132 | ));
133 | }
134 | }
135 |
136 | public void updateUserMapper(Optional user, CreateUserDTO createUserDTO){
137 | user.get().setEmail(createUserDTO.getEmail());
138 | user.get().setUsername(createUserDTO.getUsername());
139 | user.get().setNational_id(createUserDTO.getNational_id());
140 | user.get().setPassword(createUserDTO.getPassword());
141 | }
142 |
143 | @PreAuthorize("hasAuthority('Admin') or #user_id == authentication.principal.grantedAuthorities[0].userId")
144 | @Transactional
145 | public ResponseEntity updateUser(Long user_id , CreateUserDTO createUserDTO) throws Exception {
146 | if (userRepository.existsById(user_id)) {
147 | Optional user = userRepository.findById(user_id);
148 | updateUserMapper(user, createUserDTO);
149 | return ResponseEntity.ok().body(new ApiResponse(
150 | true,
151 | "Successfully updated the user",
152 | user.map(userDTOMapper)
153 | ));
154 | } else {
155 | return ResponseEntity.status(404).body(new ApiResponse(
156 | false,
157 | "The user with the id:" + user_id + " does not exist"
158 | ));
159 | }
160 | }
161 |
162 | @PreAuthorize("hasAuthority('Admin') or #user_id == authentication.principal.grantedAuthorities[0].userId")
163 | public ResponseEntity deleteUser(Long user_id) throws Exception{
164 | if (userRepository.existsById(user_id)) {
165 | Optional user = userRepository.findById(user_id);
166 | userRepository.deleteById(user_id);
167 | return ResponseEntity.ok().body(new ApiResponse(
168 | true,
169 | "Successfully deleted the user",
170 | user.map(userDTOMapper)
171 | ));
172 | }else {
173 | return ResponseEntity.status(404).body(new ApiResponse(
174 | false,
175 | "The user with the id:" + user_id + " does not exist"
176 | ));
177 | }
178 | }
179 |
180 | @Override
181 | public ResponseEntity authenticateUser(UserLoginDTO userLoginDTO) throws BadCredentialsException , LoginFailedException{
182 | Optional user = userRepository.findUserByEmail(userLoginDTO.getEmail());
183 | if(user.isPresent()){
184 | Hash hash = new Hash();
185 | if(hash.isTheSame(userLoginDTO.getPassword() , user.get().getPassword())){
186 |
187 | // do the login stuff as usual
188 | UserSecurityDetails userSecurityDetails = (UserSecurityDetails) userSecurityDetailsService.loadUserByUsername(userLoginDTO.getEmail());
189 | List grantedAuthorities = userSecurityDetails.grantedAuthorities;
190 | UserAuthority userAuthority = (UserAuthority) grantedAuthorities.get(0);
191 | String role = userAuthority.getAuthority();
192 | //updating the last login information
193 | User userObject = user.get();
194 | userObject.setLastLogin(new Date());
195 | userRepository.save(userObject);
196 | // Todo Add the last login parameter to the table and update it here to keep track of
197 | // the login userSecurityDetails
198 | String token = jwtUtils.createToken(user.get().getUser_id(), userLoginDTO.getEmail() , role);
199 | return ResponseEntity.ok().body(new ApiResponse(true , "Success in login" , new LoginResponse(token , user.map(userDTOMapper).get())));
200 | }else{
201 | return ResponseEntity.status(401).body(new ApiResponse(false , "Failed to Login" , new LoginFailedException("Incorrect Email or password").getMessage()));
202 | }
203 | }else{
204 | return ResponseEntity.status(401).body(new ApiResponse(false , "Failed to login" , new LoginFailedException("User does not exist!!").getMessage()));
205 | }
206 | }
207 |
208 |
209 |
210 | @PreAuthorize("hasAuthority('Admin')")
211 | @Transactional
212 | public ResponseEntity updateUserRole(UpdateRoleDTO updateRoleDTO) throws Exception{
213 | if(userRepository.existsById(updateRoleDTO.getUserId())){
214 | Optional user = userRepository.findById(updateRoleDTO.getUserId());
215 | if(roleRepository.existsById(updateRoleDTO.getRoleId())){
216 | Role role = roleRepository.findById(updateRoleDTO.getRoleId()).get();
217 | user.get().setRole(role);
218 | return ResponseEntity.ok().body(new ApiResponse(
219 | true,
220 | "Successfully updated the user role",
221 | user.map(userDTOMapper)
222 | ));
223 | }else{
224 | return ResponseEntity.status(404).body(new ApiResponse(
225 | false,
226 | "The role with the id:" + updateRoleDTO.getRoleId() + " does not exist try 1,2,3,4"
227 | ));
228 | }
229 | }else{
230 | return ResponseEntity.status(404).body(new ApiResponse(
231 | false,
232 | "The user with the id:" + updateRoleDTO.getUserId() + " does not exist"
233 | ));
234 | }
235 | }
236 |
237 | public ResponseEntity updatePassword(Long user_id , String newPassword) throws Exception{
238 | try {
239 | Optional optionalUser = userRepository.findById(user_id);
240 | if(optionalUser.isPresent()){
241 | Hash hash = new Hash();
242 | String hashedPassword = hash.hashPassword(newPassword);
243 | optionalUser.get().setPassword(hashedPassword);
244 | return ResponseEntity.status(200).body(new ApiResponse(
245 | true,
246 | "Password was reset successfully"
247 | ));
248 | }else{
249 | return ResponseEntity.status(404).body(new ApiResponse(
250 | false,
251 | "The user with the id:" + user_id + " does not exist"
252 | ));
253 | }
254 | }catch (RuntimeException e){
255 | return ResponseEntity.status(500).body(new ApiResponse(
256 | false,
257 | "Failed!!"
258 | ));
259 | }
260 | }
261 |
262 | }
263 |
264 |
265 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/services/UserService.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.services;
2 |
3 |
4 | import com.jazzybruno.example.v1.dto.requests.CreateUserDTO;
5 | import com.jazzybruno.example.v1.dto.requests.UpdateRoleDTO;
6 | import com.jazzybruno.example.v1.dto.requests.UserLoginDTO;
7 | import com.jazzybruno.example.v1.payload.ApiResponse;
8 | import org.springframework.http.ResponseEntity;
9 | import org.springframework.web.bind.annotation.RequestBody;
10 |
11 | public interface UserService {
12 | public ResponseEntity getAllUsers() throws Exception;
13 | public ResponseEntity getUserById(Long user_id) throws Exception;
14 | public ResponseEntity createUser(CreateUserDTO createUserDTO) throws Exception;
15 | public ResponseEntity updateUser(Long user_id , CreateUserDTO createUserDTO) throws Exception;
16 | ResponseEntity deleteUser(Long user_id) throws Exception;
17 | ResponseEntity authenticateUser(UserLoginDTO userLoginDTO) throws Exception;
18 | ResponseEntity updateUserRole(UpdateRoleDTO updateRoleDTO) throws Exception;
19 | ResponseEntity updatePassword( Long user_id , String newPassword) throws Exception;
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/jazzybruno/example/v1/utils/Hash.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example.v1.utils;
2 |
3 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
4 |
5 | public class Hash {
6 | private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
7 |
8 | public String hashPassword(String password){
9 | return bCryptPasswordEncoder.encode(password);
10 | }
11 | public boolean isTheSame(String rawPassword , String savedPassword){
12 | return bCryptPasswordEncoder.matches(rawPassword , savedPassword);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/resources/application-dev.properties:
--------------------------------------------------------------------------------
1 | server.host=localhost:8000
2 | server.port=8000
3 |
4 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.profiles.active=dev
2 |
3 | jwt.secret=${NX_JWT_SECRET:oX4E3yhCO7f9ysD@by6MMR_@YeNRwP}
4 | jwt.expiresIn=86400000
5 |
6 |
7 | spring.mvc.async.request-timeout=1000000ms
8 | server.tomcat.connection-timeout=1000000ms
9 |
10 | #swagger
11 | swagger.app_name=Spring Boot Boilerplate
12 | swagger.app_description=Spring Boot Boilerplate with spring security version 6 and swagger
13 | swagger.end_point=/swagger-ui.html
14 | swagger.base_controller_path=com.jazzybruno.example.v1.controllers
15 |
16 | server.session.timeout=60
17 | spring.servlet.multipart.max-file-size=500MB
18 | spring.servlet.multipart.max-request-size=500MB
19 | logging.level.root=INFO
20 | logging.level.org.springframework.web=INFO
21 | logging.level.org.hibernate=INFO
22 |
23 | #the database configurations
24 | spring.datasource.url=jdbc:mysql://localhost:3306/plate
25 | spring.datasource.username=bruno
26 | spring.datasource.password=Bruno@1980
27 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
28 | spring.jpa.properties.hibernate.format_sql=true
29 | spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
30 | server.error.whitelabel.enabled=false
31 | spring.main.allow-bean-definition-overriding=true
32 | spring.jpa.hibernate.ddl-auto=update
33 |
34 | spring.jpa.database=mysql
35 |
36 | spring.devtools.restart.enabled=true
37 |
--------------------------------------------------------------------------------
/src/test/java/com/jazzybruno/example/BoilerplateSwaggerApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.jazzybruno.example;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class BoilerplateSwaggerApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------