├── .gitignore ├── .mvn └── wrapper │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── README.md ├── bodyRequests.txt ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── classbdemo │ │ ├── ClassbDemoApplication.java │ │ ├── ServletInitializer.java │ │ ├── config │ │ ├── SecurityConfig.java │ │ └── SwaggerConfig.java │ │ ├── controllers │ │ ├── AuthController.java │ │ ├── CourseController.java │ │ ├── MarkController.java │ │ └── StudentController.java │ │ ├── dto │ │ ├── CreateMarkDTO.java │ │ ├── LoginRequest.java │ │ └── SignUpRequest.java │ │ ├── enumerations │ │ ├── EAccountStatus.java │ │ ├── EGender.java │ │ └── ERoleName.java │ │ ├── model │ │ ├── Course.java │ │ ├── Mark.java │ │ ├── Role.java │ │ ├── Student.java │ │ └── User.java │ │ ├── repositories │ │ ├── CourseRepository.java │ │ ├── IRoleRepository.java │ │ ├── IUserRepository.java │ │ ├── MarkRepository.java │ │ └── StudentRepository.java │ │ ├── security │ │ ├── CurrentUser.java │ │ ├── CustomUserDetailsService.java │ │ ├── JwtAuthenticationEntryPoint.java │ │ ├── JwtAuthenticationFilter.java │ │ ├── JwtTokenProvider.java │ │ └── UserPrincipal.java │ │ ├── services │ │ └── IMarkServices.java │ │ ├── servicesImpl │ │ └── MarkServiceImpl.java │ │ └── utils │ │ ├── APIResponse.java │ │ └── JwtAuthenticationResponse.java └── resources │ └── application.properties └── test └── java └── com └── example └── classbdemo └── ClassbDemoApplicationTests.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/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/Cyebukayire/Spring-Security/b7c0078988ad00ed4c6e03bcbe2c97cb94f4409a/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-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 | # spring-boot-class-demo 2 | -------------------------------------------------------------------------------- /bodyRequests.txt: -------------------------------------------------------------------------------- 1 | Signup: 2 | 3 | { 4 | "firstName": "Peace", 5 | "lastName": "Hanson", 6 | "username": "peace", 7 | "email": "peace@gmail.com", 8 | "password":"Peace@123", 9 | "mobile":"078834343", 10 | "roleName": "ROLE_ADMIN" 11 | } 12 | 13 | 14 | Signin: 15 | 16 | { 17 | 18 | "login": "peace@gmail.com", 19 | "password":"Peace@123" 20 | } 21 | -------------------------------------------------------------------------------- /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 | 5 | 4.0.0 6 | 7 | org.springframework.boot 8 | spring-boot-starter-parent 9 | 2.4.5 10 | 11 | 12 | com.example 13 | classb-demo 14 | 0.0.1-SNAPSHOT 15 | war 16 | classb-demo 17 | Demo project for class b 18 | 19 | 1.8 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-actuator 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-data-jpa 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | 36 | 37 | org.springframework.security 38 | spring-security-core 39 | 5.5.0 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-security 45 | 46 | 47 | 48 | 49 | org.springframework.security 50 | spring-security-test 51 | test 52 | 53 | 54 | 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-devtools 59 | runtime 60 | true 61 | 62 | 63 | mysql 64 | mysql-connector-java 65 | runtime 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-starter-tomcat 70 | provided 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-starter-test 75 | test 76 | 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-starter-validation 81 | 82 | 83 | 90 | 91 | org.springframework.security 92 | spring-security-core 93 | 5.5.0 94 | 95 | 96 | org.springframework.boot 97 | spring-boot-starter-security 98 | 99 | 100 | 101 | 102 | io.jsonwebtoken 103 | jjwt 104 | 0.9.1 105 | 106 | 107 | 108 | io.springfox 109 | springfox-boot-starter 110 | 3.0.0 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | org.springframework.boot 120 | spring-boot-maven-plugin 121 | 122 | 123 | org.apache.maven.plugins 124 | maven-compiler-plugin 125 | 126 | 9 127 | 9 128 | 129 | 130 | 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/ClassbDemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ClassbDemoApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ClassbDemoApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/ServletInitializer.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo; 2 | 3 | import org.springframework.boot.builder.SpringApplicationBuilder; 4 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 5 | 6 | public class ServletInitializer extends SpringBootServletInitializer { 7 | 8 | @Override 9 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 10 | return application.sources(ClassbDemoApplication.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.config; 2 | import org.springframework.beans.factory.annotation.Autowired; 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.http.HttpMethod; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.config.BeanIds; 8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.crypto.bcrypt.BCryptPasswordEncoder; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 16 | import org.springframework.web.cors.CorsConfiguration; 17 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 18 | import org.springframework.web.filter.CorsFilter; 19 | 20 | import com.example.classbdemo.security.CustomUserDetailsService; 21 | import com.example.classbdemo.security.JwtAuthenticationEntryPoint; 22 | import com.example.classbdemo.security.JwtAuthenticationFilter; 23 | 24 | @Configuration 25 | @EnableWebSecurity 26 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 27 | @Autowired 28 | CustomUserDetailsService customUserDetailsService; 29 | 30 | @Autowired 31 | private JwtAuthenticationEntryPoint unauthorizedHandler; 32 | 33 | @Bean 34 | public JwtAuthenticationFilter jwtAuthenticationFilter() { 35 | return new JwtAuthenticationFilter(); 36 | } 37 | 38 | @Override 39 | public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { 40 | authenticationManagerBuilder.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder()); 41 | } 42 | 43 | @Bean(BeanIds.AUTHENTICATION_MANAGER) 44 | @Override 45 | public AuthenticationManager authenticationManagerBean() throws Exception { 46 | return super.authenticationManagerBean(); 47 | } 48 | 49 | @Bean 50 | public PasswordEncoder passwordEncoder() { 51 | return new BCryptPasswordEncoder(); 52 | } 53 | 54 | @Bean 55 | public CorsFilter corsFilter() { 56 | final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 57 | final CorsConfiguration config = new CorsConfiguration(); 58 | config.setAllowCredentials(true); 59 | config.addAllowedOrigin("*"); 60 | config.addAllowedHeader("*"); 61 | config.addAllowedMethod("OPTIONS"); 62 | config.addAllowedMethod("HEAD"); 63 | config.addAllowedMethod("GET"); 64 | config.addAllowedMethod("PUT"); 65 | config.addAllowedMethod("POST"); 66 | config.addAllowedMethod("DELETE"); 67 | config.addAllowedMethod("PATCH"); 68 | source.registerCorsConfiguration("/**", config); 69 | return new CorsFilter(source); 70 | } 71 | 72 | @Override 73 | protected void configure(HttpSecurity http) throws Exception { 74 | http 75 | .csrf().disable() 76 | .exceptionHandling() 77 | .authenticationEntryPoint(unauthorizedHandler).and() 78 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests() 79 | .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() 80 | .antMatchers("/", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", 81 | "/**/*.css", "/**/*.js").permitAll() 82 | .antMatchers("/api/auth/**").permitAll() 83 | .antMatchers( "/swagger-resources/**", "/swagger-ui.html","/api-docs","/v3/api-docs/**","/v2/api-docs/**").permitAll() 84 | .antMatchers(HttpMethod.GET, "/api/public/**", "/api/users/**", "/ussd/**").permitAll().anyRequest() 85 | .authenticated(); 86 | http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import springfox.documentation.builders.PathSelectors; 6 | import springfox.documentation.builders.RequestHandlerSelectors; 7 | import springfox.documentation.service.*; 8 | import springfox.documentation.spi.DocumentationType; 9 | import springfox.documentation.spi.service.contexts.SecurityContext; 10 | import springfox.documentation.spring.web.plugins.Docket; 11 | 12 | import java.util.Arrays; 13 | import java.util.Collections; 14 | import java.util.List; 15 | 16 | 17 | @Configuration 18 | public class SwaggerConfig { 19 | 20 | public static final String AUTHORIZATION_HEADER = "Authorization"; 21 | 22 | private ApiInfo apiInfo() { 23 | return new ApiInfo("My REST API", 24 | "Some custom description of API.", 25 | "1.0", 26 | "Terms of service", 27 | new Contact("Muhodari Sage", "www.sage.com", "sagemuho@gmail.com"), 28 | "License of API", 29 | "API license URL", 30 | Collections.emptyList()); 31 | } 32 | 33 | @Bean 34 | public Docket api() { 35 | return new Docket(DocumentationType.SWAGGER_2) 36 | .apiInfo(apiInfo()) 37 | .securityContexts(Arrays.asList(securityContext())) 38 | .securitySchemes(Arrays.asList(apiKey())) 39 | .select() 40 | .apis(RequestHandlerSelectors.basePackage("com.example.classbdemo.controllers")) 41 | .paths(PathSelectors.any()) 42 | .build(); 43 | } 44 | 45 | private ApiKey apiKey() { 46 | return new ApiKey("JWT", AUTHORIZATION_HEADER, "header"); 47 | } 48 | 49 | private SecurityContext securityContext() { 50 | return SecurityContext.builder() 51 | .securityReferences(defaultAuth()) 52 | .build(); 53 | } 54 | 55 | List defaultAuth() { 56 | AuthorizationScope authorizationScope 57 | = new AuthorizationScope("global", "accessEverything"); 58 | AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; 59 | authorizationScopes[0] = authorizationScope; 60 | return Arrays.asList(new SecurityReference("JWT", authorizationScopes)); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/controllers/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.controllers; 2 | 3 | import java.net.URI; 4 | import java.util.Collections; 5 | import java.util.Optional; 6 | 7 | import javax.validation.Valid; 8 | 9 | import com.example.classbdemo.dto.LoginRequest; 10 | import com.example.classbdemo.dto.SignUpRequest; 11 | import com.example.classbdemo.enumerations.EAccountStatus; 12 | import com.example.classbdemo.model.Role; 13 | import com.example.classbdemo.model.User; 14 | import com.example.classbdemo.repositories.IRoleRepository; 15 | import com.example.classbdemo.repositories.IUserRepository; 16 | import com.example.classbdemo.security.JwtTokenProvider; 17 | import com.example.classbdemo.utils.APIResponse; 18 | import com.example.classbdemo.utils.JwtAuthenticationResponse; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.http.HttpStatus; 21 | import org.springframework.http.ResponseEntity; 22 | import org.springframework.security.authentication.AuthenticationManager; 23 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 24 | import org.springframework.security.core.Authentication; 25 | import org.springframework.security.core.context.SecurityContextHolder; 26 | import org.springframework.security.crypto.password.PasswordEncoder; 27 | import org.springframework.web.bind.annotation.PathVariable; 28 | import org.springframework.web.bind.annotation.PostMapping; 29 | import org.springframework.web.bind.annotation.PutMapping; 30 | import org.springframework.web.bind.annotation.RequestBody; 31 | import org.springframework.web.bind.annotation.RequestHeader; 32 | import org.springframework.web.bind.annotation.RequestMapping; 33 | import org.springframework.web.bind.annotation.RestController; 34 | import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 35 | 36 | @RestController 37 | @RequestMapping("/api/auth") 38 | public class AuthController { 39 | 40 | @Autowired 41 | private AuthenticationManager authenticationManager; 42 | 43 | @Autowired 44 | private IUserRepository userRepository; 45 | 46 | @Autowired 47 | private IRoleRepository roleRepository; 48 | 49 | @Autowired 50 | private PasswordEncoder passwordEncoder; 51 | 52 | @Autowired 53 | private JwtTokenProvider tokenProvider; 54 | 55 | @PostMapping("/signin") 56 | public ResponseEntity authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { 57 | 58 | Optional findByEmail = userRepository.findByEmailOrMobileOrUsername(loginRequest.getLogin(),loginRequest.getLogin(),loginRequest.getLogin()); 59 | if(findByEmail.isPresent()) { 60 | if(!(findByEmail.get().getStatus().equals(EAccountStatus.ACTIVE))) { 61 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid account status"); 62 | } 63 | }else { 64 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unknown account"); 65 | } 66 | Authentication authentication = authenticationManager.authenticate( 67 | new UsernamePasswordAuthenticationToken(loginRequest.getLogin(), loginRequest.getPassword())); 68 | 69 | SecurityContextHolder.getContext().setAuthentication(authentication); 70 | 71 | String jwt = tokenProvider.generateToken(authentication); 72 | return ResponseEntity.ok(new JwtAuthenticationResponse(jwt)); 73 | } 74 | 75 | @PostMapping("/signup") 76 | public ResponseEntity registerUser(@Valid @RequestBody SignUpRequest signUpRequest) { 77 | 78 | if (signUpRequest.getEmail() != null && userRepository.existsByEmail(signUpRequest.getEmail())) { 79 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new APIResponse("Email Address already in use!", true)); 80 | } 81 | 82 | if (userRepository.existsByMobile(signUpRequest.getMobile())) { 83 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body( new APIResponse("Phone number already in use!", true)); 84 | } 85 | 86 | User user = new User(signUpRequest.getFirstName(), signUpRequest.getLastName(), signUpRequest.getMobile(), 87 | signUpRequest.getEmail(), signUpRequest.getPassword()); 88 | 89 | user.setUsername(user.getEmail()); 90 | user.setPassword(passwordEncoder.encode(user.getPassword())); 91 | user.setActivationCode(user.getMobile()); 92 | user.setStatus(EAccountStatus.ACTIVE); 93 | user.setFullName(signUpRequest.getFirstName()+" "+signUpRequest.getLastName()); 94 | 95 | Optional userRole = roleRepository.findByName(signUpRequest.getRoleName()); 96 | 97 | if(!userRole.isPresent()){ 98 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new APIResponse("Role name not registered", true)); 99 | } 100 | 101 | user.setRoles(Collections.singleton(userRole.get())); 102 | User result = userRepository.save(user); 103 | URI location = ServletUriComponentsBuilder.fromCurrentContextPath().path("/users/{username}") 104 | .buildAndExpand(result.getUsername()).toUri(); 105 | 106 | return ResponseEntity.created(location).body(new APIResponse("Successfully registered", true)); 107 | } 108 | } -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/controllers/CourseController.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.controllers; 2 | 3 | import com.example.classbdemo.model.Course; 4 | import com.example.classbdemo.repositories.CourseRepository; 5 | import com.example.classbdemo.repositories.MarkRepository; 6 | import com.example.classbdemo.repositories.StudentRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | import javax.validation.Valid; 13 | import java.util.List; 14 | import java.util.Optional; 15 | 16 | @RestController 17 | @RequestMapping("/courses") 18 | public class CourseController { 19 | 20 | @Autowired 21 | private CourseRepository courseRepository; 22 | 23 | 24 | private MarkRepository markRepository; 25 | private StudentRepository studentRepository; 26 | 27 | // getting all courses 28 | @GetMapping 29 | public List getAll() { 30 | 31 | return courseRepository.findAll(); 32 | } 33 | 34 | //get course by id 35 | @GetMapping("/{id}") 36 | public ResponseEntity getById(@PathVariable(value="id") Long id) { 37 | Optional course = courseRepository.findById(id); 38 | if(course.isPresent()) { 39 | return ResponseEntity.ok(course.get()) ; 40 | } 41 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new Course()); 42 | } 43 | 44 | // inserting a new course 45 | @PostMapping 46 | public ResponseEntity save(@Valid @RequestBody Course course){ 47 | 48 | if(courseRepository.existsByNameAndCode(course.getName(), course.getCode())) { 49 | return ResponseEntity.status(HttpStatus.CREATED).body(courseRepository.findByNameAndCode(course.getName(), course.getCode()).get()); 50 | } 51 | courseRepository.save(course); 52 | 53 | return ResponseEntity.status(HttpStatus.CREATED).body(course); 54 | } 55 | 56 | // updating a course by id 57 | @PutMapping("/{id}") 58 | public ResponseEntity updateCourseById(@PathVariable Long id, @RequestBody Course course){ 59 | Optional CourseData = courseRepository.findById(id); 60 | if(CourseData.isPresent()){ 61 | Course _course = CourseData.get(); 62 | // _course.setId(course.getId()); 63 | _course.setId(id); 64 | _course.setName(course.getName()); 65 | _course.setCode(course.getCode()); 66 | return new ResponseEntity<>(courseRepository.save(_course),HttpStatus.OK); 67 | } 68 | else { 69 | return new ResponseEntity<>(HttpStatus.NOT_FOUND); 70 | } 71 | } 72 | 73 | //Delete course by ID 74 | @DeleteMapping("/{id}") 75 | public void deleteCourseById(@PathVariable Long id){ 76 | courseRepository.deleteById(id); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/controllers/MarkController.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.controllers; 2 | 3 | import com.example.classbdemo.dto.CreateMarkDTO; 4 | import com.example.classbdemo.model.Course; 5 | import com.example.classbdemo.model.Mark; 6 | import com.example.classbdemo.model.Student; 7 | import com.example.classbdemo.repositories.CourseRepository; 8 | import com.example.classbdemo.repositories.MarkRepository; 9 | import com.example.classbdemo.repositories.StudentRepository; 10 | import com.example.classbdemo.utils.APIResponse; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.web.bind.annotation.*; 15 | import com.example.classbdemo.services.IMarkServices; 16 | 17 | import javax.validation.Valid; 18 | import java.util.List; 19 | import java.util.Optional; 20 | 21 | @RestController 22 | @RequestMapping("/marks") 23 | public class MarkController{ 24 | @Autowired 25 | private MarkRepository markRepository; 26 | 27 | @Autowired 28 | private StudentRepository StudentRepository; 29 | 30 | @Autowired 31 | private CourseRepository courseRepository; 32 | 33 | private IMarkServices markService; 34 | 35 | // get all courses 36 | @GetMapping 37 | public List getAll() { 38 | 39 | return markRepository.findAll(); 40 | } 41 | 42 | // get course by id 43 | @GetMapping("/{id}") 44 | public ResponseEntity getById(@PathVariable(value="id") Long id) { 45 | 46 | Optional mark = markRepository.findById(id); 47 | if(mark.isPresent()) { 48 | return ResponseEntity.ok(mark.get()) ; 49 | } 50 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new Course()); 51 | 52 | } 53 | 54 | // adding new marks 55 | @PostMapping 56 | public ResponseEntity save(@Valid @RequestBody CreateMarkDTO dto){ 57 | Optional course = courseRepository.findById(dto.getCourseId()); 58 | if(!course.isPresent()) { 59 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new APIResponse("Course not found", false)); 60 | } 61 | Optional student = StudentRepository.findById(dto.getStudentId()); 62 | 63 | if(!student.isPresent()) { 64 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new APIResponse("Student not found", false)); 65 | } 66 | 67 | return ResponseEntity.status(HttpStatus.CREATED).body(markService.save(dto, student.get(), course.get())); 68 | } 69 | 70 | // update MARKS by id 71 | @PutMapping("{id}") 72 | public ResponseEntity updateMarkById(@PathVariable Long id, @RequestBody CreateMarkDTO markDTO){ 73 | Optional MarkData = markRepository.findById(id); 74 | Optional course = courseRepository.findById(markDTO.getCourseId()); 75 | if(!course.isPresent()) { 76 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new APIResponse("Course not found", false)); 77 | } 78 | Optional student = StudentRepository.findById(markDTO.getStudentId()); 79 | 80 | if(!student.isPresent()) { 81 | ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new APIResponse("Student not found", false)); 82 | } 83 | 84 | if(MarkData.isPresent()){ 85 | Mark _mark = MarkData.get(); 86 | _mark.setStudent(student.get()); 87 | _mark.setCourse(course.get()); 88 | _mark.setScored(markDTO.getScored()); 89 | _mark.setMax(markDTO.getMax()); 90 | 91 | return new ResponseEntity<>(markRepository.save(_mark),HttpStatus.OK); 92 | } 93 | else { 94 | return new ResponseEntity<>(HttpStatus.NOT_FOUND); 95 | } 96 | } 97 | 98 | // delete marks by id 99 | @DeleteMapping("/{id}") 100 | public void deleteMarkById(@PathVariable Long id){ 101 | courseRepository.deleteById(id); 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/controllers/StudentController.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.controllers; 2 | 3 | import com.example.classbdemo.model.Course; 4 | import com.example.classbdemo.model.Student; 5 | import com.example.classbdemo.repositories.StudentRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import javax.validation.Valid; 12 | import java.util.List; 13 | import java.util.Optional; 14 | 15 | @RestController 16 | @RequestMapping("/students") 17 | public class StudentController { 18 | @Autowired 19 | private StudentRepository studentRepository; 20 | 21 | 22 | // get all student 23 | @GetMapping() 24 | public List getAll() { 25 | 26 | return studentRepository.findAll(); 27 | } 28 | 29 | // get student by id 30 | @GetMapping("/{id}") 31 | public ResponseEntity getById(@PathVariable(value="id") Long id) { 32 | 33 | Optional student = studentRepository.findById(id); 34 | if(student.isPresent()) { 35 | return ResponseEntity.ok(student.get()) ; 36 | } 37 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new Course()); 38 | 39 | } 40 | 41 | // save new student 42 | 43 | @PostMapping 44 | public ResponseEntity save(@Valid @RequestBody Student student){ 45 | 46 | if(studentRepository.findById(student.getId())!=null){ 47 | return ResponseEntity.status(HttpStatus.CREATED).body(studentRepository.findById(student.getId())); 48 | } 49 | studentRepository.save(student); 50 | 51 | return ResponseEntity.status(HttpStatus.CREATED).body(student); 52 | } 53 | 54 | //Update student by id 55 | @PutMapping("/{id}") 56 | public ResponseEntity updateStudentById(@PathVariable Long id, @RequestBody Student student){ 57 | Optional StudentData = studentRepository.findById(id); 58 | 59 | if(StudentData.isPresent()){ 60 | Student _student = StudentData.get(); 61 | _student.setId(student.getId()); 62 | _student.setClassName(student.getClassName()); 63 | _student.setGender(student.getGender()); 64 | _student.setNames(student.getNames()); 65 | 66 | return new ResponseEntity<>(studentRepository.save(_student),HttpStatus.OK); 67 | } 68 | else { 69 | return new ResponseEntity<>(HttpStatus.NOT_FOUND); 70 | } 71 | } 72 | 73 | //Delete student by ID 74 | @DeleteMapping("/{id}") 75 | public void deleteStudentById(@PathVariable Long id){ 76 | studentRepository.deleteById(id); 77 | } 78 | 79 | 80 | 81 | 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/dto/CreateMarkDTO.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.dto; 2 | 3 | import com.sun.istack.NotNull; 4 | 5 | public class CreateMarkDTO { 6 | 7 | @NotNull 8 | private int max; 9 | 10 | @NotNull 11 | private int scored; 12 | 13 | private long studentId; 14 | 15 | private long courseId; 16 | 17 | public int getMax() { 18 | return max; 19 | } 20 | 21 | public void setMax(int max) { 22 | this.max = max; 23 | } 24 | 25 | public int getScored() { 26 | return scored; 27 | } 28 | 29 | public void setScored(int scored) { 30 | this.scored = scored; 31 | } 32 | 33 | public long getStudentId() { 34 | return studentId; 35 | } 36 | 37 | public void setStudentId(long studentId) { 38 | this.studentId = studentId; 39 | } 40 | 41 | public long getCourseId() { 42 | return courseId; 43 | } 44 | 45 | public void setCourseId(long courseId) { 46 | this.courseId = courseId; 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/dto/LoginRequest.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.dto; 2 | 3 | import javax.validation.constraints.NotBlank; 4 | 5 | public class LoginRequest { 6 | 7 | @NotBlank 8 | private String login; 9 | 10 | @NotBlank 11 | private String password; 12 | 13 | public String getLogin() { 14 | return login; 15 | } 16 | 17 | public void setLogin(String login) { 18 | this.login = login; 19 | } 20 | 21 | public String getPassword() { 22 | return password; 23 | } 24 | 25 | public void setPassword(String password) { 26 | this.password = password; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/dto/SignUpRequest.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.dto; 2 | 3 | import com.example.classbdemo.enumerations.ERoleName; 4 | 5 | import javax.validation.constraints.Email; 6 | import javax.validation.constraints.NotBlank; 7 | 8 | @SuppressWarnings("unused") 9 | public class SignUpRequest { 10 | 11 | @NotBlank 12 | private String firstName; 13 | 14 | @NotBlank 15 | private String lastName; 16 | 17 | @NotBlank 18 | private String mobile; 19 | 20 | @Email 21 | private String email; 22 | 23 | @NotBlank 24 | private String password; 25 | 26 | private ERoleName roleName; 27 | 28 | public String getFirstName() { 29 | return firstName; 30 | } 31 | 32 | public void setFirstName(String firstName) { 33 | this.firstName = firstName; 34 | } 35 | 36 | public String getLastName() { 37 | return lastName; 38 | } 39 | 40 | public void setLastName(String lastName) { 41 | this.lastName = lastName; 42 | } 43 | 44 | public String getMobile() { 45 | return mobile; 46 | } 47 | 48 | public void setMobile(String mobile) { 49 | this.mobile = mobile; 50 | } 51 | 52 | public String getEmail() { 53 | return email; 54 | } 55 | 56 | public void setEmail(String email) { 57 | this.email = email; 58 | } 59 | 60 | public String getPassword() { 61 | return password; 62 | } 63 | 64 | public void setPassword(String password) { 65 | this.password = password; 66 | } 67 | 68 | public ERoleName getRoleName() { 69 | return roleName; 70 | } 71 | 72 | public void setRoleName(ERoleName roleName) { 73 | this.roleName = roleName; 74 | } 75 | 76 | } 77 | 78 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/enumerations/EAccountStatus.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.enumerations; 2 | 3 | public enum EAccountStatus { 4 | PENDING, ACTIVE, DISABLED, SUSPENDED, EXPIRED, RESET 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/enumerations/EGender.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.enumerations; 2 | 3 | public enum EGender { 4 | 5 | MALE, FEMALE 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/enumerations/ERoleName.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.enumerations; 2 | 3 | public enum ERoleName { 4 | ROLE_ADMIN, 5 | ROLE_USER 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/model/Course.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.model; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | 8 | import com.sun.istack.NotNull; 9 | 10 | @Entity 11 | @Table(name="courses") 12 | public class Course { 13 | 14 | @Id 15 | @GeneratedValue 16 | private Long id; 17 | 18 | @NotNull 19 | private String name; 20 | 21 | @NotNull 22 | private String code; 23 | 24 | public Long getId() { 25 | return id; 26 | } 27 | 28 | public void setId(Long id) { 29 | this.id = id; 30 | } 31 | 32 | public String getName() { 33 | return name; 34 | } 35 | 36 | public void setName(String name) { 37 | this.name = name; 38 | } 39 | 40 | public String getCode() { 41 | return code; 42 | } 43 | 44 | public void setCode(String code) { 45 | this.code = code; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/model/Mark.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.model; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | import javax.persistence.ManyToOne; 7 | import javax.persistence.Table; 8 | 9 | import com.sun.istack.NotNull; 10 | 11 | @Entity 12 | @Table(name="marks") 13 | public class Mark { 14 | 15 | @Id 16 | @GeneratedValue 17 | private Long id; 18 | 19 | @NotNull 20 | private int max; 21 | 22 | @NotNull 23 | private int scored; 24 | 25 | @ManyToOne 26 | private Course course; 27 | 28 | @ManyToOne 29 | private Student student; 30 | 31 | public Long getId() { 32 | return id; 33 | } 34 | 35 | public void setId(Long id) { 36 | this.id = id; 37 | } 38 | 39 | public int getMax() { 40 | return max; 41 | } 42 | 43 | public void setMax(int max) { 44 | this.max = max; 45 | } 46 | 47 | public int getScored() { 48 | return scored; 49 | } 50 | 51 | public void setScored(int scored) { 52 | this.scored = scored; 53 | } 54 | 55 | public Course getCourse() { 56 | return course; 57 | } 58 | 59 | public void setCourse(Course course) { 60 | this.course = course; 61 | } 62 | 63 | public Student getStudent() { 64 | return student; 65 | } 66 | 67 | public void setStudent(Student student) { 68 | this.student = student; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.model; 2 | import javax.persistence.*; 3 | import javax.validation.constraints.NotNull; 4 | import javax.validation.constraints.Size; 5 | 6 | import com.example.classbdemo.enumerations.ERoleName; 7 | 8 | 9 | @Entity 10 | @Table(name = "roles") 11 | 12 | public class Role { 13 | @Id 14 | @GeneratedValue(strategy = GenerationType.IDENTITY) 15 | private Long id; 16 | 17 | @Enumerated(EnumType.STRING) 18 | @Column(length = 60) 19 | private ERoleName name; 20 | 21 | public Role(ERoleName name) { 22 | this.name = name; 23 | } 24 | 25 | public Role() { 26 | 27 | } 28 | 29 | public Long getId() { 30 | return id; 31 | } 32 | 33 | public void setId(Long id) { 34 | this.id = id; 35 | } 36 | 37 | public ERoleName getName() { 38 | return name; 39 | } 40 | 41 | public void setName(ERoleName name) { 42 | this.name = name; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/model/Student.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.model; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | 8 | import com.example.classbdemo.enumerations.EGender; 9 | import com.sun.istack.NotNull; 10 | 11 | @Entity 12 | @Table(name="students") 13 | public class Student { 14 | 15 | @Id 16 | @GeneratedValue 17 | private long id; 18 | 19 | @NotNull 20 | private String names; 21 | 22 | private EGender gender; 23 | 24 | private String className; 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 getNames() { 35 | return names; 36 | } 37 | 38 | public void setNames(String names) { 39 | this.names = names; 40 | } 41 | 42 | public EGender getGender() { 43 | return gender; 44 | } 45 | 46 | public void setGender(EGender gender) { 47 | this.gender = gender; 48 | } 49 | 50 | public String getClassName() { 51 | return className; 52 | } 53 | 54 | public void setClassName(String className) { 55 | this.className = className; 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/model/User.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.model; 2 | import java.util.HashSet; 3 | import java.util.Set; 4 | 5 | import javax.persistence.*; 6 | import javax.validation.constraints.Email; 7 | import javax.validation.constraints.NotNull; 8 | import javax.validation.constraints.Size; 9 | 10 | import com.example.classbdemo.enumerations.EAccountStatus; 11 | import com.fasterxml.jackson.annotation.JsonIgnore; 12 | 13 | @Entity 14 | @Table(name="users") 15 | 16 | public class User { 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private Long id; 20 | 21 | @NotNull(message = "first name is compulsory") 22 | private String firstName; 23 | 24 | @NotNull(message = "last name is compulsory") 25 | private String lastName; 26 | 27 | private String fullName; 28 | 29 | @NotNull 30 | private String username; 31 | 32 | private String mobile; 33 | 34 | @NotNull 35 | @Email 36 | private String email; 37 | 38 | @Enumerated(EnumType.STRING) 39 | private EAccountStatus status; 40 | 41 | @JsonIgnore 42 | @NotNull 43 | private String password; 44 | 45 | private String activationCode; 46 | 47 | @ManyToMany(fetch = FetchType.LAZY) 48 | @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) 49 | private Set roles = new HashSet<>(); 50 | 51 | public User() { 52 | 53 | } 54 | 55 | public User(@NotNull(message = "first name is compulsory") String firstName, 56 | @NotNull(message = "last name is compulsory") String lastName, @NotNull String mobile, 57 | @NotNull @Email @Size(max = 100) String email, @NotNull @Size(min = 5, max = 100) String password) { 58 | super(); 59 | this.firstName = firstName; 60 | this.lastName = lastName; 61 | this.mobile = mobile; 62 | this.email = email; 63 | this.password = password; 64 | } 65 | 66 | public User(@NotNull(message = "first name is compulsory") String firstName, 67 | @NotNull(message = "last name is compulsory") String lastName, 68 | @NotNull @Email @Size(max = 100) String email, @NotNull @Size(min = 5, max = 100) String password) { 69 | super(); 70 | this.firstName = firstName; 71 | this.lastName = lastName; 72 | this.email = email; 73 | this.password = password; 74 | } 75 | 76 | public Long getId() { 77 | return id; 78 | } 79 | 80 | public void setId(Long id) { 81 | this.id = id; 82 | } 83 | 84 | public String getFirstName() { 85 | return firstName; 86 | } 87 | 88 | public void setFirstName(String firstName) { 89 | this.firstName = firstName; 90 | } 91 | 92 | public String getLastName() { 93 | return lastName; 94 | } 95 | 96 | public void setLastName(String lastName) { 97 | this.lastName = lastName; 98 | } 99 | 100 | public String getFullName() { 101 | return fullName; 102 | } 103 | 104 | public void setFullName(String fullName) { 105 | this.fullName = fullName; 106 | } 107 | 108 | public String getUsername() { 109 | return username; 110 | } 111 | 112 | public void setUsername(String username) { 113 | this.username = username; 114 | } 115 | 116 | public String getMobile() { 117 | return mobile; 118 | } 119 | 120 | public void setMobile(String mobile) { 121 | this.mobile = mobile; 122 | } 123 | 124 | public String getEmail() { 125 | return email; 126 | } 127 | 128 | public void setEmail(String email) { 129 | this.email = email; 130 | } 131 | 132 | public EAccountStatus getStatus() { 133 | return status; 134 | } 135 | 136 | public void setStatus(EAccountStatus status) { 137 | this.status = status; 138 | } 139 | 140 | public String getPassword() { 141 | return password; 142 | } 143 | 144 | public void setPassword(String password) { 145 | this.password = password; 146 | } 147 | 148 | public String getActivationCode() { 149 | return activationCode; 150 | } 151 | 152 | public void setActivationCode(String activationCode) { 153 | this.activationCode = activationCode; 154 | } 155 | 156 | public Set getRoles() { 157 | return roles; 158 | } 159 | 160 | public void setRoles(Set roles) { 161 | this.roles = roles; 162 | } 163 | 164 | 165 | } 166 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/repositories/CourseRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.repositories; 2 | 3 | 4 | import java.util.Optional; 5 | 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import com.example.classbdemo.model.Course; 10 | 11 | @Repository 12 | public interface CourseRepository extends JpaRepository { 13 | 14 | boolean existsByNameAndCode(String name, String code); 15 | 16 | Optional findByNameAndCode(String name, String code); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/repositories/IRoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.repositories; 2 | 3 | import java.util.Optional; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import com.example.classbdemo.enumerations.ERoleName; 9 | import com.example.classbdemo.model.Role; 10 | 11 | public interface IRoleRepository extends JpaRepository{ 12 | Optional findByName(ERoleName roleName); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/repositories/IUserRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.repositories; 2 | import org.springframework.data.jpa.repository.JpaRepository; 3 | import org.springframework.stereotype.Repository; 4 | 5 | import com.example.classbdemo.model.User; 6 | 7 | import java.util.Optional; 8 | 9 | public interface IUserRepository extends JpaRepository{ 10 | Optional findByEmail(String usernameOrMobileOrEmail); 11 | 12 | Optional findByEmailOrMobileOrUsername(String usernameOrMobileOrEmail, String usernameOrMobileOrEmail2, 13 | String usernameOrMobileOrEmail3); 14 | 15 | boolean existsByEmail(String email); 16 | 17 | boolean existsByMobile(String mobile); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/repositories/MarkRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.repositories; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.example.classbdemo.model.Mark; 7 | 8 | @Repository 9 | public interface MarkRepository extends JpaRepository { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/repositories/StudentRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.repositories; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.example.classbdemo.model.Student; 7 | 8 | @Repository 9 | public interface StudentRepository extends JpaRepository { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/security/CurrentUser.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.security; 2 | 3 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 4 | import java.lang.annotation.*; 5 | 6 | @Target({ ElementType.PARAMETER, ElementType.TYPE }) 7 | @Retention(RetentionPolicy.RUNTIME) 8 | @Documented 9 | @AuthenticationPrincipal 10 | public @interface CurrentUser { 11 | } 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/security/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | import org.springframework.security.core.userdetails.UserDetailsService; 6 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import com.example.classbdemo.model.User; 11 | import com.example.classbdemo.repositories.IUserRepository; 12 | 13 | @Service 14 | public class CustomUserDetailsService implements UserDetailsService { 15 | 16 | @Autowired 17 | private IUserRepository userRepository; 18 | 19 | @Override 20 | @Transactional 21 | public UserDetails loadUserByUsername(String usernameOrMobileOrEmail) throws UsernameNotFoundException { 22 | User user = userRepository 23 | .findByEmailOrMobileOrUsername(usernameOrMobileOrEmail,usernameOrMobileOrEmail,usernameOrMobileOrEmail) 24 | .orElseThrow(() -> new UsernameNotFoundException( 25 | "User not found with mobile or email : " + usernameOrMobileOrEmail)); 26 | 27 | return UserPrincipal.create(user); 28 | } 29 | 30 | @Transactional 31 | public UserDetails loadUserById(Long id) { 32 | User user = userRepository.findById(id) 33 | .orElseThrow(() -> new UsernameNotFoundException("User not found with id : " + id)); 34 | return UserPrincipal.create(user); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/security/JwtAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.security; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.security.core.AuthenticationException; 6 | import org.springframework.security.web.AuthenticationEntryPoint; 7 | import org.springframework.stereotype.Component; 8 | 9 | import javax.servlet.ServletException; 10 | import javax.servlet.http.HttpServletRequest; 11 | import javax.servlet.http.HttpServletResponse; 12 | import java.io.IOException; 13 | 14 | @Component 15 | public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { 16 | 17 | private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class); 18 | 19 | @Override 20 | public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, 21 | AuthenticationException e) throws IOException, ServletException { 22 | logger.error("Responding with unauthorized error. Message - {}", e.getMessage()); 23 | httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, 24 | "Bad credentials. Please create an account if you don't have one."); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/security/JwtAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.security; 2 | import org.slf4j.Logger; 3 | import org.slf4j.LoggerFactory; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 6 | import org.springframework.security.core.context.SecurityContextHolder; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 9 | import org.springframework.util.StringUtils; 10 | import org.springframework.web.filter.OncePerRequestFilter; 11 | import javax.servlet.FilterChain; 12 | import javax.servlet.ServletException; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.io.IOException; 16 | 17 | public class JwtAuthenticationFilter extends OncePerRequestFilter { 18 | 19 | @Autowired 20 | private JwtTokenProvider tokenProvider; 21 | 22 | @Autowired 23 | private CustomUserDetailsService customUserDetailsService; 24 | 25 | private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class); 26 | 27 | @Override 28 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 29 | throws ServletException, IOException { 30 | try { 31 | String jwt = getJwtFromRequest(request); 32 | 33 | if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) { 34 | Long userId = tokenProvider.getUserIdFromJWT(jwt); 35 | 36 | UserDetails userDetails = customUserDetailsService.loadUserById(userId); 37 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( 38 | userDetails, null, userDetails.getAuthorities()); 39 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 40 | 41 | SecurityContextHolder.getContext().setAuthentication(authentication); 42 | } 43 | } catch (Exception ex) { 44 | logger.error("Could not set user authentication in security context", ex); 45 | } 46 | 47 | filterChain.doFilter(request, response); 48 | } 49 | 50 | private String getJwtFromRequest(HttpServletRequest request) { 51 | String bearerToken = request.getHeader("Authorization"); 52 | System.out.println("Our token is:"+ bearerToken); 53 | if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { 54 | return bearerToken.substring(7, bearerToken.length()); 55 | } 56 | return null; 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/security/JwtTokenProvider.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.security; 2 | import java.util.Date; 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Value; 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.stereotype.Component; 13 | 14 | import io.jsonwebtoken.Claims; 15 | import io.jsonwebtoken.ExpiredJwtException; 16 | import io.jsonwebtoken.Jwts; 17 | import io.jsonwebtoken.MalformedJwtException; 18 | import io.jsonwebtoken.SignatureAlgorithm; 19 | import io.jsonwebtoken.SignatureException; 20 | import io.jsonwebtoken.UnsupportedJwtException; 21 | 22 | 23 | @Component 24 | public class JwtTokenProvider { 25 | private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class); 26 | 27 | @Value("${jwt.security.key}") 28 | private String jwtSecret; 29 | 30 | @Value("${jwt.security.expirationInMs}") 31 | private int jwtExpirationInMs; 32 | 33 | public String generateToken(Authentication authentication) { 34 | 35 | UserPrincipal userDetails = (UserPrincipal) authentication.getPrincipal(); 36 | 37 | Date now = new Date(); 38 | Date expiryDate = new Date(now.getTime() + jwtExpirationInMs); 39 | 40 | Set grantedAuthorities = new HashSet<>(); 41 | for (GrantedAuthority role :userDetails.getAuthorities()){ 42 | grantedAuthorities.add(new SimpleGrantedAuthority(role.getAuthority())); 43 | } 44 | 45 | String token = Jwts .builder() .setId(userDetails.getId()+"") 46 | .setSubject(userDetails.getId()+"") 47 | .claim("authorities",grantedAuthorities) 48 | .claim("user",userDetails) 49 | 50 | .setIssuedAt(new 51 | Date(System.currentTimeMillis())) .setExpiration(expiryDate) 52 | .signWith(SignatureAlgorithm.HS512, jwtSecret).compact(); 53 | 54 | return token; 55 | } 56 | 57 | public Long getUserIdFromJWT(String token) { 58 | Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody(); 59 | 60 | return Long.parseLong(claims.getSubject()); 61 | } 62 | 63 | public boolean validateToken(String authToken) { 64 | try { 65 | Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); 66 | return true; 67 | } catch (SignatureException ex) { 68 | logger.error("Invalid JWT signature", ex); 69 | } catch (MalformedJwtException ex) { 70 | logger.error("Invalid JWT token", ex); 71 | } catch (ExpiredJwtException ex) { 72 | logger.error("Expired JWT token" + ex); 73 | } catch (UnsupportedJwtException ex) { 74 | logger.error("Unsupported JWT token" + ex); 75 | } catch (IllegalArgumentException ex) { 76 | logger.error("JWT claims string is empty" + ex); 77 | } 78 | return false; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/security/UserPrincipal.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.security; 2 | import com.example.classbdemo.model.User; 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | 5 | import org.springframework.security.core.GrantedAuthority; 6 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | 9 | import java.util.Collection; 10 | import java.util.List; 11 | import java.util.stream.Collectors; 12 | 13 | public class UserPrincipal implements UserDetails { 14 | private static final long serialVersionUID = 1L; 15 | 16 | private Long id; 17 | 18 | private String name; 19 | 20 | private String username; 21 | 22 | @JsonIgnore 23 | private String email; 24 | 25 | @JsonIgnore 26 | private String password; 27 | 28 | private String mobile; 29 | 30 | @JsonIgnore 31 | private String pin; 32 | 33 | private Collection authorities; 34 | 35 | public UserPrincipal(Long id, String name, String username, String mobile, String email, String password, 36 | Collection authorities) { 37 | this.id = id; 38 | this.name = name; 39 | this.username = username; 40 | this.email = email; 41 | this.password = password; 42 | this.mobile = mobile; 43 | this.authorities = authorities; 44 | } 45 | 46 | public static UserPrincipal create(User user) { 47 | List authorities = user.getRoles().stream() 48 | .map(role -> new SimpleGrantedAuthority(role.getName().name())).collect(Collectors.toList()); 49 | 50 | return new UserPrincipal(user.getId(), user.getFirstName()+ " "+user.getLastName(), user.getUsername(), user.getMobile(), 51 | user.getEmail(), user.getPassword(), authorities); 52 | } 53 | 54 | public Long getId() { 55 | return id; 56 | } 57 | 58 | public String getName() { 59 | return name; 60 | } 61 | 62 | public String getEmail() { 63 | return email; 64 | } 65 | 66 | public String getMobile() { 67 | return mobile; 68 | } 69 | 70 | @Override 71 | public String getUsername() { 72 | return username; 73 | } 74 | 75 | @Override 76 | public String getPassword() { 77 | return password; 78 | } 79 | 80 | public String getPin() { 81 | return pin; 82 | } 83 | 84 | public void setPin(String pin) { 85 | this.pin = pin; 86 | } 87 | 88 | @Override 89 | public Collection getAuthorities() { 90 | return authorities; 91 | } 92 | 93 | @Override 94 | public boolean isAccountNonExpired() { 95 | return true; 96 | } 97 | 98 | @Override 99 | public boolean isAccountNonLocked() { 100 | return true; 101 | } 102 | 103 | @Override 104 | public boolean isCredentialsNonExpired() { 105 | return true; 106 | } 107 | 108 | @Override 109 | public boolean isEnabled() { 110 | return true; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/services/IMarkServices.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.services; 2 | 3 | import com.example.classbdemo.dto.CreateMarkDTO; 4 | import com.example.classbdemo.model.Course; 5 | import com.example.classbdemo.model.Mark; 6 | import com.example.classbdemo.model.Student; 7 | 8 | public interface IMarkServices { 9 | 10 | Mark save(CreateMarkDTO markDto,Student student,Course course); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/servicesImpl/MarkServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.servicesImpl; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | 5 | import com.example.classbdemo.dto.CreateMarkDTO; 6 | import com.example.classbdemo.model.Course; 7 | import com.example.classbdemo.model.Mark; 8 | import com.example.classbdemo.model.Student; 9 | import com.example.classbdemo.repositories.MarkRepository; 10 | import com.example.classbdemo.services.IMarkServices; 11 | 12 | public class MarkServiceImpl implements IMarkServices { 13 | 14 | 15 | @Autowired 16 | private MarkRepository markRepository; 17 | 18 | @Override 19 | public Mark save(CreateMarkDTO markDto, Student student, Course course) { 20 | Mark mark = new Mark(); 21 | 22 | mark.setCourse(course); 23 | mark.setMax(markDto.getMax()); 24 | mark.setScored(markDto.getScored()); 25 | mark.setStudent(student); 26 | 27 | return markRepository.save(mark); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/utils/APIResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.utils; 2 | 3 | public class APIResponse { 4 | 5 | private String message; 6 | 7 | private boolean status; 8 | 9 | 10 | 11 | 12 | public APIResponse(String message, boolean status) { 13 | super(); 14 | this.message = message; 15 | this.status = status; 16 | } 17 | 18 | public APIResponse() { 19 | super(); 20 | } 21 | 22 | public String getMessage() { 23 | return message; 24 | } 25 | 26 | public void setMessage(String message) { 27 | this.message = message; 28 | } 29 | 30 | public boolean isStatus() { 31 | return status; 32 | } 33 | 34 | public void setStatus(boolean status) { 35 | this.status = status; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/example/classbdemo/utils/JwtAuthenticationResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo.utils; 2 | 3 | public class JwtAuthenticationResponse { 4 | 5 | private String accessToken; 6 | 7 | private String tokenType = "Bearer"; 8 | 9 | public JwtAuthenticationResponse(String accessToken) { 10 | this.accessToken = accessToken; 11 | } 12 | 13 | public String getAccessToken() { 14 | return accessToken; 15 | } 16 | 17 | public void setAccessToken(String accessToken) { 18 | this.accessToken = accessToken; 19 | } 20 | 21 | public String getTokenType() { 22 | return tokenType; 23 | } 24 | 25 | public void setTokenType(String tokenType) { 26 | this.tokenType = tokenType; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=Classb app 2 | 3 | ## database setup 4 | spring.datasource.url=jdbc:mysql://localhost:3306/springboot?allowPublicKeyRetrieval=true&autoReconnect=true&useSSL=true 5 | 6 | #dev 7 | spring.datasource.username=root 8 | spring.datasource.password=Peace@123 9 | 10 | jwt.security.key=j3H5Ld5nYmGWyULy6xwpOgfSH++NgKXnJMq20vpfd+8=t 11 | jwt.security.expirationInMs =86400000 12 | 13 | # dev server 14 | #spring.datasource.username=root 15 | #spring.datasource.password= 16 | 17 | spring.jpa.hibernate.ddl-auto=update 18 | #spring.jpa.hibernate.ddl-auto=create-drop 19 | spring.jpa.database=mysql 20 | spring.jpa.show-sql=true 21 | 22 | # Naming strategy 23 | spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy 24 | 25 | # The SQL dialect makes Hibernate generate better SQL for the chosen database 26 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect 27 | 28 | -------------------------------------------------------------------------------- /src/test/java/com/example/classbdemo/ClassbDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.classbdemo; 2 | 3 | import com.example.classbdemo.enumerations.ERoleName; 4 | import com.example.classbdemo.model.Role; 5 | import com.example.classbdemo.repositories.IRoleRepository; 6 | import org.assertj.core.api.Assertions; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | import java.util.List; 12 | 13 | @SpringBootTest 14 | class ClassbDemoApplicationTests { 15 | 16 | @Autowired 17 | private IRoleRepository roleRepository; 18 | 19 | @Test 20 | public void testCreateRoles(){ 21 | roleRepository.deleteAll(); 22 | Role admin = new Role(ERoleName.ROLE_ADMIN); 23 | Role user = new Role(ERoleName.ROLE_USER); 24 | 25 | roleRepository.saveAll(List.of(admin,admin,user)); 26 | List listRoles = roleRepository.findAll(); 27 | 28 | Assertions.assertThat(listRoles.size()).isEqualTo(2); 29 | } 30 | 31 | @Test 32 | void contextLoads() { 33 | } 34 | 35 | } 36 | --------------------------------------------------------------------------------