├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── README.md
├── com.springboilerplate.app.user.User
├── segments_14
└── write.lock
├── com.springboilerplate.model.User
├── segments_2b
└── write.lock
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── springboilerplate
│ │ ├── SpringBoilerplateApplication.java
│ │ ├── app
│ │ ├── auth
│ │ │ ├── AccountCredentials.java
│ │ │ ├── AuthController.java
│ │ │ └── JwtAuthenticationResponse.java
│ │ ├── passwordRestToken
│ │ │ ├── PasswordDto.java
│ │ │ ├── PasswordResetToken.java
│ │ │ ├── PasswordResetTokenController.java
│ │ │ ├── PasswordResetTokenRepository.java
│ │ │ ├── PasswordResetTokenService.java
│ │ │ └── PasswordResetTokenServiceImpl.java
│ │ ├── role
│ │ │ ├── Role.java
│ │ │ ├── RoleRepository.java
│ │ │ └── RoleType.java
│ │ ├── search
│ │ │ ├── HibernateSearchService.java
│ │ │ └── UserSearchService.java
│ │ ├── user
│ │ │ ├── User.java
│ │ │ ├── UserController.java
│ │ │ ├── UserDto.java
│ │ │ ├── UserDtoMapper.java
│ │ │ ├── UserRepository.java
│ │ │ ├── UserService.java
│ │ │ └── UserServiceImpl.java
│ │ └── userRole
│ │ │ ├── UserRole.java
│ │ │ └── UserRoleRepository.java
│ │ ├── config
│ │ ├── HibernateSearchConfig.java
│ │ ├── MailConfig.java
│ │ ├── MethodSecurityConfig.java
│ │ ├── ModelMapperConfig.java
│ │ ├── ObjectMapperConfig.java
│ │ ├── SwaggerConfig.java
│ │ ├── WebMvcConfig.java
│ │ └── WebSecurityConfig.java
│ │ ├── exceptions
│ │ ├── ApiError.java
│ │ ├── CentralizedExceptionHandler.java
│ │ ├── ExpiredTokenException.java
│ │ ├── InvalidPasswordResetToken.java
│ │ ├── InvalidTokenException.java
│ │ ├── NoTokenException.java
│ │ ├── RoleDoesNotExistException.java
│ │ └── SendingTokenException.java
│ │ ├── helper
│ │ ├── AsyncMailer.java
│ │ ├── MailData.java
│ │ ├── MailService.java
│ │ ├── MailServiceImpl.java
│ │ └── SecurityHelper.java
│ │ ├── security
│ │ ├── CustomUserService.java
│ │ ├── JwtAuthenticationEntryPoint.java
│ │ ├── JwtAuthorizationTokenFilter.java
│ │ ├── JwtTokenUtil.java
│ │ └── JwtUserDetailsService.java
│ │ └── utils
│ │ ├── DbSeed.java
│ │ ├── JsonUtils.java
│ │ └── SecurityUtils.java
└── resources
│ ├── application.properties
│ └── db
│ └── migration
│ └── V1_0__init.sql
└── test
├── java
└── com
│ └── springboilerplate
│ ├── app
│ ├── auth
│ │ └── AuthControllerTest.java
│ ├── passwordResetToken
│ │ ├── PasswordResetTokenMocks.java
│ │ ├── PasswordResetTokenRepositoryTest.java
│ │ ├── PasswordResetTokenServiceImplTest.java
│ │ └── PasswordResetTokenStubs.java
│ ├── role
│ │ ├── RoleMocks.java
│ │ ├── RoleRepositoryTest.java
│ │ └── RoleStubs.java
│ ├── search
│ │ └── UserSearchServiceTest.java
│ ├── user
│ │ ├── EnvironmentMocks.java
│ │ ├── MailServiceMocks.java
│ │ ├── UserMocks.java
│ │ ├── UserRepositoryTest.java
│ │ ├── UserServiceImplTest.java
│ │ └── UserStubs.java
│ └── userRole
│ │ ├── UserRoleRepositoryTest.java
│ │ └── UserRoleStubs.java
│ ├── dtoMapper
│ ├── MapperMocks.java
│ └── UserDtoMapperTest.java
│ ├── helper
│ └── MailServiceImplTest.java
│ ├── mocks
│ └── DataGenerator.java
│ └── security
│ ├── CustomUserDetailsServiceTest.java
│ ├── JwtTokenUtilTest.java
│ ├── SecurityHelperMocks.java
│ └── UserDetailsStub.java
└── resources
└── application.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 |
12 | ### IntelliJ IDEA ###
13 | .idea
14 | *.iws
15 | *.iml
16 | *.ipr
17 |
18 | ### NetBeans ###
19 | nbproject/private/
20 | build/
21 | nbbuild/
22 | dist/
23 | nbdist/
24 | .nb-gradle/
25 |
26 | #Hibernate search's indexes.
27 | com.springboilerplate.springboilerplate.app.user.User
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/patrick-emmanuel/spring-boot-boilerplate/12f3c81043f582260f790fea445adba2f8476efe/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Spring Boot Boilerplate
2 | A project to bootstrap a spring boot app with user authentication with a database, and test samples.
3 |
4 | # Worthy Mention
5 | JWT implementation inspired by [szerhusenBC](https://github.com/szerhusenBC/jwt-spring-security-demo).
6 |
--------------------------------------------------------------------------------
/com.springboilerplate.app.user.User/segments_14:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/patrick-emmanuel/spring-boot-boilerplate/12f3c81043f582260f790fea445adba2f8476efe/com.springboilerplate.app.user.User/segments_14
--------------------------------------------------------------------------------
/com.springboilerplate.app.user.User/write.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/patrick-emmanuel/spring-boot-boilerplate/12f3c81043f582260f790fea445adba2f8476efe/com.springboilerplate.app.user.User/write.lock
--------------------------------------------------------------------------------
/com.springboilerplate.model.User/segments_2b:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/patrick-emmanuel/spring-boot-boilerplate/12f3c81043f582260f790fea445adba2f8476efe/com.springboilerplate.model.User/segments_2b
--------------------------------------------------------------------------------
/com.springboilerplate.model.User/write.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/patrick-emmanuel/spring-boot-boilerplate/12f3c81043f582260f790fea445adba2f8476efe/com.springboilerplate.model.User/write.lock
--------------------------------------------------------------------------------
/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 | # http://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 | # Maven2 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 /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Migwn, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | # TODO classpath?
118 | fi
119 |
120 | if [ -z "$JAVA_HOME" ]; then
121 | javaExecutable="`which javac`"
122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123 | # readlink(1) is not available as standard on Solaris 10.
124 | readLink=`which readlink`
125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126 | if $darwin ; then
127 | javaHome="`dirname \"$javaExecutable\"`"
128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129 | else
130 | javaExecutable="`readlink -f \"$javaExecutable\"`"
131 | fi
132 | javaHome="`dirname \"$javaExecutable\"`"
133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134 | JAVA_HOME="$javaHome"
135 | export JAVA_HOME
136 | fi
137 | fi
138 | fi
139 |
140 | if [ -z "$JAVACMD" ] ; then
141 | if [ -n "$JAVA_HOME" ] ; then
142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143 | # IBM's JDK on AIX uses strange locations for the executables
144 | JAVACMD="$JAVA_HOME/jre/sh/java"
145 | else
146 | JAVACMD="$JAVA_HOME/bin/java"
147 | fi
148 | else
149 | JAVACMD="`which java`"
150 | fi
151 | fi
152 |
153 | if [ ! -x "$JAVACMD" ] ; then
154 | echo "Error: JAVA_HOME is not defined correctly." >&2
155 | echo " We cannot execute $JAVACMD" >&2
156 | exit 1
157 | fi
158 |
159 | if [ -z "$JAVA_HOME" ] ; then
160 | echo "Warning: JAVA_HOME environment variable is not set."
161 | fi
162 |
163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164 |
165 | # traverses directory structure from process work directory to filesystem root
166 | # first directory with .mvn subdirectory is considered project base directory
167 | find_maven_basedir() {
168 |
169 | if [ -z "$1" ]
170 | then
171 | echo "Path not specified to find_maven_basedir"
172 | return 1
173 | fi
174 |
175 | basedir="$1"
176 | wdir="$1"
177 | while [ "$wdir" != '/' ] ; do
178 | if [ -d "$wdir"/.mvn ] ; then
179 | basedir=$wdir
180 | break
181 | fi
182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183 | if [ -d "${wdir}" ]; then
184 | wdir=`cd "$wdir/.."; pwd`
185 | fi
186 | # end of workaround
187 | done
188 | echo "${basedir}"
189 | }
190 |
191 | # concatenates all lines of a file
192 | concat_lines() {
193 | if [ -f "$1" ]; then
194 | echo "$(tr -s '\n' ' ' < "$1")"
195 | fi
196 | }
197 |
198 | BASE_DIR=`find_maven_basedir "$(pwd)"`
199 | if [ -z "$BASE_DIR" ]; then
200 | exit 1;
201 | fi
202 |
203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
204 | echo $MAVEN_PROJECTBASEDIR
205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
206 |
207 | # For Cygwin, switch paths to Windows format before running java
208 | if $cygwin; then
209 | [ -n "$M2_HOME" ] &&
210 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
211 | [ -n "$JAVA_HOME" ] &&
212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
213 | [ -n "$CLASSPATH" ] &&
214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
215 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
217 | fi
218 |
219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
220 |
221 | exec "$JAVACMD" \
222 | $MAVEN_OPTS \
223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
226 |
--------------------------------------------------------------------------------
/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 http://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 Maven2 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 key stroke 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 enable echoing my setting MAVEN_BATCH_ECHO to 'on'
39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
40 |
41 | @REM set %HOME% to equivalent of $HOME
42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
43 |
44 | @REM Execute a user defined script before this one
45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
49 | :skipRcPre
50 |
51 | @setlocal
52 |
53 | set ERROR_CODE=0
54 |
55 | @REM To isolate internal variables from possible post scripts, we use another setlocal
56 | @setlocal
57 |
58 | @REM ==== START VALIDATION ====
59 | if not "%JAVA_HOME%" == "" goto OkJHome
60 |
61 | echo.
62 | echo Error: JAVA_HOME not found in your environment. >&2
63 | echo Please set the JAVA_HOME variable in your environment to match the >&2
64 | echo location of your Java installation. >&2
65 | echo.
66 | goto error
67 |
68 | :OkJHome
69 | if exist "%JAVA_HOME%\bin\java.exe" goto init
70 |
71 | echo.
72 | echo Error: JAVA_HOME is set to an invalid directory. >&2
73 | echo JAVA_HOME = "%JAVA_HOME%" >&2
74 | echo Please set the JAVA_HOME variable in your environment to match the >&2
75 | echo location of your Java installation. >&2
76 | echo.
77 | goto error
78 |
79 | @REM ==== END VALIDATION ====
80 |
81 | :init
82 |
83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
84 | @REM Fallback to current working directory if not found.
85 |
86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
88 |
89 | set EXEC_DIR=%CD%
90 | set WDIR=%EXEC_DIR%
91 | :findBaseDir
92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
93 | cd ..
94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
95 | set WDIR=%CD%
96 | goto findBaseDir
97 |
98 | :baseDirFound
99 | set MAVEN_PROJECTBASEDIR=%WDIR%
100 | cd "%EXEC_DIR%"
101 | goto endDetectBaseDir
102 |
103 | :baseDirNotFound
104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
105 | cd "%EXEC_DIR%"
106 |
107 | :endDetectBaseDir
108 |
109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
110 |
111 | @setlocal EnableExtensions EnableDelayedExpansion
112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
114 |
115 | :endReadAdditionalConfig
116 |
117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
118 |
119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
121 |
122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
123 | if ERRORLEVEL 1 goto error
124 | goto end
125 |
126 | :error
127 | set ERROR_CODE=1
128 |
129 | :end
130 | @endlocal & set ERROR_CODE=%ERROR_CODE%
131 |
132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
136 | :skipRcPost
137 |
138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
140 |
141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
142 |
143 | exit /B %ERROR_CODE%
144 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.spring-boilerplate
7 | spring-boilerplate
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | spring-boilerplate
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.0.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 | spring-snapshot
29 | http://maven.springframework.org/snapshot
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | org.postgresql
38 | postgresql
39 | 9.4-1200-jdbc41
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-data-jpa
44 | 2.0.0.RELEASE
45 |
46 |
47 | org.springframework.boot
48 | spring-boot-starter-logging
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | org.springframework.boot
60 | spring-boot-starter-web
61 | 2.0.0.RELEASE
62 |
63 |
64 | org.hibernate.validator
65 | hibernate-validator
66 | 6.0.8.Final
67 |
68 |
69 | org.hibernate
70 | hibernate-search-orm
71 | 5.11.5.Final
72 |
73 |
74 | org.hibernate
75 | hibernate-core
76 | 5.2.3.Final
77 |
78 |
79 | com.h2database
80 | h2
81 | test
82 |
83 |
84 |
85 | org.springframework.boot
86 | spring-boot-starter-data-rest
87 |
88 |
89 |
90 | org.springframework.boot
91 | spring-boot-starter-actuator
92 |
93 |
94 | org.springframework.boot
95 | spring-boot-devtools
96 | runtime
97 |
98 |
99 |
100 | org.springframework.boot
101 | spring-boot-starter-test
102 | test
103 |
104 |
105 | org.springframework.security
106 | spring-security-test
107 | test
108 |
109 |
110 |
111 | io.jsonwebtoken
112 | jjwt
113 | 0.9.0
114 |
115 |
116 | org.springframework.boot
117 | spring-boot-starter-security
118 |
119 |
120 | io.springfox
121 | springfox-swagger2
122 | 2.7.0
123 |
124 |
125 | io.springfox
126 | springfox-swagger-ui
127 | 2.9.2
128 |
129 |
130 |
131 | org.springframework.boot
132 | spring-boot-starter-mail
133 |
134 |
135 | org.modelmapper.extensions
136 | modelmapper-spring
137 | 2.3.6
138 |
139 |
140 | com.google.code.gson
141 | gson
142 |
143 |
144 |
145 | commons-io
146 | commons-io
147 | 2.6
148 |
149 |
150 |
151 |
152 |
153 | org.springframework.boot
154 | spring-boot-starter-cache
155 | 2.2.5.RELEASE
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 | org.springframework.boot
164 | spring-boot-maven-plugin
165 |
166 |
167 |
168 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/SpringBoilerplateApplication.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringBoilerplateApplication {
8 | public static void main(String[] args) {
9 | SpringApplication.run(SpringBoilerplateApplication.class, args);
10 | }
11 |
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/auth/AccountCredentials.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.auth;
2 |
3 | import java.io.Serializable;
4 |
5 | public class AccountCredentials implements Serializable{
6 | private String email;
7 | private String password;
8 |
9 | public String getEmail() {
10 | return email;
11 | }
12 |
13 | public void setEmail(String email) {
14 | this.email = email;
15 | }
16 |
17 | public String getPassword() {
18 | return password;
19 | }
20 |
21 | public void setPassword(String password) {
22 | this.password = password;
23 | }
24 |
25 | public AccountCredentials() {}
26 |
27 | public AccountCredentials(String email, String password) {
28 | this.email = email;
29 | this.password = password;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/auth/AuthController.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.auth;
2 |
3 | import com.springboilerplate.app.user.User;
4 | import com.springboilerplate.security.CustomUserService;
5 | import com.springboilerplate.security.JwtTokenUtil;
6 | import io.swagger.annotations.Api;
7 | import org.slf4j.Logger;
8 | import org.slf4j.LoggerFactory;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.beans.factory.annotation.Value;
11 | import org.springframework.http.ResponseEntity;
12 | import org.springframework.security.authentication.AuthenticationManager;
13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
14 | import org.springframework.security.core.AuthenticationException;
15 | import org.springframework.web.bind.annotation.*;
16 |
17 | import javax.servlet.http.HttpServletRequest;
18 | import javax.validation.constraints.NotNull;
19 |
20 | @RestController
21 | @Api(value="Authentication", description="Operations that handle user authentication")
22 | public class AuthController {
23 |
24 | private Logger logger = LoggerFactory.getLogger(AuthController.class);
25 | @Value("${jwt.header}")
26 | private String tokenHeader;
27 | @Autowired
28 | private JwtTokenUtil jwtTokenUtil;
29 | @Autowired
30 | private AuthenticationManager authenticationManager;
31 | @Autowired
32 | private CustomUserService customUserService;
33 |
34 | @GetMapping(value = "/user")
35 | public User getAuthenticatedUser(HttpServletRequest request) {
36 | String token = request.getHeader(tokenHeader).substring(7);
37 | logger.info("Retrieved token: '{}'", token);
38 | String email = jwtTokenUtil.getEmailFromToken(token);
39 | logger.info("Retrieved user from token: '{}'", email);
40 | return customUserService.loadUserByUsername(email);
41 | }
42 |
43 | @PostMapping(value = "${jwt.route.authentication.path}")
44 | public ResponseEntity> createAuthenticationToken(@RequestBody AccountCredentials accountCredentials) {
45 | authenticateUser(accountCredentials);
46 | final User userDetails = customUserService.loadUserByUsername(accountCredentials.getEmail());
47 | logger.info("Loaded user details: '{}' '{}'", userDetails);
48 | final String token = jwtTokenUtil.generateToken(userDetails);
49 | logger.info("Generated token: '{}'", token);
50 | return ResponseEntity.ok(new JwtAuthenticationResponse(token));
51 | }
52 |
53 | @GetMapping(value = "${jwt.route.authentication.refresh}")
54 | public ResponseEntity> refreshAndGetAuthenticationToken(HttpServletRequest request) {
55 | String authToken = request.getHeader(tokenHeader);
56 | final String token = authToken.substring(7);
57 | String email = jwtTokenUtil.getEmailFromToken(token);
58 | User user = customUserService.loadUserByUsername(email);
59 | if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
60 | String refreshedToken = jwtTokenUtil.refreshToken(token);
61 | return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
62 | } else {
63 | return ResponseEntity.badRequest().body(null);
64 | }
65 | }
66 |
67 | private void authenticateUser(@NotNull AccountCredentials accountCredentials) throws AuthenticationException{
68 | String email = accountCredentials.getEmail(), password = accountCredentials.getPassword();
69 | logger.info("Authenticating with the following email and password: '{}' '{}'", email, password);
70 | authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, password));
71 | logger.info("Authenticated with email: '{}' '{}'", email, password);
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/auth/JwtAuthenticationResponse.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.auth;
2 |
3 | import java.io.Serializable;
4 |
5 | public class JwtAuthenticationResponse implements Serializable {
6 |
7 | private static final long serialVersionUID = 1250166508152483573L;
8 |
9 | private final String token;
10 |
11 | public JwtAuthenticationResponse(String token) {
12 | this.token = token;
13 | }
14 |
15 | public String getToken() {
16 | return this.token;
17 | }
18 | }
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/passwordRestToken/PasswordDto.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.passwordRestToken;
2 |
3 | public class PasswordDto {
4 | private String newPassword;
5 |
6 | public String getNewPassword() {
7 | return newPassword;
8 | }
9 |
10 | public void setNewPassword(String newPassword) {
11 | this.newPassword = newPassword;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/passwordRestToken/PasswordResetToken.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.passwordRestToken;
2 |
3 | import com.fasterxml.jackson.annotation.JsonRootName;
4 | import com.springboilerplate.app.user.User;
5 |
6 | import javax.persistence.*;
7 | import javax.validation.constraints.NotNull;
8 | import java.time.Instant;
9 |
10 | @Entity
11 | @Table(name = "password_reset_token")
12 | @JsonRootName(value = "payload")
13 | public class PasswordResetToken {
14 |
15 | private Long id;
16 | private String token;
17 | private User user;
18 | private Instant expiryDate = Instant.now().plusSeconds(86400L);
19 |
20 | public PasswordResetToken() {
21 | }
22 |
23 | @Id
24 | @GeneratedValue(strategy= GenerationType.IDENTITY)
25 | @Column(name = "password_reset_token_id")
26 | public Long getId() {
27 | return id;
28 | }
29 |
30 | public void setId(Long id) {
31 | this.id = id;
32 | }
33 |
34 | @NotNull
35 | public String getToken() {
36 | return token;
37 | }
38 |
39 | public void setToken(String token) {
40 | this.token = token;
41 | }
42 |
43 | @OneToOne(targetEntity = User.class, fetch = FetchType.LAZY)
44 | @JoinColumn(nullable = false, name = "user_id")
45 | public User getUser() {
46 | return user;
47 | }
48 |
49 | public void setUser(User user) {
50 | this.user = user;
51 | }
52 |
53 | @Column(name = "expiry_date")
54 | public Instant getExpiryDate() {
55 | return expiryDate;
56 | }
57 |
58 | public void setExpiryDate(Instant expiryDate) {
59 | this.expiryDate = expiryDate;
60 | }
61 |
62 | public PasswordResetToken(String token, User user) {
63 | this.token = token;
64 | this.user = user;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/passwordRestToken/PasswordResetTokenController.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.passwordRestToken;
2 |
3 | import com.springboilerplate.app.user.User;
4 | import com.springboilerplate.utils.SecurityUtils;
5 | import io.swagger.annotations.Api;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.http.HttpStatus;
8 | import org.springframework.http.ResponseEntity;
9 | import org.springframework.web.bind.annotation.PostMapping;
10 | import org.springframework.web.bind.annotation.RequestParam;
11 | import org.springframework.web.bind.annotation.RestController;
12 |
13 | @RestController("/passwordResetToken")
14 | @Api(value="Reset Password", description="Operations to enable the user replace their password")
15 | public class PasswordResetTokenController {
16 |
17 | private PasswordResetTokenService passwordResetTokenService;
18 |
19 | @Autowired
20 | public PasswordResetTokenController(PasswordResetTokenService passwordResetTokenService) {
21 | this.passwordResetTokenService = passwordResetTokenService;
22 | }
23 |
24 | @PostMapping(value = "/resetPassword")
25 | public ResponseEntity> resetPassword() throws Exception{
26 | User user = SecurityUtils.getLoggedInUser();
27 | passwordResetTokenService.createPasswordResetTokenForUser(user);
28 | return new ResponseEntity<>(HttpStatus.OK);
29 | }
30 |
31 | //If successfully validated, then the user can update his password.
32 | @PostMapping(value = "/validateToken")
33 | public ResponseEntity validateUserPassword(@RequestParam("userId") long userId,
34 | @RequestParam("token") String token) {
35 | boolean valid = passwordResetTokenService.validateResetToken(userId, token);
36 | return new ResponseEntity<>(valid, HttpStatus.OK);
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/passwordRestToken/PasswordResetTokenRepository.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.passwordRestToken;
2 | import org.springframework.data.jpa.repository.JpaRepository;
3 |
4 | import java.util.Optional;
5 |
6 | public interface PasswordResetTokenRepository extends JpaRepository{
7 |
8 | Optional findByToken(String token);
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/passwordRestToken/PasswordResetTokenService.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.passwordRestToken;
2 |
3 | import com.springboilerplate.app.user.User;
4 |
5 | import javax.mail.MessagingException;
6 |
7 | public interface PasswordResetTokenService {
8 | void createPasswordResetTokenForUser(User user) throws MessagingException;
9 |
10 | boolean validateResetToken(Long userId, String token);
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/passwordRestToken/PasswordResetTokenServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.passwordRestToken;
2 |
3 | import com.springboilerplate.app.user.User;
4 | import com.springboilerplate.helper.MailService;
5 | import com.springboilerplate.helper.SecurityHelper;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 |
9 | import javax.mail.MessagingException;
10 | import java.time.Instant;
11 | import java.util.Optional;
12 | import java.util.UUID;
13 | @Service
14 | public class PasswordResetTokenServiceImpl implements PasswordResetTokenService {
15 |
16 | private PasswordResetTokenRepository passwordTokenRepository;
17 | private MailService mailService;
18 | private SecurityHelper securityHelper;
19 |
20 | @Autowired
21 | public PasswordResetTokenServiceImpl(PasswordResetTokenRepository passwordTokenRepository,
22 | MailService mailService, SecurityHelper securityHelper) {
23 | this.passwordTokenRepository = passwordTokenRepository;
24 | this.mailService = mailService;
25 | this.securityHelper = securityHelper;
26 | }
27 |
28 | @Override
29 | public void createPasswordResetTokenForUser(User user) throws MessagingException {
30 | String token = UUID.randomUUID().toString();
31 | PasswordResetToken userToken = new PasswordResetToken(token, user);
32 | passwordTokenRepository.save(userToken);
33 | mailService.sendMail(user.getEmail(), "Your reset password is: " + token, "Password Reset Token");
34 | }
35 |
36 | @Override
37 | public boolean validateResetToken(Long userId, String tokenValue) {
38 | Optional optionalToken = passwordTokenRepository.findByToken(tokenValue);
39 | boolean validToken = optionalToken
40 | .filter(userToken -> !isTokenExpired(userToken))
41 | .filter(userToken -> isTokenValid(userToken, userId))
42 | .isPresent();
43 | if(validToken){
44 | securityHelper.grantUserChangePasswordPrivilege(optionalToken.get());
45 | return true;
46 | }
47 | return false;
48 | }
49 |
50 | private boolean isTokenValid(PasswordResetToken userToken, Long userId) {
51 | return Optional.ofNullable(userToken)
52 | .map(PasswordResetToken::getUser)
53 | .filter(user -> user.getId().equals(userId))
54 | .isPresent();
55 | }
56 |
57 | private boolean isTokenExpired(PasswordResetToken userToken){
58 | Instant currentTime = Instant.now();
59 | Instant expiryTime = userToken.getExpiryDate();
60 | return expiryTime.isBefore(currentTime);
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/role/Role.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.role;
2 |
3 | import javax.persistence.*;
4 | import javax.validation.constraints.NotNull;
5 | import java.time.LocalDateTime;
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | import com.fasterxml.jackson.annotation.JsonFormat;
10 | import com.fasterxml.jackson.annotation.JsonIdentityInfo;
11 | import com.fasterxml.jackson.annotation.JsonRootName;
12 | import com.fasterxml.jackson.annotation.ObjectIdGenerators;
13 | import com.springboilerplate.app.userRole.UserRole;
14 | import org.hibernate.search.annotations.DocumentId;
15 |
16 | @Entity
17 | @Table(name="role")
18 | @JsonIdentityInfo(
19 | generator = ObjectIdGenerators.PropertyGenerator.class,
20 | property = "id", scope = Role.class)
21 | @JsonRootName(value = "payload")
22 | public class Role {
23 | @Transient
24 | private LocalDateTime now = LocalDateTime.now();
25 |
26 | private Long id;
27 | private RoleType name;
28 | private List userRoles = new ArrayList<>();
29 | private boolean enabled = true;
30 | private boolean deleted = false;
31 | private LocalDateTime createdAt = now;
32 | private LocalDateTime modifiedAt = now;
33 |
34 | public Role(RoleType name) {
35 | this.name = name;
36 | }
37 |
38 | public Role() {
39 | }
40 |
41 | @Id
42 | @GeneratedValue(strategy=GenerationType.IDENTITY)
43 | @DocumentId
44 | @Column(name="role_id")
45 | public Long getId() {
46 | return id;
47 | }
48 |
49 | public void setId(Long id) {
50 | this.id = id;
51 | }
52 |
53 | @NotNull
54 | @Column(name="name", unique = true, length = 50)
55 | @Enumerated(EnumType.STRING)
56 | public RoleType getName() {
57 | return name;
58 | }
59 |
60 | public void setName(RoleType name) {
61 | this.name = name;
62 | }
63 |
64 | @OneToMany(mappedBy = "role", orphanRemoval = true)
65 | public List getUserRoles() {
66 | return userRoles;
67 | }
68 |
69 | public void setUserRoles(List userRoles) {
70 | this.userRoles = userRoles;
71 | }
72 |
73 | public void addUserRole(UserRole userRole){
74 | userRoles.add(userRole);
75 | userRole.setRole(this);
76 | }
77 |
78 | @Column
79 | public boolean isEnabled() {
80 | return enabled;
81 | }
82 |
83 | public void setEnabled(boolean enabled) {
84 | this.enabled = enabled;
85 | }
86 |
87 | @Column
88 | public boolean isDeleted() {
89 | return deleted;
90 | }
91 |
92 | public void setDeleted(boolean deleted) {
93 | this.deleted = deleted;
94 | }
95 |
96 | @Column(name = "created_at")
97 | @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
98 | public LocalDateTime getCreatedAt() {
99 | return createdAt;
100 | }
101 |
102 | public void setCreatedAt(LocalDateTime createdAt) {
103 | this.createdAt = createdAt;
104 | }
105 |
106 | @Column(name = "modified_at")
107 | @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
108 | public LocalDateTime getModifiedAt() {
109 | return modifiedAt;
110 | }
111 |
112 | public void setModifiedAt(LocalDateTime modifiedAt) {
113 | this.modifiedAt = modifiedAt;
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/role/RoleRepository.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.role;
2 |
3 | import org.springframework.data.jpa.repository.JpaRepository;
4 | import org.springframework.transaction.annotation.Transactional;
5 |
6 | import java.util.Optional;
7 |
8 | @Transactional
9 | public interface RoleRepository extends JpaRepository{
10 | Optional findByName(RoleType name);
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/role/RoleType.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.role;
2 |
3 | public enum RoleType {
4 | ROLE_USER, ROLE_ADMIN
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/search/HibernateSearchService.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.search;
2 |
3 |
4 | import org.hibernate.search.jpa.FullTextEntityManager;
5 | import org.hibernate.search.jpa.Search;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 | import org.springframework.transaction.annotation.Transactional;
9 |
10 | import javax.persistence.EntityManager;
11 |
12 | @Service
13 | public class HibernateSearchService {
14 |
15 | private EntityManager entityManager;
16 |
17 | @Autowired
18 | public HibernateSearchService(EntityManager entityManager) {
19 | this.entityManager = entityManager;
20 | }
21 |
22 | public HibernateSearchService() {
23 | }
24 |
25 | public EntityManager getEntityManager() {
26 | return entityManager;
27 | }
28 |
29 | @Transactional
30 | public void initializeHibernateSearch() throws InterruptedException {
31 | FullTextEntityManager fullTextEntityManager =
32 | Search.getFullTextEntityManager(entityManager);
33 | fullTextEntityManager.createIndexer().startAndWait();
34 | }
35 | }
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/search/UserSearchService.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.search;
2 |
3 | import com.springboilerplate.app.user.User;
4 | import org.apache.lucene.search.Query;
5 | import org.hibernate.search.jpa.FullTextEntityManager;
6 | import org.hibernate.search.jpa.Search;
7 | import org.hibernate.search.query.dsl.QueryBuilder;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.stereotype.Service;
10 | import org.springframework.transaction.annotation.Transactional;
11 |
12 | import javax.annotation.PostConstruct;
13 | import java.util.List;
14 |
15 | @Service
16 | public class UserSearchService {
17 |
18 | HibernateSearchService hibernateSearchService;
19 |
20 | @Autowired
21 | public UserSearchService(HibernateSearchService hibernateSearchService) {
22 | this.hibernateSearchService = hibernateSearchService;
23 | }
24 |
25 | @PostConstruct
26 | public void initHibernateSearch() throws Exception{
27 | hibernateSearchService.initializeHibernateSearch();
28 | }
29 | @Transactional
30 | public List findUsersByKeyword(String keyword){
31 | FullTextEntityManager fullTextEntityManager =
32 | Search.getFullTextEntityManager(hibernateSearchService.getEntityManager());
33 | fullTextEntityManager.flushToIndexes();
34 | QueryBuilder queryBuilder = fullTextEntityManager
35 | .getSearchFactory().buildQueryBuilder().forEntity(User.class).get();
36 | Query luceneQuery = queryBuilder.keyword().fuzzy().withEditDistanceUpTo(1)
37 | .withPrefixLength(1).onFields("firstname", "lastname", "email")
38 | .matching(keyword).createQuery();
39 | javax.persistence.Query jpaQuery = fullTextEntityManager.
40 | createFullTextQuery(luceneQuery, User.class);
41 | return jpaQuery.getResultList();
42 | }
43 | }
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/user/User.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.user;
2 |
3 | import com.fasterxml.jackson.annotation.JsonFormat;
4 | import com.fasterxml.jackson.annotation.JsonIgnore;
5 | import com.fasterxml.jackson.annotation.JsonRootName;
6 | import com.springboilerplate.app.userRole.UserRole;
7 | import org.hibernate.Hibernate;
8 | import org.hibernate.annotations.Where;
9 | import org.hibernate.search.annotations.*;
10 | import org.hibernate.search.annotations.Index;
11 | import org.hibernate.validator.constraints.Email;
12 | import org.springframework.security.core.GrantedAuthority;
13 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
14 | import org.springframework.security.core.userdetails.UserDetails;
15 |
16 | import javax.persistence.*;
17 | import javax.validation.constraints.NotNull;
18 | import javax.validation.constraints.Size;
19 | import java.time.LocalDateTime;
20 | import java.util.ArrayList;
21 | import java.util.Collection;
22 | import java.util.Date;
23 | import java.util.List;
24 | import java.util.stream.Collectors;
25 |
26 | @Entity
27 | @Table(name="users")
28 | @Indexed
29 | @Where(clause = "deleted = false")
30 | @JsonRootName(value = "payload")
31 | public class User implements UserDetails{
32 | @Transient
33 | private LocalDateTime now = LocalDateTime.now();
34 | private Long id;
35 | private String firstname;
36 | private String lastname;
37 | private String password;
38 | private String email;
39 | private List userRoles = new ArrayList<>();
40 | private Date lastPasswordResetDate;
41 | private LocalDateTime lastLogin = now;
42 | private LocalDateTime createdAt = now;
43 | private LocalDateTime modifiedAt = now;
44 | private boolean enabled = true;
45 | private boolean deleted = false;
46 |
47 | public User(String firstname, String lastname, String password, String email) {
48 | this.firstname = firstname;
49 | this.lastname = lastname;
50 | this.password = password;
51 | this.email = email;
52 | }
53 |
54 | public User(String firstname, String lastname, String password, String email, List userRoles) {
55 | this.firstname = firstname;
56 | this.lastname = lastname;
57 | this.password = password;
58 | this.email = email;
59 | this.userRoles = userRoles;
60 | }
61 |
62 | public User() {
63 | }
64 |
65 | @Id
66 | @GeneratedValue(strategy=GenerationType.IDENTITY)
67 | @DocumentId
68 | @Column(name="user_id", unique = true)
69 | public Long getId() {
70 | return id;
71 | }
72 |
73 | public void setId(Long id) {
74 | this.id = id;
75 | }
76 |
77 | @NotNull
78 | @Size(min=2, max=30, message="The length of firstname should be within the range of 2 to 30.")
79 | @Column(name = "firstname")
80 | @Field(index= Index.YES, analyze= Analyze.YES, store= Store.NO)
81 | public String getFirstname() {
82 | return firstname;
83 | }
84 |
85 | public void setFirstname(String firstname) {
86 | this.firstname = firstname;
87 | }
88 |
89 | @NotNull
90 | @Size(min=2, max=30, message="The length lastname should be within the range of 2 to 30.")
91 | @Column(name = "lastname")
92 | @Field(index= Index.YES, analyze= Analyze.YES, store= Store.NO)
93 | public String getLastname() {
94 | return lastname;
95 | }
96 |
97 | public void setLastname(String lastname) {
98 | this.lastname = lastname;
99 | }
100 |
101 | @NotNull
102 | @Size(min=2, max=100, message="The length of password should be within the range of 2 to 30.")
103 | @Column(name = "password")
104 | public String getPassword() {
105 | return password;
106 | }
107 |
108 | public void setPassword(String password) {
109 | this.password = password;
110 | }
111 |
112 | @NotNull
113 | @Column(name = "email", unique = true)
114 | @Email(message = "Email is not valid.")
115 | @Field(index= Index.YES, analyze= Analyze.YES, store= Store.NO)
116 | public String getEmail() {
117 | return email;
118 | }
119 | public void setEmail(String email) {
120 | this.email = email;
121 | }
122 |
123 |
124 | @OneToMany(mappedBy="user", orphanRemoval = true, fetch = FetchType.EAGER)
125 | public List getUserRoles() {
126 | return userRoles;
127 | }
128 |
129 | public void setUserRoles(List userRoles) {
130 | this.userRoles = userRoles;
131 | }
132 |
133 | public void addUserRole(UserRole userRole){
134 | userRoles.add(userRole);
135 | userRole.setUser(this);
136 | }
137 |
138 | @Column(name = "enabled")
139 | public boolean isEnabled() {
140 | return enabled;
141 | }
142 |
143 | public void setEnabled(boolean enabled) {
144 | this.enabled = enabled;
145 | }
146 |
147 | @Column(name = "created_at")
148 | @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
149 | public LocalDateTime getCreatedAt() {
150 | return createdAt;
151 | }
152 |
153 | public void setCreatedAt(LocalDateTime createdAt) {
154 | this.createdAt = createdAt;
155 | }
156 |
157 | @Column(name = "modified_at")
158 | @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
159 | public LocalDateTime getModifiedAt() {
160 | return modifiedAt;
161 | }
162 |
163 | public void setModifiedAt(LocalDateTime modifiedAt) {
164 | this.modifiedAt = modifiedAt;
165 | }
166 |
167 | @Column(name = "deleted")
168 | public boolean isDeleted() {
169 | return deleted;
170 | }
171 |
172 | public void setDeleted(boolean deleted) {
173 | this.deleted = deleted;
174 | }
175 |
176 | @Column(name = "last_login")
177 | @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
178 | public LocalDateTime getLastLogin() {
179 | return lastLogin;
180 | }
181 |
182 | public void setLastLogin(LocalDateTime lastLogin) {
183 | this.lastLogin = lastLogin;
184 | }
185 |
186 | @Column(name = "last_password_reset_data")
187 | @JsonIgnore
188 | public Date getLastPasswordResetDate() {
189 | return lastPasswordResetDate;
190 | }
191 |
192 | public void setLastPasswordResetDate(Date lastPasswordResetDate) {
193 | this.lastPasswordResetDate = lastPasswordResetDate;
194 | }
195 |
196 | @Override
197 | @JsonIgnore
198 | @Transient
199 | public Collection extends GrantedAuthority> getAuthorities() {
200 | //Hibernate initialize because role on userRole is lazily loaded.
201 | userRoles.forEach(userRole -> Hibernate.initialize(userRole.getRole()));
202 | return userRoles.stream().map(userRole -> new SimpleGrantedAuthority(
203 | userRole.getRole().getName().name())).collect(Collectors.toList());
204 | }
205 |
206 | @Override
207 | @JsonIgnore
208 | @Transient
209 | public String getUsername() {
210 | return email;
211 | }
212 |
213 | @Override
214 | @JsonIgnore
215 | @Transient
216 | public boolean isAccountNonExpired() {
217 | return true;
218 | }
219 |
220 | @Override
221 | @JsonIgnore
222 | @Transient
223 | public boolean isAccountNonLocked() {
224 | return true;
225 | }
226 |
227 | @Override
228 | @JsonIgnore
229 | @Transient
230 | public boolean isCredentialsNonExpired() {
231 | return true;
232 | }
233 | }
--------------------------------------------------------------------------------
/src/main/java/com/springboilerplate/app/user/UserController.java:
--------------------------------------------------------------------------------
1 | package com.springboilerplate.app.user;
2 |
3 | import com.springboilerplate.app.role.RoleType;
4 | import com.springboilerplate.app.search.UserSearchService;
5 | import com.springboilerplate.app.passwordRestToken.PasswordDto;
6 | import com.springboilerplate.utils.SecurityUtils;
7 | import io.swagger.annotations.Api;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.http.HttpStatus;
10 | import org.springframework.http.ResponseEntity;
11 | import org.springframework.web.bind.annotation.*;
12 |
13 | import javax.validation.Valid;
14 | import java.util.List;
15 |
16 | @RestController
17 | @RequestMapping("/users")
18 | @Api(value="User", description="Operations that pertains to managing user operations")
19 | public class UserController {
20 |
21 | private UserService userService;
22 | private UserSearchService userSearchService;
23 |
24 | @Autowired
25 | public UserController(UserService userService, UserSearchService userSearchService) {
26 | this.userService = userService;
27 | this.userSearchService = userSearchService;
28 | }
29 |
30 | @PostMapping(path="/register")
31 | public ResponseEntity> registerUser(@Valid @RequestBody UserDto user) throws Exception {
32 | userService.saveUser(user, RoleType.ROLE_USER);
33 | return new ResponseEntity<>(HttpStatus.CREATED);
34 | }
35 |
36 | @PostMapping(value = "/savePassword")
37 | public ResponseEntity> savePassword(@Valid PasswordDto passwordDto) {
38 | User user = SecurityUtils.getLoggedInUser();
39 | userService.changeUserPassword(user, passwordDto);
40 | return new ResponseEntity