├── .gitignore ├── .mvn ├── ._wrapper └── wrapper │ ├── ._MavenWrapperDownloader.java │ ├── ._maven-wrapper.jar │ ├── ._maven-wrapper.properties │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── lk │ │ └── teachmeit │ │ └── boilerplate │ │ ├── AuthApplication.java │ │ ├── configs │ │ └── EmailServerConfig.java │ │ ├── constants │ │ └── AuthConstants.java │ │ ├── controller │ │ ├── AuthController.java │ │ └── UserController.java │ │ ├── dao │ │ ├── PermissionDao.java │ │ ├── UserDao.java │ │ └── UserRoleDao.java │ │ ├── dto │ │ ├── AuthTokenDto.java │ │ ├── ConfirmEmailDto.java │ │ ├── LoginUserDto.java │ │ ├── ResponseWrapper.java │ │ ├── RoleDto.java │ │ └── UserDto.java │ │ ├── events │ │ └── SeedEventListner.java │ │ ├── exceptions │ │ ├── EmailAlreadyException.java │ │ ├── EmailNotVerifiedException.java │ │ ├── InvalidCodeException.java │ │ ├── InvalidCredentialsException.java │ │ └── MyFileNotFoundException.java │ │ ├── model │ │ ├── Permission.java │ │ ├── Role.java │ │ └── User.java │ │ ├── service │ │ ├── impl │ │ │ ├── AuthServiceImpl.java │ │ │ ├── RoleServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ └── interfaces │ │ │ ├── AuthService.java │ │ │ ├── ICrudService.java │ │ │ └── UserService.java │ │ └── util │ │ ├── CORSFilter.java │ │ ├── ChyperHelper.java │ │ ├── EmailService.java │ │ ├── FileManagerService.java │ │ ├── FileService.java │ │ ├── HtmlProcessService.java │ │ ├── JwtAuthenticationEntryPoint.java │ │ ├── JwtAuthenticationFilter.java │ │ ├── RandomValueUtil.java │ │ ├── TokenProvider.java │ │ └── WebSecurityConfig.java └── resources │ ├── META-INF │ └── additional-spring-configuration-metadata.json │ ├── application.properties │ └── templates │ ├── .DS_Store │ ├── email │ ├── email-verification.html │ ├── includes │ │ ├── email-footer.html │ │ └── email-header.html │ └── statics │ │ └── email.css │ └── report │ ├── Code39.ttf │ └── credit-controll.html └── test ├── ._java └── java ├── ._lk └── lk ├── ._teachmeit └── teachmeit └── boilerplate └── AuthApplicationTests.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: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/.mvn/._wrapper -------------------------------------------------------------------------------- /.mvn/wrapper/._MavenWrapperDownloader.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/.mvn/wrapper/._MavenWrapperDownloader.java -------------------------------------------------------------------------------- /.mvn/wrapper/._maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/.mvn/wrapper/._maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/._maven-wrapper.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/.mvn/wrapper/._maven-wrapper.properties -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # springboot-jwt-boilerplate 2 | SpringBoot Authentication With JWT - BoilerPlate 3 | 4 | POSTMAN COLLECTION: https://www.getpostman.com/collections/9da99679debaafa51a9d 5 | 6 | # Features 7 | 8 | 🚀 Sign In 9 | 10 | 🚀 Sign Up 11 | 12 | 🚀 Forgot Password 13 | 14 | 🚀 Reset Password 15 | 16 | 🚀 Confirm Email 17 | 18 | 🚀 Initial Data Seeder 19 | -------------------------------------------------------------------------------- /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 /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 Mingw, 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 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | -------------------------------------------------------------------------------- /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 "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\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/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "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%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.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% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.3.4.RELEASE 9 | 10 | 11 | lk.teachmeit 12 | auth 13 | 0.0.1-SNAPSHOT 14 | auth 15 | Spring Boot Privilege and Role based authentication 16 | 17 | 18 | 11 19 | 20 | 21 | 22 | 23 | 24 | org.springframework.boot 25 | spring-boot-starter-data-jpa 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-security 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-thymeleaf 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-web 41 | 42 | 43 | 44 | org.thymeleaf.extras 45 | thymeleaf-extras-springsecurity5 46 | 47 | 48 | 49 | ognl 50 | ognl 51 | 3.1.12 52 | 53 | 54 | 55 | org.xhtmlrenderer 56 | flying-saucer-pdf 57 | 9.1.20 58 | 59 | 60 | 61 | com.github.jtidy 62 | jtidy 63 | 1.0.2 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-starter-websocket 69 | 70 | 71 | 72 | org.assertj 73 | assertj-core 74 | 75 | 76 | 77 | org.modelmapper 78 | modelmapper 79 | 2.3.5 80 | 81 | 82 | 83 | io.jsonwebtoken 84 | jjwt 85 | 0.9.0 86 | 87 | 88 | 89 | org.apache.commons 90 | commons-lang3 91 | 92 | 93 | 94 | org.awaitility 95 | awaitility 96 | 97 | 98 | 99 | org.mockito 100 | mockito-core 101 | 102 | 103 | 104 | ch.qos.logback 105 | logback-classic 106 | 107 | 108 | 109 | org.springframework.boot 110 | spring-boot-starter-mail 111 | 112 | 113 | 114 | mysql 115 | mysql-connector-java 116 | runtime 117 | 118 | 119 | 120 | org.springframework.boot 121 | spring-boot-configuration-processor 122 | true 123 | 124 | 125 | 126 | org.springframework.boot 127 | spring-boot-starter-test 128 | test 129 | 130 | 131 | org.junit.vintage 132 | junit-vintage-engine 133 | 134 | 135 | 136 | 137 | org.springframework.security 138 | spring-security-test 139 | test 140 | 141 | 142 | junit 143 | junit 144 | test 145 | 146 | 147 | 148 | 149 | 150 | 151 | org.springframework.boot 152 | spring-boot-maven-plugin 153 | 154 | 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/AuthApplication.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | @SpringBootApplication 8 | public class AuthApplication { 9 | 10 | public static void main(String[] args) { 11 | SpringApplication.run(AuthApplication.class, args); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/configs/EmailServerConfig.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.configs; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.mail.javamail.JavaMailSender; 7 | import org.springframework.mail.javamail.JavaMailSenderImpl; 8 | 9 | import java.util.Properties; 10 | 11 | @Configuration 12 | public class EmailServerConfig { 13 | 14 | @Value("${email.username}") 15 | private String userName; 16 | 17 | @Value("${email.password}") 18 | private String password; 19 | 20 | @Value("${email.host}") 21 | private String host; 22 | 23 | @Bean("email") 24 | public JavaMailSender gmailMailSender() { 25 | JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); 26 | mailSender.setHost(host); 27 | mailSender.setPort(587); 28 | 29 | mailSender.setUsername(userName); 30 | mailSender.setPassword(password); 31 | 32 | Properties props = mailSender.getJavaMailProperties(); 33 | props.put("mail.transport.protocol", "smtp"); 34 | props.put("mail.smtp.auth", "true"); 35 | props.put("mail.smtp.starttls.enable", "true"); 36 | props.put("mail.debug", "true"); 37 | 38 | return mailSender; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/constants/AuthConstants.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.constants; 2 | 3 | public class AuthConstants { 4 | 5 | public static final long ACCESS_TOKEN_VALIDITY_SECONDS = 744*60*60; 6 | public static final String SIGNING_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9anVzdCBlbmNvZGVkanVzdCBlbmNvZGVkanVzdCBlbmNvZGVkanVzdCBlbmNvZGVkanVzdCBlbmNvZGVk"; 7 | public static final String TOKEN_PREFIX = "Bearer "; 8 | public static final String HEADER_STRING = "Authorization"; 9 | public static final String AUTHORITIES_KEY = "scopes"; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.controller; 2 | 3 | import lk.teachmeit.boilerplate.dto.ConfirmEmailDto; 4 | import lk.teachmeit.boilerplate.dto.LoginUserDto; 5 | import lk.teachmeit.boilerplate.dto.ResponseWrapper; 6 | import lk.teachmeit.boilerplate.dto.UserDto; 7 | import lk.teachmeit.boilerplate.exceptions.EmailAlreadyException; 8 | import lk.teachmeit.boilerplate.exceptions.EmailNotVerifiedException; 9 | import lk.teachmeit.boilerplate.exceptions.InvalidCodeException; 10 | import lk.teachmeit.boilerplate.exceptions.InvalidCredentialsException; 11 | import lk.teachmeit.boilerplate.service.interfaces.AuthService; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.security.core.AuthenticationException; 15 | import org.springframework.web.bind.annotation.*; 16 | 17 | import java.io.IOException; 18 | 19 | @CrossOrigin(origins = "*", maxAge = 3600) 20 | @RestController 21 | @RequestMapping("/auth") 22 | public class AuthController { 23 | 24 | @Autowired 25 | private AuthService authService; 26 | 27 | @PostMapping(value = "/sign-in") 28 | public ResponseEntity signIn(@RequestBody LoginUserDto loginUserDto) throws AuthenticationException { 29 | try{ 30 | return ResponseEntity.ok(new ResponseWrapper(authService.signIn(loginUserDto), "success", "User authentication successful")); 31 | } catch (EmailNotVerifiedException emailNotVerifiedException){ 32 | return ResponseEntity.ok(new ResponseWrapper(null, "un-verified", emailNotVerifiedException.getMessage())); 33 | } catch (InvalidCredentialsException invalidCredentialsException) { 34 | return ResponseEntity.ok(new ResponseWrapper(null, "wrong", invalidCredentialsException.getMessage())); 35 | } catch (Exception e) { 36 | return ResponseEntity.ok(new ResponseWrapper(null, "failed", "Something went wrong! Please contact developer")); 37 | } 38 | } 39 | 40 | @PostMapping(value = "/signup") 41 | public Object saveUser(@RequestBody UserDto user) { 42 | try { 43 | return new ResponseWrapper(authService.signUp(user), "success", "User successfully registered"); 44 | } catch (EmailAlreadyException emailAlreadyException) { 45 | return new ResponseWrapper(null, "already", emailAlreadyException.getMessage()); 46 | } catch (IOException ioException) { 47 | return new ResponseWrapper(null, "email-sending-failed", "Email sending failed"); 48 | } catch (Exception exception) { 49 | return new ResponseWrapper(null, "failed", "Something went wrong! Please contact developer"); 50 | } 51 | } 52 | 53 | @PostMapping(value = "/email/verify") 54 | public ResponseWrapper verifyEmail(@RequestBody ConfirmEmailDto confirm) throws IOException { 55 | try { 56 | return new ResponseWrapper(authService.verifyEmail(confirm), "success", "Email verification Success"); 57 | } catch (InvalidCredentialsException invalidCredentialsException) { 58 | return new ResponseWrapper(null, "wrong-email", invalidCredentialsException.getMessage()); 59 | } catch (InvalidCodeException invalidCodeException) { 60 | return new ResponseWrapper(null, "invalid-code", invalidCodeException.getMessage()); 61 | } catch (IOException ioException) { 62 | return new ResponseWrapper(null, "email-sending-failed", "Email sending failed"); 63 | } catch (Exception e) { 64 | return new ResponseWrapper(null, "failed", "Something went wrong! Please contact developer"); 65 | } 66 | } 67 | 68 | @PostMapping(value = "/password/forgot") 69 | public Object forgotPassword(@RequestParam("email") String email) { 70 | try{ 71 | return new ResponseWrapper(authService.forgotPassword(email), "success", "Forgot password request success"); 72 | } catch(IOException ioException){ 73 | return new ResponseWrapper(null, "email-sending-failed", "Email sending failed"); 74 | } catch (InvalidCredentialsException invalidCredentialsException) { 75 | return new ResponseWrapper(null, "wrong-email", invalidCredentialsException.getMessage()); 76 | } catch(Exception e){ 77 | return new ResponseWrapper(null, "failed", "Something went wrong! Please contact developer"); 78 | } 79 | } 80 | 81 | @PostMapping(value = "/password/verify-code") 82 | public Object verifyResetCode(@RequestParam("email") String email, @RequestParam("resetCode") String resetCode) { 83 | try{ 84 | return new ResponseWrapper(authService.checkPasswordVerifyCode(email, resetCode), "success", "Forgot password request success"); 85 | } catch (InvalidCodeException invalidCodeException) { 86 | return new ResponseWrapper(null, "invalid-code", invalidCodeException.getMessage()); 87 | } catch (Exception e) { 88 | return new ResponseWrapper(null, "failed", "Something went wrong! Please contact developer"); 89 | } 90 | } 91 | 92 | @PostMapping(value = "/password/reset") 93 | public Object verifyResetCode(@RequestParam("email") String email, @RequestParam("resetCode") String resetCode, @RequestParam("newPassword") String newPassword) { 94 | try{ 95 | return new ResponseWrapper(authService.resetPassword(email, resetCode, newPassword), "success", "Password resettled successfully"); 96 | }catch (IOException ioException) { 97 | return new ResponseWrapper(null, "email-sending-failed", "Email sending failed"); 98 | } catch (InvalidCodeException invalidCodeException) { 99 | return new ResponseWrapper(null, "invalid-code", invalidCodeException.getMessage()); 100 | } catch (InvalidCredentialsException invalidCredentialsException) { 101 | return new ResponseWrapper(null, "wrong-email", invalidCredentialsException.getMessage()); 102 | } catch (Exception exception){ 103 | return new ResponseWrapper(null, "failed", "Something went wrong! Please contact developer"); 104 | } 105 | 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.controller; 2 | 3 | import lk.teachmeit.boilerplate.model.User; 4 | import lk.teachmeit.boilerplate.service.interfaces.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.access.prepost.PreAuthorize; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | import java.util.List; 10 | 11 | @CrossOrigin(origins = "*", maxAge = 3600) 12 | @RestController 13 | @RequestMapping("/user") 14 | public class UserController { 15 | 16 | @Autowired 17 | private UserService userService; 18 | 19 | @PreAuthorize("hasRole('ADMIN')") 20 | @RequestMapping(value="/users", method = RequestMethod.GET) 21 | public List listUser(){ 22 | return userService.findAll(); 23 | } 24 | 25 | @PreAuthorize("hasAnyRole('USER', 'ADMIN')") 26 | @RequestMapping(value = "/{id}", method = RequestMethod.GET) 27 | public User getOne(@PathVariable(value = "id") Long id){ 28 | return userService.findById(id); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dao/PermissionDao.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dao; 2 | 3 | import lk.teachmeit.boilerplate.model.Permission; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | /* 7 | * Author: Tharuka Lakshan Dissanayake 8 | * Date: 2020/12/04 9 | */ 10 | 11 | public interface PermissionDao extends CrudRepository { 12 | Permission findRoleByName(String name); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dao; 2 | 3 | import lk.teachmeit.boilerplate.model.User; 4 | import org.springframework.data.repository.CrudRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import java.util.List; 8 | 9 | /* 10 | * Author: Tharuka Lakshan Dissanayake 11 | * Date: 2020/12/04 12 | */ 13 | 14 | @Repository 15 | public interface UserDao extends CrudRepository { 16 | User findByEmail(String email); 17 | List findByPermissionsName(String permissionName); 18 | List findByRoleId(long roleId); 19 | boolean existsByEmail(String email); 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dao/UserRoleDao.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dao; 2 | 3 | import lk.teachmeit.boilerplate.model.Role; 4 | import org.springframework.data.repository.CrudRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | @Repository 8 | public interface UserRoleDao extends CrudRepository { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dto/AuthTokenDto.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dto; 2 | 3 | public class AuthTokenDto { 4 | 5 | private String token; 6 | 7 | public AuthTokenDto(){ 8 | 9 | } 10 | 11 | public AuthTokenDto(String token){ 12 | this.token = token; 13 | } 14 | 15 | public String getToken() { 16 | return token; 17 | } 18 | 19 | public void setToken(String token) { 20 | this.token = token; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dto/ConfirmEmailDto.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dto; 2 | 3 | public class ConfirmEmailDto { 4 | private String email; 5 | 6 | private String verifyCode; 7 | 8 | public ConfirmEmailDto() { 9 | } 10 | 11 | public ConfirmEmailDto(String email, String verifyCode) { 12 | this.email = email; 13 | this.verifyCode = verifyCode; 14 | } 15 | 16 | public String getEmail() { 17 | return email; 18 | } 19 | 20 | public void setEmail(String email) { 21 | this.email = email; 22 | } 23 | 24 | public String getVerifyCode() { 25 | return verifyCode; 26 | } 27 | 28 | public void setVerifyCode(String verifyCode) { 29 | this.verifyCode = verifyCode; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dto/LoginUserDto.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dto; 2 | 3 | public class LoginUserDto { 4 | 5 | private String email; 6 | private String password; 7 | 8 | public String getEmail() { 9 | return email; 10 | } 11 | 12 | public void setUsername(String username) { 13 | this.email = username; 14 | } 15 | 16 | public String getPassword() { 17 | return password; 18 | } 19 | 20 | public void setPassword(String password) { 21 | this.password = password; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dto/ResponseWrapper.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dto; 2 | 3 | public class ResponseWrapper { 4 | private Object body; 5 | private String status; 6 | private String message; 7 | 8 | public ResponseWrapper() { 9 | } 10 | 11 | public ResponseWrapper(Object body, String status, String message) { 12 | this.body = body; 13 | this.status = status; 14 | this.message = message; 15 | } 16 | 17 | public Object getBody() { 18 | return body; 19 | } 20 | 21 | public void setBody(Object body) { 22 | this.body = body; 23 | } 24 | 25 | public String getStatus() { 26 | return status; 27 | } 28 | 29 | public void setStatus(String status) { 30 | this.status = status; 31 | } 32 | 33 | public String getMessage() { 34 | return message; 35 | } 36 | 37 | public void setMessage(String message) { 38 | this.message = message; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dto/RoleDto.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dto; 2 | 3 | import lk.teachmeit.boilerplate.model.Permission; 4 | 5 | import java.util.List; 6 | 7 | public class RoleDto { 8 | private String id; 9 | private String name; 10 | private String description; 11 | private List permissions; 12 | 13 | public RoleDto() { 14 | } 15 | 16 | public RoleDto(String id, String name, String description, List permissions) { 17 | this.id = id; 18 | this.name = name; 19 | this.description = description; 20 | this.permissions = permissions; 21 | } 22 | 23 | public String getId() { 24 | return id; 25 | } 26 | 27 | public void setId(String id) { 28 | this.id = id; 29 | } 30 | 31 | public String getName() { 32 | return name; 33 | } 34 | 35 | public void setName(String name) { 36 | this.name = name; 37 | } 38 | 39 | public String getDescription() { 40 | return description; 41 | } 42 | 43 | public void setDescription(String description) { 44 | this.description = description; 45 | } 46 | 47 | public List getPermissions() { 48 | return permissions; 49 | } 50 | 51 | public void setPermissions(List permissions) { 52 | this.permissions = permissions; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/dto/UserDto.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.dto; 2 | 3 | /* 4 | * Author: Tharuka Lakshan Dissanayake 5 | * Date: 2020/12/04 6 | */ 7 | 8 | public class UserDto { 9 | 10 | private String firstName; 11 | private String lastName; 12 | private String avatar; 13 | private String email; 14 | private String password; 15 | private long userRoleId; 16 | 17 | public UserDto() { 18 | } 19 | 20 | 21 | 22 | public String getFirstName() { 23 | return firstName; 24 | } 25 | 26 | public void setFirstName(String firstName) { 27 | this.firstName = firstName; 28 | } 29 | 30 | public String getLastName() { 31 | return lastName; 32 | } 33 | 34 | public void setLastName(String lastName) { 35 | this.lastName = lastName; 36 | } 37 | 38 | public String getAvatar() { 39 | return avatar; 40 | } 41 | 42 | public void setAvatar(String avatar) { 43 | this.avatar = avatar; 44 | } 45 | 46 | public String getEmail() { 47 | return email; 48 | } 49 | 50 | public void setEmail(String email) { 51 | this.email = email; 52 | } 53 | 54 | public String getPassword() { 55 | return password; 56 | } 57 | 58 | public void setPassword(String password) { 59 | this.password = password; 60 | } 61 | 62 | public long getUserRoleId() { 63 | return userRoleId; 64 | } 65 | 66 | public void setUserRoleId(long userRoleId) { 67 | this.userRoleId = userRoleId; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/events/SeedEventListner.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.events; 2 | 3 | import lk.teachmeit.boilerplate.dao.*; 4 | import lk.teachmeit.boilerplate.model.*; 5 | import lk.teachmeit.boilerplate.service.impl.RoleServiceImpl; 6 | import lk.teachmeit.boilerplate.service.interfaces.UserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.context.event.ContextRefreshedEvent; 9 | import org.springframework.context.event.EventListener; 10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 11 | import org.springframework.stereotype.Component; 12 | 13 | import java.util.ArrayList; 14 | import java.util.Arrays; 15 | import java.util.List; 16 | 17 | @Component 18 | public class SeedEventListner { 19 | 20 | @Autowired 21 | private PermissionDao permissionDao; 22 | 23 | @Autowired 24 | private UserDao userRepository; 25 | 26 | @Autowired 27 | private UserService userService; 28 | 29 | @Autowired 30 | private BCryptPasswordEncoder bcryptEncoder; 31 | 32 | @Autowired 33 | private UserRoleDao userRoleDao; 34 | 35 | @Autowired 36 | private RoleServiceImpl roleServiceImpl; 37 | 38 | @EventListener 39 | public void seed(ContextRefreshedEvent event){ 40 | try{ 41 | boolean roles = permissionDao.findById(1L).isPresent(); 42 | if(!roles){ 43 | seedRoles(); 44 | seedUsers(); 45 | } 46 | }catch (Exception ignored){ 47 | System.out.println("this is the error"); 48 | System.out.println(ignored.getMessage()); 49 | } 50 | 51 | } 52 | 53 | private void seedRoles(){ 54 | 55 | try{ 56 | List userPermissions = Arrays.asList( 57 | new Permission("ADMIN_PRIVILEGES", "Admin privileges") 58 | ); 59 | 60 | List userRoles = new ArrayList<>(); 61 | for(Permission item:userPermissions){ 62 | userRoles.add(permissionDao.save(item)); 63 | } 64 | 65 | Role userRole = new Role(); 66 | userRole.setDescription("Admin"); 67 | userRole.setName("ADMIN"); 68 | userRole.setPermissions(userPermissions); 69 | userRoleDao.save(userRole); 70 | 71 | }catch (Exception ignored){ 72 | 73 | } 74 | } 75 | 76 | private void seedUsers(){ 77 | User admin; 78 | 79 | try{ 80 | admin = new User(); 81 | Role userRole = userRoleDao.findById((long) 1).get(); 82 | admin.setFirstName("Default"); 83 | admin.setLastName("Admin"); 84 | admin.setEmail("admin@sample.com"); 85 | admin.setIsEmailVerified("TRUE"); 86 | admin.setPassword(bcryptEncoder.encode("12345678")); 87 | admin.setUserRole(userRole); 88 | admin = userRepository.save(admin); 89 | userService.setUserRole(1, admin); 90 | }catch (Exception e){ 91 | System.out.println(e.getMessage()); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/exceptions/EmailAlreadyException.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.exceptions; 2 | 3 | public class EmailAlreadyException extends RuntimeException{ 4 | public EmailAlreadyException(String exception){ 5 | super(exception); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/exceptions/EmailNotVerifiedException.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.exceptions; 2 | 3 | public class EmailNotVerifiedException extends RuntimeException{ 4 | public EmailNotVerifiedException(String exception){ 5 | super(exception); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/exceptions/InvalidCodeException.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.exceptions; 2 | 3 | public class InvalidCodeException extends RuntimeException{ 4 | public InvalidCodeException(String exception){ 5 | super(exception); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/exceptions/InvalidCredentialsException.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.exceptions; 2 | 3 | public class InvalidCredentialsException extends RuntimeException{ 4 | public InvalidCredentialsException(String exception){ 5 | super(exception); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/exceptions/MyFileNotFoundException.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.exceptions; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(HttpStatus.NOT_FOUND) 7 | public class MyFileNotFoundException extends RuntimeException { 8 | public MyFileNotFoundException(String message) { 9 | super(message); 10 | } 11 | 12 | public MyFileNotFoundException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/model/Permission.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.model; 2 | 3 | import javax.persistence.*; 4 | 5 | @Entity 6 | public class Permission { 7 | 8 | @Id 9 | @GeneratedValue(strategy = GenerationType.AUTO) 10 | private long id; 11 | 12 | @Column 13 | private String name; 14 | 15 | @Column 16 | private String description; 17 | 18 | public Permission() { 19 | } 20 | 21 | public Permission(String name, String description) { 22 | this.name = name; 23 | this.description = description; 24 | } 25 | 26 | public long getId() { 27 | return id; 28 | } 29 | 30 | public void setId(long id) { 31 | this.id = id; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | public String getDescription() { 43 | return description; 44 | } 45 | 46 | public void setDescription(String description) { 47 | this.description = description; 48 | } 49 | 50 | // public List getUserRoles() { 51 | // return userRoles; 52 | // } 53 | // 54 | // public void setUserRoles(List userRoles) { 55 | // this.userRoles = userRoles; 56 | // } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/model/Role.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.model; 2 | 3 | import javax.persistence.*; 4 | import java.util.List; 5 | 6 | @Entity 7 | public class Role { 8 | 9 | @Id 10 | @GeneratedValue(strategy= GenerationType.IDENTITY) 11 | private long id; 12 | @Column 13 | private String name; 14 | @Column 15 | private String description; 16 | @ManyToMany(fetch = FetchType.EAGER) 17 | private List permissions; 18 | 19 | public Role() { 20 | } 21 | 22 | public Role(String name, String description, List permissions) { 23 | this.name = name; 24 | this.description = description; 25 | this.permissions = permissions; 26 | } 27 | 28 | public long getId() { 29 | return id; 30 | } 31 | 32 | public void setId(long id) { 33 | this.id = id; 34 | } 35 | 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | public void setName(String name) { 41 | this.name = name; 42 | } 43 | 44 | public String getDescription() { 45 | return description; 46 | } 47 | 48 | public void setDescription(String description) { 49 | this.description = description; 50 | } 51 | 52 | public List getPermissions() { 53 | return permissions; 54 | } 55 | 56 | public void setPermissions(List permissions) { 57 | this.permissions = permissions; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/model/User.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | 5 | import javax.persistence.*; 6 | import java.util.Set; 7 | 8 | @Entity 9 | public class User { 10 | 11 | @Id 12 | @GeneratedValue(strategy= GenerationType.IDENTITY) 13 | private long id; 14 | @Column 15 | private String firstName; 16 | @Column 17 | private String lastName; 18 | @Column 19 | private String email; 20 | @Column 21 | private String avatar; 22 | @Column 23 | private String emailVerifyCode; 24 | @Column 25 | @JsonIgnore 26 | private String password; 27 | @Column 28 | @JsonIgnore 29 | private String passwordResetCode; 30 | @Column 31 | private String isEmailVerified; 32 | @OneToOne 33 | private Role role; 34 | private String gender; 35 | 36 | @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 37 | @JoinTable(name = "PERMISSIONS", joinColumns = { 38 | @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { 39 | @JoinColumn(name = "PERMISSION_ID") }) 40 | @JsonIgnore 41 | private Set permissions; 42 | 43 | public User() { 44 | } 45 | 46 | public User(long id, String firstName, String lastName, String email, String avatar, String emailVerifyCode, String password, String passwordResetCode, String isEmailVerified, Role role, String gender, Set permissions) { 47 | this.id = id; 48 | this.firstName = firstName; 49 | this.lastName = lastName; 50 | this.email = email; 51 | this.avatar = avatar; 52 | this.emailVerifyCode = emailVerifyCode; 53 | this.password = password; 54 | this.passwordResetCode = passwordResetCode; 55 | this.isEmailVerified = isEmailVerified; 56 | this.role = role; 57 | this.gender = gender; 58 | this.permissions = permissions; 59 | } 60 | 61 | public String getEmailVerifyCode() { 62 | return emailVerifyCode; 63 | } 64 | 65 | public void setEmailVerifyCode(String emailVerifyCode) { 66 | this.emailVerifyCode = emailVerifyCode; 67 | } 68 | 69 | public Role getRole() { 70 | return role; 71 | } 72 | 73 | public void setRole(Role role) { 74 | this.role = role; 75 | } 76 | 77 | public String getGender() { 78 | return gender; 79 | } 80 | 81 | public void setGender(String gender) { 82 | this.gender = gender; 83 | } 84 | 85 | public Role getUserRole() { 86 | return role; 87 | } 88 | 89 | public void setUserRole(Role role) { 90 | this.role = role; 91 | } 92 | 93 | public long getId() { 94 | return id; 95 | } 96 | 97 | public void setId(long id) { 98 | this.id = id; 99 | } 100 | 101 | public String getFirstName() { 102 | return firstName; 103 | } 104 | 105 | public void setFirstName(String firstName) { 106 | this.firstName = firstName; 107 | } 108 | 109 | public String getLastName() { 110 | return lastName; 111 | } 112 | 113 | public void setLastName(String lastName) { 114 | this.lastName = lastName; 115 | } 116 | 117 | public String getEmail() { 118 | return email; 119 | } 120 | 121 | public void setEmail(String email) { 122 | this.email = email; 123 | } 124 | 125 | public String getAvatar() { 126 | return avatar; 127 | } 128 | 129 | public void setAvatar(String avatar) { 130 | this.avatar = avatar; 131 | } 132 | 133 | public String getPassword() { 134 | return password; 135 | } 136 | 137 | public void setPassword(String password) { 138 | this.password = password; 139 | } 140 | 141 | public String getPasswordResetCode() { 142 | return passwordResetCode; 143 | } 144 | 145 | public void setPasswordResetCode(String passwordResetCode) { 146 | this.passwordResetCode = passwordResetCode; 147 | } 148 | 149 | public String getIsEmailVerified() { 150 | return isEmailVerified; 151 | } 152 | 153 | public void setIsEmailVerified(String isEmailVerified) { 154 | this.isEmailVerified = isEmailVerified; 155 | } 156 | 157 | public Set getPermissions() { 158 | return permissions; 159 | } 160 | 161 | public void setPermissions(Set permissions) { 162 | this.permissions = permissions; 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/service/impl/AuthServiceImpl.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.service.impl; 2 | 3 | import lk.teachmeit.boilerplate.dto.*; 4 | import lk.teachmeit.boilerplate.exceptions.EmailAlreadyException; 5 | import lk.teachmeit.boilerplate.exceptions.EmailNotVerifiedException; 6 | import lk.teachmeit.boilerplate.exceptions.InvalidCodeException; 7 | import lk.teachmeit.boilerplate.exceptions.InvalidCredentialsException; 8 | import lk.teachmeit.boilerplate.model.User; 9 | import lk.teachmeit.boilerplate.util.HtmlProcessService; 10 | import lk.teachmeit.boilerplate.service.interfaces.AuthService; 11 | import lk.teachmeit.boilerplate.service.interfaces.UserService; 12 | import lk.teachmeit.boilerplate.util.EmailService; 13 | import lk.teachmeit.boilerplate.util.RandomValueUtil; 14 | import lk.teachmeit.boilerplate.util.TokenProvider; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.security.authentication.AuthenticationManager; 17 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 18 | import org.springframework.security.core.Authentication; 19 | import org.springframework.security.core.context.SecurityContextHolder; 20 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 21 | import org.springframework.stereotype.Service; 22 | import org.thymeleaf.context.Context; 23 | 24 | import java.io.IOException; 25 | import java.util.ArrayList; 26 | import java.util.List; 27 | 28 | @Service 29 | public class AuthServiceImpl implements AuthService { 30 | 31 | @Autowired 32 | private AuthenticationManager authenticationManager; 33 | 34 | @Autowired 35 | private TokenProvider jwtTokenUtil; 36 | 37 | @Autowired 38 | private UserService userService; 39 | 40 | @Autowired 41 | private EmailService emailService; 42 | 43 | @Autowired 44 | private BCryptPasswordEncoder bcryptEncoder; 45 | 46 | @Autowired 47 | private HtmlProcessService htmlProcessService; 48 | 49 | @Override 50 | public List signIn(LoginUserDto loginUserDto) { 51 | Authentication authentication; 52 | try { 53 | authentication = authenticationManager.authenticate( 54 | new UsernamePasswordAuthenticationToken( 55 | loginUserDto.getEmail(), 56 | loginUserDto.getPassword() 57 | ) 58 | ); 59 | } catch (Exception e) { 60 | throw new InvalidCredentialsException("User email or password incorrect"); 61 | } 62 | SecurityContextHolder.getContext().setAuthentication(authentication); 63 | final String token = jwtTokenUtil.generateToken(authentication); 64 | User user = userService.findOne(loginUserDto.getEmail()); 65 | if(user!=null) { 66 | if(user.getIsEmailVerified().equals("FALSE")) { 67 | throw new EmailNotVerifiedException("Your email is not verified yet"); 68 | } 69 | } 70 | List results = new ArrayList<>(); 71 | results.add(new AuthTokenDto(token)); 72 | results.add(user); 73 | 74 | return results; 75 | } 76 | 77 | @Override 78 | public User signUp(UserDto userDto) throws IOException { 79 | if( !userService.isUserExists(userDto.getEmail())){ 80 | User user = new User(); 81 | String resetCode = RandomValueUtil.getRandomNumberString(999999); 82 | user.setFirstName(userDto.getFirstName()); 83 | user.setLastName(userDto.getLastName()); 84 | user.setEmail(userDto.getEmail()); 85 | user.setPassword(userDto.getPassword()); 86 | user.setEmailVerifyCode(resetCode); 87 | user.setIsEmailVerified("FALSE"); 88 | user.setPassword(bcryptEncoder.encode(userDto.getPassword())); 89 | Context emailContext = new Context(); 90 | emailContext.setVariable("user", user); 91 | emailContext.setVariable("code", resetCode); 92 | emailService.sendHtmlEmailSmtp("Email Verification ", this.htmlProcessService.processHtml(emailContext, "email/email-verification"), user.getEmail()); 93 | return userService.save(user); 94 | } else { 95 | throw new EmailAlreadyException("Email address already using"); 96 | } 97 | } 98 | 99 | @Override 100 | public Object verifyEmail(ConfirmEmailDto confirmEmailDto) throws IOException { 101 | User authUser = userService.findOne(confirmEmailDto.getEmail()); 102 | if( authUser != null){ 103 | if(confirmEmailDto.getVerifyCode().equals(authUser.getEmailVerifyCode())) { 104 | authUser.setIsEmailVerified("TRUE"); 105 | authUser.setEmailVerifyCode(null); 106 | userService.save(authUser); 107 | emailService.sendHtmlEmailSmtp("Email Verification", "Welcome to the Spring Email", authUser.getEmail()); 108 | return authUser; 109 | } else { 110 | throw new InvalidCodeException("You provided verify code is wrong"); 111 | } 112 | } else { 113 | throw new InvalidCredentialsException("Entered email address is not valid!"); 114 | } 115 | } 116 | 117 | @Override 118 | public Object forgotPassword(String email) throws IOException { 119 | if(userService.isUserExists(email)){ 120 | User authUser = userService.findOne(email); 121 | String resetCode = RandomValueUtil.getRandomNumberString(999999); 122 | authUser.setPasswordResetCode(resetCode); 123 | userService.save(authUser); 124 | 125 | Context emailContext = new Context(); 126 | emailContext.setVariable("user", authUser); 127 | emailContext.setVariable("code", resetCode); 128 | 129 | emailService.sendHtmlEmailSmtp("Email Verification", this.htmlProcessService.processHtml(emailContext, "email/email-verification"), authUser.getEmail()); 130 | 131 | return authUser; 132 | } else { 133 | throw new InvalidCredentialsException("User not found"); 134 | } 135 | } 136 | 137 | @Override 138 | public Object checkPasswordVerifyCode(String email, String code) { 139 | if(userService.isUserExists(email)){ 140 | User authUser = userService.findOne(email); 141 | authUser = userService.save(authUser); 142 | if(code.equals(authUser.getPasswordResetCode())) { 143 | return authUser; 144 | } else { 145 | throw new InvalidCodeException("Wrong reset code"); 146 | } 147 | } else { 148 | throw new InvalidCredentialsException("User not found"); 149 | } 150 | } 151 | 152 | @Override 153 | public Object resetPassword(String email, String code, String newPassword) throws IOException { 154 | if(userService.isUserExists(email)){ 155 | User authUser = userService.findOne(email); 156 | if(code.equals(authUser.getPasswordResetCode())) { 157 | authUser.setPassword(bcryptEncoder.encode(newPassword)); 158 | authUser.setPasswordResetCode(null); 159 | authUser = userService.save(authUser); 160 | emailService.sendHtmlEmailSmtp("Password reset successfully", "Your password reset successfully!", email); 161 | return authUser; 162 | } else { 163 | throw new InvalidCodeException("Wrong reset code"); 164 | } 165 | } else { 166 | throw new InvalidCredentialsException("User not found"); 167 | } 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/service/impl/RoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.service.impl; 2 | 3 | import lk.teachmeit.boilerplate.dao.PermissionDao; 4 | import lk.teachmeit.boilerplate.dao.UserDao; 5 | import lk.teachmeit.boilerplate.dao.UserRoleDao; 6 | import lk.teachmeit.boilerplate.dto.RoleDto; 7 | import lk.teachmeit.boilerplate.model.Permission; 8 | import lk.teachmeit.boilerplate.model.User; 9 | import lk.teachmeit.boilerplate.model.Role; 10 | import lk.teachmeit.boilerplate.service.interfaces.ICrudService; 11 | import org.modelmapper.ModelMapper; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.stereotype.Service; 14 | 15 | import java.util.ArrayList; 16 | import java.util.HashSet; 17 | import java.util.List; 18 | import java.util.Set; 19 | 20 | @Service 21 | public class RoleServiceImpl implements ICrudService { 22 | 23 | @Autowired 24 | private UserRoleDao userRoleDao; 25 | @Autowired 26 | private PermissionDao permissionDao; 27 | @Autowired 28 | private UserDao userDao; 29 | private ModelMapper modelMapper = new ModelMapper(); 30 | 31 | @Override 32 | public Role create(RoleDto roleDto) { 33 | Role role = modelMapper.map(roleDto, Role.class); 34 | return userRoleDao.save(role); 35 | } 36 | 37 | @Override 38 | public Role update(RoleDto roleDto) { 39 | Role role = modelMapper.map(roleDto, Role.class); 40 | return userRoleDao.save(role); 41 | } 42 | 43 | @Override 44 | public boolean delete(RoleDto roleDto) { 45 | Role role = modelMapper.map(roleDto, Role.class); 46 | userRoleDao.delete(role); 47 | return true; 48 | } 49 | 50 | @Override 51 | public boolean delete(long id) { 52 | userRoleDao.deleteById(id); 53 | return true; 54 | } 55 | 56 | @Override 57 | public Role getById(long id) { 58 | return userRoleDao.findById(id).get(); 59 | } 60 | 61 | @Override 62 | public List getAll() { 63 | return (List) userRoleDao.findAll(); 64 | } 65 | 66 | public Role addPermissions(long roleId, List permissions) { 67 | Role userRole = userRoleDao.findById(roleId).get(); 68 | List userList = userDao.findByRoleId(roleId); 69 | userRole.getPermissions().clear(); 70 | for(long permission: permissions){ 71 | Permission role = permissionDao.findById(permission).get(); 72 | userRole.getPermissions().add(role); 73 | } 74 | userRole = userRoleDao.save(userRole); 75 | Set roles = new HashSet<>(userRole.getPermissions()); 76 | for(User user:userList){ 77 | user.setPermissions(roles); 78 | userDao.save(user); 79 | } 80 | 81 | return userRole; 82 | } 83 | 84 | public Role addPermissionsByName(long roleId, List name){ 85 | List permission = new ArrayList<>(); 86 | for(String perm:name){ 87 | permission.add(permissionDao.findRoleByName(perm)); 88 | } 89 | Role role =userRoleDao.findById(roleId).get(); 90 | role.setPermissions(permission); 91 | role = userRoleDao.save(role); 92 | return role; 93 | } 94 | 95 | @Override 96 | public List getPaginate(long page, long offset) { 97 | return null; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.service.impl; 2 | 3 | import lk.teachmeit.boilerplate.dao.UserDao; 4 | import lk.teachmeit.boilerplate.model.Permission; 5 | import lk.teachmeit.boilerplate.model.Role; 6 | import lk.teachmeit.boilerplate.model.User; 7 | import lk.teachmeit.boilerplate.service.interfaces.UserService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 13 | import org.springframework.stereotype.Service; 14 | 15 | import java.util.ArrayList; 16 | import java.util.HashSet; 17 | import java.util.List; 18 | import java.util.Set; 19 | 20 | 21 | @Service(value = "userService") 22 | public class UserServiceImpl implements UserDetailsService, UserService { 23 | 24 | @Autowired 25 | private UserDao userDao; 26 | @Autowired 27 | private RoleServiceImpl roleServiceImpl; 28 | 29 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 30 | User user = userDao.findByEmail(username); 31 | if(user == null){ 32 | throw new UsernameNotFoundException("Invalid username or password."); 33 | } 34 | return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), getAuthority(user)); 35 | } 36 | 37 | private Set getAuthority(User user) { 38 | Set authorities = new HashSet<>(); 39 | user.getPermissions().forEach(role -> { 40 | authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName())); 41 | }); 42 | return authorities; 43 | } 44 | 45 | public List findAll() { 46 | List list = new ArrayList<>(); 47 | userDao.findAll().iterator().forEachRemaining(list::add); 48 | return list; 49 | } 50 | 51 | public List getByPermission(String permission){ 52 | return userDao.findByPermissionsName(permission); 53 | } 54 | 55 | @Override 56 | public boolean isUserExists(String email) { 57 | return userDao.existsByEmail(email); 58 | } 59 | 60 | @Override 61 | public void delete(long id) { 62 | userDao.deleteById(id); 63 | } 64 | 65 | @Override 66 | public User findOne(String email) { 67 | return userDao.findByEmail(email); 68 | } 69 | 70 | @Override 71 | public User findById(Long id) { 72 | return userDao.findById(id).get(); 73 | } 74 | 75 | @Override 76 | public User save(User user) { 77 | user = userDao.save(user); 78 | return user; 79 | } 80 | 81 | @Override 82 | public User setUserRole(long userRoleId, User user){ 83 | Role role = roleServiceImpl.getById(userRoleId); 84 | Set roles = new HashSet<>(role.getPermissions()); 85 | user.setPermissions(roles); 86 | user.setUserRole(role); 87 | user = userDao.save(user); 88 | return user; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/service/interfaces/AuthService.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.service.interfaces; 2 | 3 | import lk.teachmeit.boilerplate.dto.ConfirmEmailDto; 4 | import lk.teachmeit.boilerplate.dto.LoginUserDto; 5 | import lk.teachmeit.boilerplate.dto.UserDto; 6 | import lk.teachmeit.boilerplate.model.User; 7 | 8 | import java.io.IOException; 9 | import java.util.List; 10 | 11 | public interface AuthService { 12 | List signIn(LoginUserDto loginUserDto); 13 | User signUp(UserDto userDto) throws IOException; 14 | Object verifyEmail(ConfirmEmailDto confirmEmailDto) throws IOException; 15 | Object forgotPassword(String email) throws IOException; 16 | Object checkPasswordVerifyCode(String email, String code); 17 | Object resetPassword(String email, String code, String newPassword) throws IOException; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/service/interfaces/ICrudService.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.service.interfaces; 2 | 3 | import java.util.List; 4 | 5 | public interface ICrudService { 6 | Return create(Input input); 7 | Return update(Input input); 8 | boolean delete(Input input); 9 | boolean delete(long id); 10 | Return getById(long id); 11 | List getAll(); 12 | List getPaginate(long page, long offset); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/service/interfaces/UserService.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.service.interfaces; 2 | 3 | import lk.teachmeit.boilerplate.model.User; 4 | 5 | import java.util.List; 6 | 7 | public interface UserService { 8 | 9 | User save(User user); 10 | List findAll(); 11 | void delete(long id); 12 | User findOne(String username); 13 | 14 | User findById(Long id); 15 | 16 | User setUserRole(long userRoleId, User user); 17 | 18 | List getByPermission(String permission); 19 | 20 | boolean isUserExists(String email); 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/CORSFilter.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import javax.servlet.*; 4 | import javax.servlet.http.HttpServletResponse; 5 | import java.io.IOException; 6 | 7 | 8 | public class CORSFilter implements Filter { 9 | 10 | public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 11 | HttpServletResponse response = (HttpServletResponse) res; 12 | response.setHeader("Access-Control-Allow-Origin", "*"); 13 | response.setHeader("Access-Control-Allow-Credentials", "true"); 14 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); 15 | response.setHeader("Access-Control-Max-Age", "3600"); 16 | response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers"); 17 | chain.doFilter(req, res); 18 | } 19 | 20 | public void init(FilterConfig filterConfig) {} 21 | 22 | public void destroy() {} 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/ChyperHelper.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | import javax.crypto.Cipher; 6 | import javax.crypto.spec.SecretKeySpec; 7 | import java.io.UnsupportedEncodingException; 8 | import java.security.MessageDigest; 9 | import java.security.NoSuchAlgorithmException; 10 | import java.util.Arrays; 11 | import java.util.Base64; 12 | 13 | @Service 14 | public class ChyperHelper { 15 | private static SecretKeySpec secretKey; 16 | private static byte[] key; 17 | public static String SECRET_KEY = "sample-key"; 18 | 19 | public static void setKey(String myKey) 20 | { 21 | MessageDigest sha = null; 22 | try { 23 | key = myKey.getBytes("UTF-8"); 24 | sha = MessageDigest.getInstance("SHA-1"); 25 | key = sha.digest(key); 26 | key = Arrays.copyOf(key, 16); 27 | secretKey = new SecretKeySpec(key, "AES"); 28 | } 29 | catch (NoSuchAlgorithmException e) { 30 | e.printStackTrace(); 31 | } 32 | catch (UnsupportedEncodingException e) { 33 | e.printStackTrace(); 34 | } 35 | } 36 | 37 | public static String encrypt(String strToEncrypt, String secret) 38 | { 39 | try 40 | { 41 | setKey(secret); 42 | Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 43 | cipher.init(Cipher.ENCRYPT_MODE, secretKey); 44 | return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); 45 | } 46 | catch (Exception e) 47 | { 48 | System.out.println("Error while encrypting: " + e.toString()); 49 | } 50 | return null; 51 | } 52 | 53 | public static String decrypt(String strToDecrypt, String secret) 54 | { 55 | try 56 | { 57 | setKey(secret); 58 | Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); 59 | cipher.init(Cipher.DECRYPT_MODE, secretKey); 60 | return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); 61 | } 62 | catch (Exception e) 63 | { 64 | System.out.println("Error while decrypting: " + e.toString()); 65 | } 66 | return null; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/EmailService.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.mail.javamail.JavaMailSender; 7 | import org.springframework.mail.javamail.MimeMessageHelper; 8 | import org.springframework.mail.javamail.MimeMessagePreparator; 9 | import org.springframework.stereotype.Service; 10 | 11 | @Service 12 | public class EmailService { 13 | @Autowired 14 | @Qualifier("email") 15 | private JavaMailSender javaMailSender; 16 | 17 | @Value("${email.username}") 18 | private String emailFrom; 19 | 20 | public void sendHtmlEmailSmtp(String subject, String body, String... to){ 21 | MimeMessagePreparator preparator = mimeMessage -> { 22 | MimeMessageHelper message = new MimeMessageHelper(mimeMessage); 23 | message.setTo(to[0]); 24 | message.setFrom(emailFrom, emailFrom); 25 | message.setSubject(subject); 26 | message.setText(body, true); 27 | }; 28 | javaMailSender.send(preparator); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/FileManagerService.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.stereotype.Service; 5 | 6 | @Service 7 | public class FileManagerService { 8 | 9 | @Autowired 10 | FileService fileService; 11 | 12 | public boolean deleteImage(String name){ 13 | try { 14 | String [] fileName = name.split("/"); 15 | fileService.deleteFile(fileName[fileName.length - 1]); 16 | return true; 17 | } catch ( Exception e) { 18 | return false; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/FileService.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import lk.teachmeit.boilerplate.exceptions.MyFileNotFoundException; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.core.io.Resource; 6 | import org.springframework.core.io.UrlResource; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.util.StringUtils; 9 | import org.springframework.web.multipart.MultipartFile; 10 | 11 | import javax.imageio.IIOImage; 12 | import javax.imageio.ImageIO; 13 | import javax.imageio.ImageWriteParam; 14 | import javax.imageio.ImageWriter; 15 | import javax.imageio.stream.ImageOutputStream; 16 | import java.awt.*; 17 | import java.awt.image.BufferedImage; 18 | import java.io.File; 19 | import java.io.FileOutputStream; 20 | import java.io.OutputStream; 21 | import java.net.MalformedURLException; 22 | import java.nio.file.Path; 23 | import java.nio.file.Paths; 24 | 25 | @Service 26 | public class FileService { 27 | 28 | @Value("${upload.path}") 29 | public String uploadDir; 30 | 31 | public void uploadFile(MultipartFile file, String fileName, String location) { 32 | try { 33 | Path copyLocation = Paths 34 | .get(uploadDir + File.separator + location + File.separator + StringUtils.cleanPath(fileName)); 35 | 36 | File output = new File(String.valueOf(copyLocation)); 37 | file.transferTo(output); 38 | } catch (Exception e) { 39 | System.out.println("File upload failed"); 40 | } 41 | } 42 | 43 | public void uploadImage(BufferedImage image, String fileName, String location) { 44 | try { 45 | Path copyLocation = Paths 46 | .get(uploadDir + File.separator + location + File.separator + StringUtils.cleanPath(fileName)); 47 | 48 | BufferedImage result = new BufferedImage( 49 | image.getWidth(), 50 | image.getHeight(), 51 | BufferedImage.TYPE_INT_RGB); 52 | result.createGraphics().drawImage(image, 0, 0, Color.WHITE, null); 53 | 54 | ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); 55 | File output = new File(String.valueOf(copyLocation)); 56 | OutputStream out = new FileOutputStream(output); 57 | 58 | ImageOutputStream ios = ImageIO.createImageOutputStream(out); 59 | writer.setOutput(ios); 60 | 61 | ImageWriteParam param = writer.getDefaultWriteParam(); 62 | if (param.canWriteCompressed()){ 63 | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 64 | param.setCompressionQuality(0.5f); 65 | } 66 | 67 | writer.write(null, new IIOImage(result, null, null), param); 68 | 69 | out.close(); 70 | ios.close(); 71 | writer.dispose(); 72 | 73 | } catch (Exception e) { 74 | System.out.println("Image compression failed"); 75 | } 76 | } 77 | 78 | public void uploadImage(MultipartFile file, String fileName, String location) { 79 | try { 80 | Path copyLocation = Paths 81 | .get(uploadDir + File.separator + location + File.separator + StringUtils.cleanPath(fileName)); 82 | 83 | BufferedImage image = ImageIO.read(file.getInputStream()); 84 | BufferedImage result = new BufferedImage( 85 | image.getWidth(), 86 | image.getHeight(), 87 | BufferedImage.TYPE_INT_RGB); 88 | result.createGraphics().drawImage(image, 0, 0, Color.WHITE, null); 89 | 90 | // BufferedImage image = ImageIO.read(file.getInputStream()); 91 | ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); 92 | File output = new File(String.valueOf(copyLocation)); 93 | OutputStream out = new FileOutputStream(output); 94 | 95 | ImageOutputStream ios = ImageIO.createImageOutputStream(out); 96 | writer.setOutput(ios); 97 | 98 | ImageWriteParam param = writer.getDefaultWriteParam(); 99 | if (param.canWriteCompressed()){ 100 | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 101 | param.setCompressionQuality(0.5f); 102 | } 103 | 104 | writer.write(null, new IIOImage(result, null, null), param); 105 | 106 | out.close(); 107 | ios.close(); 108 | writer.dispose(); 109 | 110 | } catch (Exception e) { 111 | System.out.println("Image compression failed"); 112 | } 113 | } 114 | 115 | public Resource loadFileAsResource(String fileLocation ,String fileName) { 116 | Path fileStorageLocation = Paths.get(uploadDir.concat(fileLocation)) 117 | .toAbsolutePath().normalize(); 118 | try { 119 | Path filePath = fileStorageLocation.resolve(fileName).normalize(); 120 | Resource resource = new UrlResource(filePath.toUri()); 121 | if(resource.exists()) { 122 | return resource; 123 | } else { 124 | throw new MyFileNotFoundException("File not found " + fileName); 125 | } 126 | } catch (MalformedURLException ex) { 127 | throw new MyFileNotFoundException("File not found " + fileName, ex); 128 | } 129 | } 130 | 131 | public boolean deleteFile(String imagName) { 132 | try { 133 | File file = new File(uploadDir.concat("/").concat(imagName)); 134 | if(file.delete()) { 135 | return true; 136 | } else { 137 | return false; 138 | } 139 | } 140 | catch(Exception e) 141 | { 142 | return false; 143 | } 144 | } 145 | 146 | public String getFilePath(String fileName){ 147 | String path = "http://api.teachmeit.lk/guest/downloadFile/"; 148 | return path+fileName; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/HtmlProcessService.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import org.springframework.stereotype.Service; 4 | import org.thymeleaf.TemplateEngine; 5 | import org.thymeleaf.context.Context; 6 | import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; 7 | 8 | import static org.apache.commons.lang3.CharEncoding.UTF_8; 9 | import static org.thymeleaf.templatemode.TemplateMode.HTML; 10 | 11 | @Service 12 | public class HtmlProcessService { 13 | 14 | public String processHtml (Context context, String file) { 15 | ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); 16 | templateResolver.setPrefix("templates/"); 17 | templateResolver.setSuffix(".html"); 18 | templateResolver.setTemplateMode(HTML); 19 | templateResolver.setCharacterEncoding(UTF_8); 20 | 21 | TemplateEngine templateEngine = new TemplateEngine(); 22 | templateEngine.setTemplateResolver(templateResolver); 23 | 24 | return templateEngine.process(file, context); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/JwtAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.web.AuthenticationEntryPoint; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | import java.io.Serializable; 11 | 12 | @Component 13 | public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { 14 | 15 | @Override 16 | public void commence(HttpServletRequest request, 17 | HttpServletResponse response, 18 | AuthenticationException authException) throws IOException { 19 | 20 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/JwtAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import io.jsonwebtoken.ExpiredJwtException; 4 | import io.jsonwebtoken.SignatureException; 5 | import lk.teachmeit.boilerplate.constants.AuthConstants; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Qualifier; 8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 9 | import org.springframework.security.core.context.SecurityContextHolder; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 13 | import org.springframework.web.filter.OncePerRequestFilter; 14 | 15 | import javax.servlet.FilterChain; 16 | import javax.servlet.ServletException; 17 | import javax.servlet.http.HttpServletRequest; 18 | import javax.servlet.http.HttpServletResponse; 19 | import java.io.IOException; 20 | 21 | public class JwtAuthenticationFilter extends OncePerRequestFilter { 22 | 23 | @Qualifier("userService") 24 | @Autowired 25 | private UserDetailsService userDetailsService; 26 | 27 | @Autowired 28 | private TokenProvider jwtTokenUtil; 29 | 30 | @Override 31 | protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { 32 | String header = req.getHeader(AuthConstants.HEADER_STRING); 33 | String username = null; 34 | String authToken = null; 35 | if (header != null && header.startsWith(AuthConstants.TOKEN_PREFIX)) { 36 | authToken = header.replace(AuthConstants.TOKEN_PREFIX,""); 37 | try { 38 | username = jwtTokenUtil.getUsernameFromToken(authToken); 39 | } catch (IllegalArgumentException e) { 40 | logger.error("an error occured during getting username from token", e); 41 | } catch (ExpiredJwtException e) { 42 | logger.warn("the token is expired and not valid anymore", e); 43 | } catch(SignatureException e){ 44 | logger.error("Authentication Failed. Username or Password not valid."); 45 | } 46 | } else { 47 | logger.warn("couldn't find bearer string, will ignore the header"); 48 | } 49 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 50 | 51 | UserDetails userDetails = userDetailsService.loadUserByUsername(username); 52 | 53 | if (jwtTokenUtil.validateToken(authToken, userDetails)) { 54 | UsernamePasswordAuthenticationToken authentication = jwtTokenUtil.getAuthentication(authToken, SecurityContextHolder.getContext().getAuthentication(), userDetails); 55 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(req)); 56 | logger.info("authenticated user " + username + ", setting security context"); 57 | SecurityContextHolder.getContext().setAuthentication(authentication); 58 | } 59 | } 60 | 61 | chain.doFilter(req, res); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/RandomValueUtil.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import java.util.Random; 4 | 5 | public class RandomValueUtil { 6 | public static String getRandomNumberString(int bound) { 7 | Random rnd = new Random(); 8 | int number = rnd.nextInt(bound); 9 | return String.format("%06d", number); 10 | } 11 | 12 | public static String randomPasswordGenerator(int length){ 13 | String capitalCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 14 | String lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz"; 15 | String specialCharacters = "!@#$"; 16 | String numbers = "1234567890"; 17 | String combinedChars = capitalCaseLetters + lowerCaseLetters + specialCharacters + numbers; 18 | Random random = new Random(); 19 | char[] password = new char[length]; 20 | 21 | password[0] = lowerCaseLetters.charAt(random.nextInt(lowerCaseLetters.length())); 22 | password[1] = capitalCaseLetters.charAt(random.nextInt(capitalCaseLetters.length())); 23 | password[2] = specialCharacters.charAt(random.nextInt(specialCharacters.length())); 24 | password[3] = numbers.charAt(random.nextInt(numbers.length())); 25 | 26 | for(int i = 4; i< length ; i++) { 27 | password[i] = combinedChars.charAt(random.nextInt(combinedChars.length())); 28 | } 29 | return String.valueOf(password); 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/TokenProvider.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import io.jsonwebtoken.*; 4 | import lk.teachmeit.boilerplate.constants.AuthConstants; 5 | import lk.teachmeit.boilerplate.model.User; 6 | import lk.teachmeit.boilerplate.service.interfaces.UserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 9 | import org.springframework.security.core.Authentication; 10 | import org.springframework.security.core.GrantedAuthority; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.security.core.userdetails.UserDetails; 13 | import org.springframework.stereotype.Component; 14 | 15 | import javax.servlet.http.HttpServletRequest; 16 | import java.io.Serializable; 17 | import java.util.Arrays; 18 | import java.util.Collection; 19 | import java.util.Date; 20 | import java.util.function.Function; 21 | import java.util.stream.Collectors; 22 | 23 | @Component 24 | public class TokenProvider implements Serializable { 25 | 26 | @Autowired 27 | private UserService userService; 28 | 29 | public String getUsernameFromToken(String token) { 30 | return getClaimFromToken(token, Claims::getSubject); 31 | } 32 | 33 | public Date getExpirationDateFromToken(String token) { 34 | return getClaimFromToken(token, Claims::getExpiration); 35 | } 36 | 37 | public T getClaimFromToken(String token, Function claimsResolver) { 38 | final Claims claims = getAllClaimsFromToken(token); 39 | return claimsResolver.apply(claims); 40 | } 41 | 42 | private Claims getAllClaimsFromToken(String token) { 43 | return Jwts.parser() 44 | .setSigningKey(AuthConstants.SIGNING_KEY) 45 | .parseClaimsJws(token) 46 | .getBody(); 47 | } 48 | 49 | private Boolean isTokenExpired(String token) { 50 | final Date expiration = getExpirationDateFromToken(token); 51 | return expiration.before(new Date()); 52 | } 53 | 54 | public String generateToken(Authentication authentication) { 55 | final String authorities = authentication.getAuthorities().stream() 56 | .map(GrantedAuthority::getAuthority) 57 | .collect(Collectors.joining(",")); 58 | return Jwts.builder() 59 | .setSubject(authentication.getName()) 60 | .claim(AuthConstants.AUTHORITIES_KEY, authorities) 61 | .signWith(SignatureAlgorithm.HS256, AuthConstants.SIGNING_KEY) 62 | .setIssuedAt(new Date(System.currentTimeMillis())) 63 | .setExpiration(new Date(System.currentTimeMillis() + AuthConstants.ACCESS_TOKEN_VALIDITY_SECONDS*1000)) 64 | .compact(); 65 | } 66 | 67 | Boolean validateToken(String token, UserDetails userDetails) { 68 | final String username = getUsernameFromToken(token); 69 | return ( 70 | username.equals(userDetails.getUsername()) 71 | && !isTokenExpired(token)); 72 | } 73 | 74 | UsernamePasswordAuthenticationToken getAuthentication(final String token, final Authentication existingAuth, final UserDetails userDetails) { 75 | 76 | final JwtParser jwtParser = Jwts.parser().setSigningKey(AuthConstants.SIGNING_KEY); 77 | 78 | final Jws claimsJws = jwtParser.parseClaimsJws(token); 79 | 80 | final Claims claims = claimsJws.getBody(); 81 | 82 | final Collection authorities = 83 | Arrays.stream(claims.get(AuthConstants.AUTHORITIES_KEY).toString().split(",")) 84 | .map(SimpleGrantedAuthority::new) 85 | .collect(Collectors.toList()); 86 | 87 | return new UsernamePasswordAuthenticationToken(userDetails, "", authorities); 88 | } 89 | 90 | public User getAuthUser(HttpServletRequest req) { 91 | String header = req.getHeader(AuthConstants.HEADER_STRING); 92 | String authToken = header.replace(AuthConstants.TOKEN_PREFIX,""); 93 | User authUser = userService.findOne(getUsernameFromToken(authToken)); 94 | 95 | return authUser; 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/lk/teachmeit/boilerplate/util/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate.util; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 8 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.config.http.SessionCreationPolicy; 13 | import org.springframework.security.core.userdetails.UserDetailsService; 14 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 15 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 16 | 17 | import javax.annotation.Resource; 18 | 19 | @Configuration 20 | @EnableWebSecurity 21 | //@EnableGlobalMethodSecurity(securedEnabled = true) 22 | @EnableGlobalMethodSecurity(prePostEnabled = true) 23 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 24 | 25 | @Resource(name = "userService") 26 | private UserDetailsService userDetailsService; 27 | 28 | @Autowired 29 | private JwtAuthenticationEntryPoint unauthorizedHandler; 30 | 31 | @Override 32 | @Bean 33 | public AuthenticationManager authenticationManagerBean() throws Exception { 34 | return super.authenticationManagerBean(); 35 | } 36 | 37 | @Autowired 38 | public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { 39 | auth.userDetailsService(userDetailsService) 40 | .passwordEncoder(encoder()); 41 | } 42 | 43 | @Bean 44 | public JwtAuthenticationFilter authenticationTokenFilterBean() { 45 | return new JwtAuthenticationFilter(); 46 | } 47 | 48 | @Override 49 | protected void configure(HttpSecurity http) throws Exception { 50 | http.cors().and().csrf().disable(). 51 | authorizeRequests() 52 | .antMatchers("/auth/signup", "/auth/sign-in", "/auth/password/forgot", "/auth/password/verify-code", "/auth/password/reset", "/auth/email/verify").permitAll() 53 | .anyRequest().authenticated() 54 | .and() 55 | .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() 56 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 57 | http 58 | .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 59 | } 60 | 61 | @Bean 62 | public BCryptPasswordEncoder encoder(){ 63 | return new BCryptPasswordEncoder(); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/additional-spring-configuration-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": [ 3 | { 4 | "name": "email.username", 5 | "type": "java.lang.String", 6 | "description": "Description for email.username." 7 | }, 8 | { 9 | "name": "email.password", 10 | "type": "java.lang.String", 11 | "description": "Description for email.password." 12 | }, 13 | { 14 | "name": "email.host", 15 | "type": "java.lang.String", 16 | "description": "Description for email.host." 17 | }, 18 | { 19 | "name": "upload.path", 20 | "type": "java.lang.String", 21 | "description": "Description for upload.path." 22 | } 23 | ] } 24 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | spring.jpa.hibernate.ddl-auto=update 3 | spring.datasource.url=jdbc:mysql://localhost:3306/boilerplate 4 | spring.datasource.username=root 5 | spring.datasource.password=thot4hm! 6 | 7 | upload.path=/var/www/upload/ 8 | 9 | spring.thymeleaf.prefix=classpath:/templates/ 10 | 11 | spring.servlet.multipart.enabled=true 12 | spring.servlet.multipart.file-size-threshold=2KB 13 | spring.servlet.multipart.max-file-size=200MB 14 | spring.servlet.multipart.max-request-size=215MB 15 | 16 | email.username=********* 17 | email.password=******** 18 | email.host=smtp.gmail.com 19 | -------------------------------------------------------------------------------- /src/main/resources/templates/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/src/main/resources/templates/.DS_Store -------------------------------------------------------------------------------- /src/main/resources/templates/email/email-verification.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 65 | 66 | 67 |
68 |
69 |
70 | sample 71 |
72 | 73 | 80 | 81 | 87 |
88 |
89 | 90 | 91 | -------------------------------------------------------------------------------- /src/main/resources/templates/email/includes/email-footer.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/templates/email/includes/email-header.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/templates/email/statics/email.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/src/main/resources/templates/email/statics/email.css -------------------------------------------------------------------------------- /src/main/resources/templates/report/Code39.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/src/main/resources/templates/report/Code39.ttf -------------------------------------------------------------------------------- /src/main/resources/templates/report/credit-controll.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | report 4 | 5 | 6 | 48 | 49 | 50 | 51 | 52 |
53 |
54 | 55 |
56 | 57 |
58 | 59 | 60 |
61 |

CCMS

62 |

CCMS, Kandy

63 |

081-22222333

64 |
65 | 66 |
67 | 68 |
69 | 70 |
71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 87 | 88 | 89 | 90 | 91 |
First NameLast NameHospitalBooking DateAmount
82 | 83 | 84 | 85 | 86 |
Total
92 | 93 |
94 | 95 | 96 | -------------------------------------------------------------------------------- /src/test/._java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/src/test/._java -------------------------------------------------------------------------------- /src/test/java/._lk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/src/test/java/._lk -------------------------------------------------------------------------------- /src/test/java/lk/._teachmeit: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tharukaCodeWorks/springboot-jwt-boilerplate/b2ac6bc6adfaa047ac5a0999001040da43b42c9f/src/test/java/lk/._teachmeit -------------------------------------------------------------------------------- /src/test/java/lk/teachmeit/boilerplate/AuthApplicationTests.java: -------------------------------------------------------------------------------- 1 | package lk.teachmeit.boilerplate; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class AuthApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------