├── .gitattributes ├── .github └── workflows │ └── deploy.yml ├── .gitignore ├── build.gradle.kts ├── deployment ├── nginx-notes-config └── notes.service ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── kotlin │ └── com │ │ └── plcoding │ │ └── spring_boot_crash_course │ │ ├── GlobalValidationHandler.kt │ │ ├── SpringBootCrashCourseApplication.kt │ │ ├── controllers │ │ ├── AuthController.kt │ │ ├── NoteController.kt │ │ └── StatusController.kt │ │ ├── database │ │ ├── model │ │ │ ├── Note.kt │ │ │ ├── RefreshToken.kt │ │ │ └── User.kt │ │ └── repository │ │ │ ├── NoteRepository.kt │ │ │ ├── RefreshTokenRepository.kt │ │ │ └── UserRepository.kt │ │ └── security │ │ ├── AuthService.kt │ │ ├── HashEncoder.kt │ │ ├── JwtAuthFilter.kt │ │ ├── JwtService.kt │ │ └── SecurityConfig.kt └── resources │ └── application.properties └── test └── kotlin └── com └── plcoding └── spring_boot_crash_course └── SpringBootCrashCourseApplicationTests.kt /.gitattributes: -------------------------------------------------------------------------------- 1 | /gradlew text eol=lf 2 | *.bat text eol=crlf 3 | *.jar binary 4 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Notes Backend 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | deploy: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout code 14 | uses: actions/checkout@v3 15 | 16 | - name: Setup SSH 17 | uses: webfactory/ssh-agent@v0.5.3 18 | with: 19 | ssh-private-key: ${{ secrets.DEPLOY_KEY }} 20 | 21 | - name: Add server to known hosts 22 | run: | 23 | ssh-keyscan -H 91.99.31.20 > ~/.ssh/known_hosts 24 | 25 | - name: Build JAR 26 | run: | 27 | ./gradlew bootJar 28 | 29 | - name: Deploy JAR to Server 30 | run: | 31 | JAR_NAME="spring_boot_crash_course-0.0.1-SNAPSHOT.jar" 32 | LOCAL_JAR_PATH="build/libs/$JAR_NAME" 33 | REMOTE_SERVER="admin@91.99.31.20" 34 | REMOTE_JAR_DIR="/opt/notes" 35 | 36 | rsync -avz -e "ssh" $LOCAL_JAR_PATH $REMOTE_SERVER:$REMOTE_JAR_DIR/$JAR_NAME 37 | 38 | ssh $REMOTE_SERVER << EOF 39 | mv $REMOTE_JAR_DIR/$JAR_NAME $REMOTE_JAR_DIR/notes.jar 40 | sudo systemctl restart notes.service 41 | EOF 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | 39 | ### Kotlin ### 40 | .kotlin 41 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") version "1.9.25" 3 | kotlin("plugin.spring") version "1.9.25" 4 | id("org.springframework.boot") version "3.4.3" 5 | id("io.spring.dependency-management") version "1.1.7" 6 | } 7 | 8 | group = "com.plcoding" 9 | version = "0.0.1-SNAPSHOT" 10 | 11 | java { 12 | toolchain { 13 | languageVersion = JavaLanguageVersion.of(17) 14 | } 15 | } 16 | 17 | repositories { 18 | mavenCentral() 19 | } 20 | 21 | dependencies { 22 | implementation("org.springframework.boot:spring-boot-starter-web") 23 | implementation("org.springframework.boot:spring-boot-starter-data-mongodb") 24 | implementation("org.springframework.boot:spring-boot-starter-data-mongodb-reactive") 25 | implementation("org.springframework.boot:spring-boot-starter-security") 26 | implementation("org.springframework.security:spring-security-crypto") 27 | implementation("org.springframework.boot:spring-boot-starter-validation") 28 | implementation("io.projectreactor.kotlin:reactor-kotlin-extensions") 29 | implementation("org.jetbrains.kotlin:kotlin-reflect") 30 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") 31 | testImplementation("org.springframework.boot:spring-boot-starter-test") 32 | testImplementation("io.projectreactor:reactor-test") 33 | testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") 34 | testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test") 35 | testImplementation("org.springframework.security:spring-security-test") 36 | testRuntimeOnly("org.junit.platform:junit-platform-launcher") 37 | 38 | compileOnly("jakarta.servlet:jakarta.servlet-api:6.1.0") 39 | implementation("io.jsonwebtoken:jjwt-api:0.12.6") 40 | runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.6") 41 | runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.12.6") 42 | } 43 | 44 | kotlin { 45 | compilerOptions { 46 | freeCompilerArgs.addAll("-Xjsr305=strict") 47 | } 48 | } 49 | 50 | tasks.withType { 51 | useJUnitPlatform() 52 | } 53 | -------------------------------------------------------------------------------- /deployment/nginx-notes-config: -------------------------------------------------------------------------------- 1 | server { 2 | server_name notes.pl-coding.com; # replace with your domain 3 | 4 | location / { 5 | proxy_pass http://127.0.0.1:8085; # replace with your port 6 | proxy_http_version 1.1; 7 | proxy_set_header Host $host; 8 | proxy_set_header X-Real-IP $remote_addr; 9 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 10 | proxy_set_header X-Forwarded-Proto $scheme; 11 | } 12 | } -------------------------------------------------------------------------------- /deployment/notes.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Spring Boot Notes Application 3 | After=network.target 4 | 5 | [Service] 6 | User=admin 7 | Group=admin 8 | EnvironmentFile=/etc/default/notes-env 9 | ExecStart=/usr/bin/java -jar /opt/notes/notes.jar 10 | Restart=always 11 | RestartSec=5 12 | 13 | [Install] 14 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/philipplackner/SpringBootCrashCourse/932c91921261a3a5917a15207e0591ccaa0f4afd/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | org.gradle.wrapper.GradleWrapperMain \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "spring_boot_crash_course" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/GlobalValidationHandler.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course 2 | 3 | import org.springframework.http.ResponseEntity 4 | import org.springframework.web.bind.MethodArgumentNotValidException 5 | import org.springframework.web.bind.annotation.ExceptionHandler 6 | import org.springframework.web.bind.annotation.RestControllerAdvice 7 | 8 | @RestControllerAdvice 9 | class GlobalValidationHandler { 10 | 11 | @ExceptionHandler(MethodArgumentNotValidException::class) 12 | fun handleValidationError(e: MethodArgumentNotValidException): ResponseEntity> { 13 | val errors = e.bindingResult.allErrors.map { 14 | it.defaultMessage ?: "Invalid value" 15 | } 16 | return ResponseEntity 17 | .status(400) 18 | .body(mapOf("errors" to errors)) 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/SpringBootCrashCourseApplication.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication 4 | import org.springframework.boot.runApplication 5 | 6 | @SpringBootApplication 7 | class SpringBootCrashCourseApplication 8 | 9 | fun main(args: Array) { 10 | runApplication(*args) 11 | } 12 | -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/controllers/AuthController.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.controllers 2 | 3 | import com.plcoding.spring_boot_crash_course.security.AuthService 4 | import jakarta.validation.Valid 5 | import jakarta.validation.constraints.Email 6 | import jakarta.validation.constraints.Pattern 7 | import org.springframework.web.bind.annotation.PostMapping 8 | import org.springframework.web.bind.annotation.RequestBody 9 | import org.springframework.web.bind.annotation.RequestMapping 10 | import org.springframework.web.bind.annotation.RestController 11 | 12 | @RestController 13 | @RequestMapping("/auth") 14 | class AuthController( 15 | private val authService: AuthService 16 | ) { 17 | data class AuthRequest( 18 | @field:Email(message = "Invalid email format.") 19 | val email: String, 20 | @field:Pattern( 21 | regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{9,}\$", 22 | message = "Password must be at least 9 characters long and contain at least one digit, uppercase and lowercase character." 23 | ) 24 | val password: String 25 | ) 26 | 27 | data class RefreshRequest( 28 | val refreshToken: String 29 | ) 30 | 31 | @PostMapping("/register") 32 | fun register( 33 | @Valid @RequestBody body: AuthRequest 34 | ) { 35 | authService.register(body.email, body.password) 36 | } 37 | 38 | @PostMapping("/login") 39 | fun login( 40 | @RequestBody body: AuthRequest 41 | ): AuthService.TokenPair { 42 | return authService.login(body.email, body.password) 43 | } 44 | 45 | @PostMapping("/refresh") 46 | fun refresh( 47 | @RequestBody body: RefreshRequest 48 | ): AuthService.TokenPair { 49 | return authService.refresh(body.refreshToken) 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/controllers/NoteController.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.controllers 2 | 3 | import com.plcoding.spring_boot_crash_course.controllers.NoteController.NoteResponse 4 | import com.plcoding.spring_boot_crash_course.database.model.Note 5 | import com.plcoding.spring_boot_crash_course.database.repository.NoteRepository 6 | import jakarta.validation.Valid 7 | import jakarta.validation.constraints.NotBlank 8 | import org.bson.types.ObjectId 9 | import org.springframework.security.core.context.SecurityContextHolder 10 | import org.springframework.web.bind.annotation.* 11 | import java.time.Instant 12 | 13 | // POST http://localhost:8085/notes 14 | // GET http://localhost:8085/notes?ownerId=123 15 | // DELETE http://localhost:8085/notes/123 16 | 17 | @RestController 18 | @RequestMapping("/notes") 19 | class NoteController( 20 | private val repository: NoteRepository, 21 | private val noteRepository: NoteRepository 22 | ) { 23 | 24 | data class NoteRequest( 25 | val id: String?, 26 | @field:NotBlank(message = "Title can't be blank.") 27 | val title: String, 28 | val content: String, 29 | val color: Long, 30 | ) 31 | 32 | data class NoteResponse( 33 | val id: String, 34 | val title: String, 35 | val content: String, 36 | val color: Long, 37 | val createdAt: Instant 38 | ) 39 | 40 | @PostMapping 41 | fun save( 42 | @Valid @RequestBody body: NoteRequest 43 | ): NoteResponse { 44 | val ownerId = SecurityContextHolder.getContext().authentication.principal as String 45 | val note = repository.save( 46 | Note( 47 | id = body.id?.let { ObjectId(it) } ?: ObjectId.get(), 48 | title = body.title, 49 | content = body.content, 50 | color = body.color, 51 | createdAt = Instant.now(), 52 | ownerId = ObjectId(ownerId) 53 | ) 54 | ) 55 | 56 | return note.toResponse() 57 | } 58 | 59 | @GetMapping 60 | fun findByOwnerId(): List { 61 | val ownerId = SecurityContextHolder.getContext().authentication.principal as String 62 | return repository.findByOwnerId(ObjectId(ownerId)).map { 63 | it.toResponse() 64 | } 65 | } 66 | 67 | @DeleteMapping(path = ["/{id}"]) 68 | fun deleteById(@PathVariable id: String) { 69 | val note = noteRepository.findById(ObjectId(id)).orElseThrow { 70 | IllegalArgumentException("Note not found") 71 | } 72 | val ownerId = SecurityContextHolder.getContext().authentication.principal as String 73 | if(note.ownerId.toHexString() == ownerId) { 74 | repository.deleteById(ObjectId(id)) 75 | } 76 | } 77 | } 78 | 79 | private fun Note.toResponse(): NoteController.NoteResponse { 80 | return NoteResponse( 81 | id = id.toHexString(), 82 | title = title, 83 | content = content, 84 | color = color, 85 | createdAt = createdAt 86 | ) 87 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/controllers/StatusController.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.controllers 2 | 3 | import org.springframework.web.bind.annotation.GetMapping 4 | import org.springframework.web.bind.annotation.RequestMapping 5 | import org.springframework.web.bind.annotation.RestController 6 | 7 | @RestController 8 | @RequestMapping("/") 9 | class StatusController { 10 | 11 | @GetMapping 12 | fun getStatus(): String { 13 | return "Everything cool!" 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/database/model/Note.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.database.model 2 | 3 | import org.bson.types.ObjectId 4 | import org.springframework.data.annotation.Id 5 | import org.springframework.data.mongodb.core.mapping.Document 6 | import java.time.Instant 7 | 8 | @Document("notes") 9 | data class Note( 10 | val title: String, 11 | val content: String, 12 | val color: Long, 13 | val createdAt: Instant, 14 | val ownerId: ObjectId, 15 | @Id val id: ObjectId = ObjectId.get() 16 | ) 17 | -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/database/model/RefreshToken.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.database.model 2 | 3 | import org.bson.types.ObjectId 4 | import org.springframework.data.mongodb.core.index.Indexed 5 | import org.springframework.data.mongodb.core.mapping.Document 6 | import java.time.Instant 7 | 8 | @Document("refresh_tokens") 9 | data class RefreshToken( 10 | val userId: ObjectId, 11 | @Indexed(expireAfter = "0s") 12 | val expiresAt: Instant, 13 | val hashedToken: String, 14 | val createdAt: Instant = Instant.now() 15 | ) 16 | -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/database/model/User.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.database.model 2 | 3 | import org.bson.types.ObjectId 4 | import org.springframework.data.annotation.Id 5 | import org.springframework.data.mongodb.core.mapping.Document 6 | 7 | @Document("users") 8 | data class User( 9 | val email: String, 10 | val hashedPassword: String, 11 | @Id val id: ObjectId = ObjectId() 12 | ) 13 | -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/database/repository/NoteRepository.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.database.repository 2 | 3 | import com.plcoding.spring_boot_crash_course.database.model.Note 4 | import org.bson.types.ObjectId 5 | import org.springframework.data.mongodb.repository.MongoRepository 6 | 7 | interface NoteRepository: MongoRepository { 8 | fun findByOwnerId(ownerId: ObjectId): List 9 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/database/repository/RefreshTokenRepository.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.database.repository 2 | 3 | import com.plcoding.spring_boot_crash_course.database.model.RefreshToken 4 | import org.bson.types.ObjectId 5 | import org.springframework.data.mongodb.repository.MongoRepository 6 | 7 | interface RefreshTokenRepository: MongoRepository { 8 | fun findByUserIdAndHashedToken(userId: ObjectId, hashedToken: String): RefreshToken? 9 | fun deleteByUserIdAndHashedToken(userId: ObjectId, hashedToken: String) 10 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/database/repository/UserRepository.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.database.repository 2 | 3 | import com.plcoding.spring_boot_crash_course.database.model.User 4 | import org.bson.types.ObjectId 5 | import org.springframework.data.mongodb.repository.MongoRepository 6 | 7 | interface UserRepository: MongoRepository { 8 | fun findByEmail(email: String): User? 9 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/security/AuthService.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.security 2 | 3 | import com.plcoding.spring_boot_crash_course.database.model.RefreshToken 4 | import com.plcoding.spring_boot_crash_course.database.model.User 5 | import com.plcoding.spring_boot_crash_course.database.repository.RefreshTokenRepository 6 | import com.plcoding.spring_boot_crash_course.database.repository.UserRepository 7 | import org.bson.types.ObjectId 8 | import org.springframework.http.HttpStatus 9 | import org.springframework.http.HttpStatusCode 10 | import org.springframework.security.authentication.BadCredentialsException 11 | import org.springframework.stereotype.Service 12 | import org.springframework.transaction.annotation.Transactional 13 | import org.springframework.web.server.ResponseStatusException 14 | import java.security.MessageDigest 15 | import java.time.Instant 16 | import java.util.* 17 | 18 | @Service 19 | class AuthService( 20 | private val jwtService: JwtService, 21 | private val userRepository: UserRepository, 22 | private val hashEncoder: HashEncoder, 23 | private val refreshTokenRepository: RefreshTokenRepository 24 | ) { 25 | data class TokenPair( 26 | val accessToken: String, 27 | val refreshToken: String 28 | ) 29 | 30 | fun register(email: String, password: String): User { 31 | val user = userRepository.findByEmail(email.trim()) 32 | if(user != null) { 33 | throw ResponseStatusException(HttpStatus.CONFLICT, "A user with that email already exists.") 34 | } 35 | return userRepository.save( 36 | User( 37 | email = email, 38 | hashedPassword = hashEncoder.encode(password) 39 | ) 40 | ) 41 | } 42 | 43 | fun login(email: String, password: String): TokenPair { 44 | val user = userRepository.findByEmail(email) 45 | ?: throw BadCredentialsException("Invalid credentials.") 46 | 47 | if(!hashEncoder.matches(password, user.hashedPassword)) { 48 | throw BadCredentialsException("Invalid credentials.") 49 | } 50 | 51 | val newAccessToken = jwtService.generateAccessToken(user.id.toHexString()) 52 | val newRefreshToken = jwtService.generateRefreshToken(user.id.toHexString()) 53 | 54 | storeRefreshToken(user.id, newRefreshToken) 55 | 56 | return TokenPair( 57 | accessToken = newAccessToken, 58 | refreshToken = newRefreshToken 59 | ) 60 | } 61 | 62 | @Transactional 63 | fun refresh(refreshToken: String): TokenPair { 64 | if(!jwtService.validateRefreshToken(refreshToken)) { 65 | throw ResponseStatusException(HttpStatusCode.valueOf(401), "Invalid refresh token.") 66 | } 67 | 68 | val userId = jwtService.getUserIdFromToken(refreshToken) 69 | val user = userRepository.findById(ObjectId(userId)).orElseThrow { 70 | ResponseStatusException(HttpStatusCode.valueOf(401), "Invalid refresh token.") 71 | } 72 | 73 | val hashed = hashToken(refreshToken) 74 | refreshTokenRepository.findByUserIdAndHashedToken(user.id, hashed) 75 | ?: throw ResponseStatusException( 76 | HttpStatusCode.valueOf(401), 77 | "Refresh token not recognized (maybe used or expired?)" 78 | ) 79 | 80 | refreshTokenRepository.deleteByUserIdAndHashedToken(user.id, hashed) 81 | 82 | val newAccessToken = jwtService.generateAccessToken(userId) 83 | val newRefreshToken = jwtService.generateRefreshToken(userId) 84 | 85 | storeRefreshToken(user.id, newRefreshToken) 86 | 87 | return TokenPair( 88 | accessToken = newAccessToken, 89 | refreshToken = newRefreshToken 90 | ) 91 | } 92 | 93 | private fun storeRefreshToken(userId: ObjectId, rawRefreshToken: String) { 94 | val hashed = hashToken(rawRefreshToken) 95 | val expiryMs = jwtService.refreshTokenValidityMs 96 | val expiresAt = Instant.now().plusMillis(expiryMs) 97 | 98 | refreshTokenRepository.save( 99 | RefreshToken( 100 | userId = userId, 101 | expiresAt = expiresAt, 102 | hashedToken = hashed 103 | ) 104 | ) 105 | } 106 | 107 | private fun hashToken(token: String): String { 108 | val digest = MessageDigest.getInstance("SHA-256") 109 | val hashBytes = digest.digest(token.encodeToByteArray()) 110 | return Base64.getEncoder().encodeToString(hashBytes) 111 | } 112 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/security/HashEncoder.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.security 2 | 3 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder 4 | import org.springframework.stereotype.Component 5 | 6 | @Component 7 | class HashEncoder { 8 | 9 | private val bcrypt = BCryptPasswordEncoder() 10 | 11 | fun encode(raw: String): String = bcrypt.encode(raw) 12 | 13 | fun matches(raw: String, hashed: String): Boolean = bcrypt.matches(raw, hashed) 14 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/security/JwtAuthFilter.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.security 2 | 3 | import jakarta.servlet.FilterChain 4 | import jakarta.servlet.http.HttpServletRequest 5 | import jakarta.servlet.http.HttpServletResponse 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 7 | import org.springframework.security.core.context.SecurityContextHolder 8 | import org.springframework.stereotype.Component 9 | import org.springframework.web.filter.OncePerRequestFilter 10 | 11 | @Component 12 | class JwtAuthFilter( 13 | private val jwtService: JwtService 14 | ): OncePerRequestFilter() { 15 | 16 | override fun doFilterInternal( 17 | request: HttpServletRequest, 18 | response: HttpServletResponse, 19 | filterChain: FilterChain 20 | ) { 21 | val authHeader = request.getHeader("Authorization") 22 | if(authHeader != null && authHeader.startsWith("Bearer ")) { 23 | if(jwtService.validateAccessToken(authHeader)) { 24 | val userId = jwtService.getUserIdFromToken(authHeader) 25 | val auth = UsernamePasswordAuthenticationToken(userId, null, emptyList()) 26 | SecurityContextHolder.getContext().authentication = auth 27 | } 28 | } 29 | 30 | filterChain.doFilter(request, response) 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/security/JwtService.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.security 2 | 3 | import io.jsonwebtoken.Claims 4 | import io.jsonwebtoken.Jwts 5 | import io.jsonwebtoken.security.Keys 6 | import org.springframework.beans.factory.annotation.Value 7 | import org.springframework.http.HttpStatusCode 8 | import org.springframework.stereotype.Service 9 | import org.springframework.web.server.ResponseStatusException 10 | import java.util.Base64 11 | import java.util.Date 12 | 13 | @Service 14 | class JwtService( 15 | @Value("\${jwt.secret}") private val jwtSecret: String 16 | ) { 17 | 18 | private val secretKey = Keys.hmacShaKeyFor(Base64.getDecoder().decode(jwtSecret)) 19 | private val accessTokenValidityMs = 15L * 60L * 1000L 20 | val refreshTokenValidityMs = 30L * 24 * 60 * 60 * 1000L 21 | 22 | private fun generateToken( 23 | userId: String, 24 | type: String, 25 | expiry: Long 26 | ): String { 27 | val now = Date() 28 | val expiryDate = Date(now.time + expiry) 29 | return Jwts.builder() 30 | .subject(userId) 31 | .claim("type", type) 32 | .issuedAt(now) 33 | .expiration(expiryDate) 34 | .signWith(secretKey, Jwts.SIG.HS256) 35 | .compact() 36 | } 37 | 38 | fun generateAccessToken(userId: String): String { 39 | return generateToken(userId, "access", accessTokenValidityMs) 40 | } 41 | 42 | fun generateRefreshToken(userId: String): String { 43 | return generateToken(userId, "refresh", refreshTokenValidityMs) 44 | } 45 | 46 | fun validateAccessToken(token: String): Boolean { 47 | val claims = parseAllClaims(token) ?: return false 48 | val tokenType = claims["type"] as? String ?: return false 49 | return tokenType == "access" 50 | } 51 | 52 | fun validateRefreshToken(token: String): Boolean { 53 | val claims = parseAllClaims(token) ?: return false 54 | val tokenType = claims["type"] as? String ?: return false 55 | return tokenType == "refresh" 56 | } 57 | 58 | fun getUserIdFromToken(token: String): String { 59 | val claims = parseAllClaims(token) ?: throw ResponseStatusException( 60 | HttpStatusCode.valueOf(401), 61 | "Invalid token." 62 | ) 63 | return claims.subject 64 | } 65 | 66 | private fun parseAllClaims(token: String): Claims? { 67 | val rawToken = if(token.startsWith("Bearer ")) { 68 | token.removePrefix("Bearer ") 69 | } else token 70 | return try { 71 | Jwts.parser() 72 | .verifyWith(secretKey) 73 | .build() 74 | .parseSignedClaims(rawToken) 75 | .payload 76 | } catch(e: Exception) { 77 | null 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/plcoding/spring_boot_crash_course/security/SecurityConfig.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course.security 2 | 3 | import jakarta.servlet.DispatcherType 4 | import org.springframework.context.annotation.Bean 5 | import org.springframework.context.annotation.Configuration 6 | import org.springframework.http.HttpStatus 7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity 8 | import org.springframework.security.config.http.SessionCreationPolicy 9 | import org.springframework.security.web.SecurityFilterChain 10 | import org.springframework.security.web.authentication.HttpStatusEntryPoint 11 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter 12 | 13 | @Configuration 14 | class SecurityConfig( 15 | private val jwtAuthFilter: JwtAuthFilter 16 | ) { 17 | 18 | @Bean 19 | fun filterChain(httpSecurity: HttpSecurity): SecurityFilterChain { 20 | return httpSecurity 21 | .csrf { csrf -> csrf.disable() } 22 | .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) } 23 | .authorizeHttpRequests { auth -> 24 | auth 25 | .requestMatchers("/") 26 | .permitAll() 27 | .requestMatchers("/auth/**") 28 | .permitAll() 29 | .dispatcherTypeMatchers( 30 | DispatcherType.ERROR, 31 | DispatcherType.FORWARD 32 | ) 33 | .permitAll() 34 | .anyRequest() 35 | .authenticated() 36 | } 37 | .exceptionHandling { configurer -> 38 | configurer 39 | .authenticationEntryPoint(HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)) 40 | } 41 | .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter::class.java) 42 | .build() 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=spring_boot_crash_course 2 | server.port=8085 3 | spring.data.mongodb.uri=${MONGODB_CONNECTION_STRING} 4 | spring.data.mongodb.auto-index-creation=true 5 | jwt.secret=${JWT_SECRET_BASE64} -------------------------------------------------------------------------------- /src/test/kotlin/com/plcoding/spring_boot_crash_course/SpringBootCrashCourseApplicationTests.kt: -------------------------------------------------------------------------------- 1 | package com.plcoding.spring_boot_crash_course 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.springframework.boot.test.context.SpringBootTest 5 | 6 | @SpringBootTest 7 | class SpringBootCrashCourseApplicationTests { 8 | 9 | @Test 10 | fun contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------