├── .gitignore ├── .jpb └── persistence-units.xml ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── docker-compose.yml ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── springboot │ │ └── blog │ │ ├── SpringbootBlogRestApiApplication.java │ │ ├── config │ │ ├── SecurityConfiguration.java │ │ └── SwaggerConfig.java │ │ ├── controller │ │ ├── AuthController.java │ │ ├── CommentController.java │ │ └── PostController.java │ │ ├── dto │ │ ├── auth │ │ │ ├── LoginDto.java │ │ │ └── LoginResponseDto.java │ │ ├── comment │ │ │ ├── CommentDto.java │ │ │ ├── CommentMapper.java │ │ │ └── UpdateCommentDto.java │ │ ├── post │ │ │ ├── CreatePostDto.java │ │ │ ├── PostDto.java │ │ │ ├── PostMapper.java │ │ │ ├── PostResponseDto.java │ │ │ └── UpdatePostDto.java │ │ ├── role │ │ │ └── RoleDto.java │ │ └── user │ │ │ ├── RegisterDto.java │ │ │ ├── UserDto.java │ │ │ └── UserMapper.java │ │ ├── entity │ │ ├── Comment.java │ │ ├── Post.java │ │ ├── Role.java │ │ └── User.java │ │ ├── exception │ │ ├── BlogApiException.java │ │ ├── GlobalExceptionHandler.java │ │ ├── ResourceNotFoundException.java │ │ └── ValidationErrorsHandler.java │ │ ├── repository │ │ ├── CommentRepository.java │ │ ├── PostRepository.java │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ ├── security │ │ ├── jwt │ │ │ ├── JwtAuthEntryPoint.java │ │ │ ├── JwtAuthFilter.java │ │ │ └── JwtUtils.java │ │ └── service │ │ │ ├── UserDetailsImpl.java │ │ │ └── UserDetailsServiceImpl.java │ │ ├── service │ │ ├── auth │ │ │ ├── AuthService.java │ │ │ └── AuthServiceImpl.java │ │ ├── comment │ │ │ ├── CommentService.java │ │ │ └── CommentServiceImpl.java │ │ ├── post │ │ │ ├── PostService.java │ │ │ └── PostServiceImpl.java │ │ └── user │ │ │ ├── UserService.java │ │ │ └── UserServiceImpl.java │ │ └── utils │ │ ├── AppConstants.java │ │ ├── ErrorDetails.java │ │ └── ValidationErrors.java └── resources │ ├── application-dev.properties │ ├── application-prod.properties │ └── application.properties └── test └── java └── com └── springboot └── blog └── SpringbootBlogRestApiApplicationTests.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 | -------------------------------------------------------------------------------- /.jpb/persistence-units.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dvun/springboot-blog_rest_api/c381ce3148cc2fb5a091b9010cb75443f5ce907a/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.5' 2 | services: 3 | 4 | database: 5 | image: postgres:14.2-alpine 6 | restart: unless-stopped 7 | ports: 8 | - '5432:5432' 9 | volumes: 10 | - data:/var/lib/postgresql/data 11 | environment: 12 | - POSTGRES_USER=postgres 13 | - POSTGRES_PASSWORD=postgres 14 | 15 | volumes: 16 | data: -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.2 9 | 10 | 11 | com.springboot.blog 12 | springboot-blog_rest_api 13 | 0.0.1-SNAPSHOT 14 | springboot-blog_rest_api 15 | springboot-blog_rest_api 16 | 17 | 17 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-data-jpa 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-validation 34 | 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-devtools 39 | runtime 40 | true 41 | 42 | 43 | 44 | org.postgresql 45 | postgresql 46 | runtime 47 | 48 | 49 | 50 | org.projectlombok 51 | lombok 52 | true 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-starter-test 58 | test 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-security 64 | 65 | 66 | 67 | org.mapstruct 68 | mapstruct 69 | 1.5.2.Final 70 | 71 | 72 | 73 | io.jsonwebtoken 74 | jjwt-api 75 | 0.11.5 76 | 77 | 78 | 79 | io.jsonwebtoken 80 | jjwt-impl 81 | 0.11.5 82 | runtime 83 | 84 | 85 | 86 | io.jsonwebtoken 87 | jjwt-jackson 88 | 0.11.5 89 | runtime 90 | 91 | 92 | 93 | org.springdoc 94 | springdoc-openapi-ui 95 | 1.6.10 96 | 97 | 98 | 99 | org.jetbrains 100 | annotations 101 | 23.0.0 102 | compile 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | org.apache.maven.plugins 111 | maven-compiler-plugin 112 | 3.10.1 113 | 114 | 11 115 | 11 116 | 117 | 118 | org.projectlombok 119 | lombok 120 | 1.18.24 121 | 122 | 123 | org.mapstruct 124 | mapstruct-processor 125 | 1.5.2.Final 126 | 127 | 128 | org.projectlombok 129 | lombok-mapstruct-binding 130 | 0.2.0 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/SpringbootBlogRestApiApplication.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog; 2 | 3 | import com.springboot.blog.entity.Role; 4 | import com.springboot.blog.service.auth.AuthService; 5 | import org.springframework.boot.CommandLineRunner; 6 | import org.springframework.boot.SpringApplication; 7 | import org.springframework.boot.autoconfigure.SpringBootApplication; 8 | import org.springframework.context.annotation.Bean; 9 | 10 | @SpringBootApplication 11 | public class SpringbootBlogRestApiApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(SpringbootBlogRestApiApplication.class, args); 15 | } 16 | 17 | @Bean 18 | CommandLineRunner run(AuthService authService) { 19 | return args -> { 20 | if (authService.findByRole("ROLE_ADMIN").isEmpty()) { 21 | authService.createRole(new Role(null, "ROLE_ADMIN")); 22 | } 23 | if (authService.findByRole("ROLE_USER").isEmpty()) { 24 | authService.createRole(new Role(null, "ROLE_USER")); 25 | } 26 | }; 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.config; 2 | 3 | 4 | import com.springboot.blog.security.jwt.JwtAuthEntryPoint; 5 | import com.springboot.blog.security.jwt.JwtAuthFilter; 6 | import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn; 7 | import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; 8 | import io.swagger.v3.oas.annotations.security.SecurityScheme; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.http.HttpMethod; 12 | import org.springframework.security.authentication.AuthenticationManager; 13 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 14 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 15 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 16 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 17 | import org.springframework.security.config.http.SessionCreationPolicy; 18 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 19 | import org.springframework.security.crypto.password.PasswordEncoder; 20 | import org.springframework.security.web.SecurityFilterChain; 21 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 22 | 23 | @Configuration 24 | @EnableWebSecurity 25 | @EnableGlobalMethodSecurity(prePostEnabled = true) 26 | @SecurityScheme(name = "Authorization", scheme = "bearer", type = SecuritySchemeType.HTTP, in = SecuritySchemeIn.HEADER) 27 | public class SecurityConfiguration { 28 | 29 | private final JwtAuthEntryPoint jwtAuthEntryPoint; 30 | 31 | public SecurityConfiguration(JwtAuthEntryPoint jwtAuthEntryPoint) { 32 | this.jwtAuthEntryPoint = jwtAuthEntryPoint; 33 | } 34 | 35 | @Bean 36 | protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 37 | http 38 | // .csrf().csrfTokenRepository(new CookieCsrfTokenRepository()) 39 | .csrf().disable() 40 | .exceptionHandling().authenticationEntryPoint(jwtAuthEntryPoint) 41 | .and() 42 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 43 | .and() 44 | .authorizeRequests(auth -> auth 45 | .antMatchers(HttpMethod.GET, "/api/**").permitAll() 46 | .antMatchers("/api/auth/login", "/api/auth/register").permitAll() 47 | .antMatchers("/v3/api-docs/**").permitAll() 48 | .antMatchers("/swagger-ui/**").permitAll() 49 | .anyRequest().authenticated()); 50 | return http.addFilterBefore(authTokenFilter(), UsernamePasswordAuthenticationFilter.class).build(); 51 | } 52 | 53 | @Bean 54 | PasswordEncoder passwordEncoder() { 55 | return new BCryptPasswordEncoder(); 56 | } 57 | 58 | @Bean 59 | JwtAuthFilter authTokenFilter() { 60 | return new JwtAuthFilter(); 61 | } 62 | 63 | @Bean 64 | public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { 65 | return configuration.getAuthenticationManager(); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.config; 2 | 3 | 4 | import io.swagger.v3.oas.annotations.Operation; 5 | import io.swagger.v3.oas.annotations.security.SecurityRequirement; 6 | import io.swagger.v3.oas.models.OpenAPI; 7 | import io.swagger.v3.oas.models.info.Contact; 8 | import io.swagger.v3.oas.models.info.Info; 9 | import io.swagger.v3.oas.models.info.License; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | 13 | @Configuration 14 | public class SwaggerConfig { 15 | 16 | @Operation(security = { @SecurityRequirement(name = "Authorization") }) 17 | 18 | 19 | @Bean 20 | public OpenAPI springShopOpenAPI() { 21 | return new OpenAPI() 22 | .info(new Info().title("Spring Boot Blog REST API") 23 | .description("Spring Boot Blog REST API Documentation") 24 | .version("1.0") 25 | .contact(new Contact().name("Roman Seveljov").email("roman084@gmx.com")) 26 | .description("Blog API Wiki Documentation") 27 | .license(new License().name("License of API").url("API License URL"))); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.controller; 2 | 3 | 4 | import com.springboot.blog.dto.auth.LoginDto; 5 | import com.springboot.blog.dto.auth.LoginResponseDto; 6 | import com.springboot.blog.dto.user.RegisterDto; 7 | import com.springboot.blog.service.auth.AuthService; 8 | import io.swagger.v3.oas.annotations.Operation; 9 | import io.swagger.v3.oas.annotations.media.Content; 10 | import io.swagger.v3.oas.annotations.media.Schema; 11 | import io.swagger.v3.oas.annotations.responses.ApiResponse; 12 | import io.swagger.v3.oas.annotations.responses.ApiResponses; 13 | import io.swagger.v3.oas.annotations.tags.Tag; 14 | import lombok.AllArgsConstructor; 15 | import org.springframework.http.ResponseEntity; 16 | import org.springframework.web.bind.annotation.PostMapping; 17 | import org.springframework.web.bind.annotation.RequestBody; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RestController; 20 | 21 | 22 | @RestController 23 | @RequestMapping("/api/auth") 24 | @AllArgsConstructor 25 | @Tag(name = "Auth") 26 | public class AuthController { 27 | 28 | private final AuthService authService; 29 | 30 | @Operation(summary = "Login User that give a user info and access token") 31 | @ApiResponses(value = { 32 | @ApiResponse(responseCode = "200", description = "User details", 33 | content = {@Content(mediaType = "application/json", 34 | schema = @Schema(implementation = LoginResponseDto.class))}), 35 | @ApiResponse(responseCode = "400", 36 | description = "Bad Credentials!", 37 | content = @Content) 38 | }) 39 | 40 | @PostMapping("/login") 41 | public ResponseEntity login(@RequestBody LoginDto dto) { 42 | return authService.login(dto); 43 | } 44 | 45 | @PostMapping("/register") 46 | public ResponseEntity register(@RequestBody RegisterDto dto) { 47 | return authService.register(dto); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/controller/CommentController.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.controller; 2 | 3 | 4 | import com.springboot.blog.dto.comment.CommentDto; 5 | import com.springboot.blog.dto.comment.UpdateCommentDto; 6 | import com.springboot.blog.service.comment.CommentService; 7 | import io.swagger.v3.oas.annotations.security.SecurityRequirement; 8 | import io.swagger.v3.oas.annotations.tags.Tag; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import javax.validation.Valid; 14 | import java.util.List; 15 | 16 | @RestController 17 | @RequestMapping("/api") 18 | @Tag(name = "Comment") 19 | public class CommentController { 20 | private final CommentService commentService; 21 | 22 | public CommentController(CommentService commentService) { 23 | this.commentService = commentService; 24 | } 25 | 26 | 27 | @PostMapping("/posts/{postId}/comments") 28 | @SecurityRequirement(name = "Authorization") 29 | public ResponseEntity create(@PathVariable(value = "postId") Long postId, @Valid @RequestBody CommentDto dto) { 30 | CommentDto comment = commentService.create(postId, dto); 31 | return new ResponseEntity<>(comment, HttpStatus.CREATED); 32 | } 33 | 34 | @GetMapping("/posts/{postId}/comments") 35 | public List getAllByPost(@PathVariable(value = "postId") Long postId) { 36 | return commentService.getAllByPost(postId); 37 | } 38 | 39 | @GetMapping("/posts/{postId}/comments/{commentId}") 40 | public ResponseEntity getCommentById( 41 | @PathVariable(value = "postId") Long postId, 42 | @PathVariable(value = "commentId") Long commentId) { 43 | return new ResponseEntity<>(commentService.getCommentById(postId, commentId), HttpStatus.OK); 44 | } 45 | 46 | @PutMapping("/posts/{postId}/comments/{commentId}") 47 | @SecurityRequirement(name = "Authorization") 48 | public ResponseEntity update( 49 | @PathVariable(value = "commentId") Long commentId, 50 | @PathVariable(value = "postId") Long postId, 51 | @Valid @RequestBody UpdateCommentDto dto) { 52 | CommentDto comment = commentService.update(postId, commentId, dto); 53 | return new ResponseEntity<>(comment, HttpStatus.OK); 54 | } 55 | 56 | @DeleteMapping("/posts/{postId}/comments/{commentId}") 57 | @SecurityRequirement(name = "Authorization") 58 | public ResponseEntity delete( 59 | @PathVariable(value = "commentId") Long commentId, 60 | @PathVariable(value = "postId") Long postId) { 61 | commentService.delete(postId, commentId); 62 | return new ResponseEntity<>("Comment deleted successfully!", HttpStatus.OK); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/controller/PostController.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.controller; 2 | 3 | import com.springboot.blog.dto.post.CreatePostDto; 4 | import com.springboot.blog.dto.post.PostDto; 5 | import com.springboot.blog.dto.post.UpdatePostDto; 6 | import com.springboot.blog.service.post.PostService; 7 | import com.springboot.blog.utils.AppConstants; 8 | import com.springboot.blog.dto.post.PostResponseDto; 9 | import io.swagger.v3.oas.annotations.security.SecurityRequirement; 10 | import io.swagger.v3.oas.annotations.tags.Tag; 11 | import lombok.AllArgsConstructor; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.web.bind.annotation.*; 15 | 16 | import javax.validation.Valid; 17 | 18 | @RestController() 19 | @AllArgsConstructor 20 | @RequestMapping("/api/posts") 21 | @Tag(name = "Post") 22 | public class PostController { 23 | private final PostService postService; 24 | 25 | 26 | @PostMapping 27 | @SecurityRequirement(name = "Authorization") 28 | public ResponseEntity create(@Valid @RequestBody CreatePostDto dto) { 29 | return postService.create(dto); 30 | } 31 | 32 | @GetMapping 33 | public PostResponseDto getAll( 34 | @RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE, required = false) int page, 35 | @RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_SIZE, required = false) int size, 36 | @RequestParam(value = "sortBy", defaultValue = AppConstants.DEFAULT_SORT_BY, required = false) String sortBy, 37 | @RequestParam(value = "sort", defaultValue = AppConstants.DEFAULT_SORT_DIRECTION, required = false) String sort) { 38 | return postService.getAll(page, size, sort, sortBy); 39 | } 40 | 41 | @GetMapping(value = "/{id}") 42 | public PostDto getById(@PathVariable("id") Long id) { 43 | return postService.getById(id); 44 | } 45 | 46 | @PutMapping("/{id}") 47 | @SecurityRequirement(name = "Authorization") 48 | public PostDto update(@PathVariable("id") Long id, @Valid @RequestBody UpdatePostDto dto) { 49 | return postService.update(id, dto); 50 | } 51 | 52 | @DeleteMapping("/{id}") 53 | @SecurityRequirement(name = "Authorization") 54 | public ResponseEntity delete(@PathVariable("id") Long id) { 55 | postService.delete(id); 56 | return new ResponseEntity<>("Post deleted successfully!", HttpStatus.OK); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/auth/LoginDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.auth; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.regex.Pattern; 6 | 7 | @Data 8 | public class LoginDto { 9 | 10 | private String usernameOrEmail; 11 | private String password; 12 | 13 | public void setUsernameOrEmail(String usernameOrEmail) { 14 | String emailRegex = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 15 | if (Pattern.compile(emailRegex).matcher(usernameOrEmail).matches()) 16 | this.usernameOrEmail = usernameOrEmail.toLowerCase(); 17 | else 18 | this.usernameOrEmail = usernameOrEmail; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/auth/LoginResponseDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.auth; 2 | 3 | 4 | import com.springboot.blog.dto.user.UserDto; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | import lombok.Setter; 9 | 10 | @Getter 11 | @Setter 12 | @AllArgsConstructor 13 | @NoArgsConstructor 14 | public class LoginResponseDto { 15 | 16 | private UserDto user; 17 | private String accessToken; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/comment/CommentDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.comment; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.Email; 6 | import javax.validation.constraints.NotEmpty; 7 | import javax.validation.constraints.Pattern; 8 | import javax.validation.constraints.Size; 9 | 10 | @Data 11 | public class CommentDto { 12 | 13 | private Long id; 14 | 15 | @NotEmpty(message = "Name is required!") 16 | private String name; 17 | 18 | @NotEmpty(message = "Email is required!") 19 | @Email(regexp = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}", 20 | flags = Pattern.Flag.CASE_INSENSITIVE, 21 | message = "Email must be a well-formed email address!") 22 | private String email; 23 | 24 | @NotEmpty(message = "Message is required!") 25 | @Size(min = 10, message = "Comment message should have at least 10 characters!") 26 | private String message; 27 | 28 | 29 | public void setEmail(String email) { 30 | this.email = email.toLowerCase().trim(); 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name.trim(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/comment/CommentMapper.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.comment; 2 | 3 | 4 | import com.springboot.blog.entity.Comment; 5 | import org.mapstruct.Mapper; 6 | import org.mapstruct.factory.Mappers; 7 | 8 | @Mapper 9 | public interface CommentMapper { 10 | 11 | CommentMapper INSTANCE = Mappers.getMapper(CommentMapper.class); 12 | 13 | Comment dtoToEntity(CommentDto dto); 14 | CommentDto entityToDto(Comment comment); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/comment/UpdateCommentDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.comment; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.Email; 6 | import javax.validation.constraints.NotEmpty; 7 | import javax.validation.constraints.Pattern; 8 | import javax.validation.constraints.Size; 9 | 10 | @Data 11 | public class UpdateCommentDto { 12 | 13 | @NotEmpty(message = "Name is required!") 14 | private String name; 15 | 16 | @NotEmpty(message = "Email is required!") 17 | @Email(regexp = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}", 18 | flags = Pattern.Flag.CASE_INSENSITIVE, 19 | message = "Email must be a well-formed email address!") 20 | private String email; 21 | 22 | @NotEmpty(message = "Message is required!") 23 | @Size(min = 10, message = "Comment message should have at least 10 characters!") 24 | private String message; 25 | 26 | 27 | public void setEmail(String email) { 28 | this.email = email.toLowerCase().trim(); 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name.trim(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/post/CreatePostDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.post; 2 | 3 | import lombok.Data; 4 | 5 | import javax.validation.constraints.NotEmpty; 6 | import javax.validation.constraints.Size; 7 | 8 | @Data 9 | public class CreatePostDto { 10 | 11 | @NotEmpty 12 | @Size(min = 2, message = "Post title should have at least 2 characters!") 13 | private String title; 14 | 15 | @NotEmpty 16 | @Size(min = 10, message = "Post description should have at least 10 characters!") 17 | private String description; 18 | 19 | @NotEmpty 20 | private String content; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/post/PostDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.post; 2 | 3 | import com.springboot.blog.dto.comment.CommentDto; 4 | import lombok.Data; 5 | 6 | import java.time.LocalDateTime; 7 | import java.util.Set; 8 | 9 | @Data 10 | public class PostDto extends CreatePostDto { 11 | 12 | private Long id; 13 | private LocalDateTime createdAt; 14 | private LocalDateTime updatedAt; 15 | private Set comments; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/post/PostMapper.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.post; 2 | 3 | import com.springboot.blog.entity.Post; 4 | import org.mapstruct.Mapper; 5 | import org.mapstruct.Mapping; 6 | import org.mapstruct.factory.Mappers; 7 | 8 | @Mapper 9 | public interface PostMapper { 10 | 11 | PostMapper INSTANCE = Mappers.getMapper(PostMapper.class); 12 | 13 | @Mapping(target = "post.comments", ignore = true) 14 | PostDto entityToDto(Post post); 15 | Post dtoToEntity(PostDto dto); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/post/PostResponseDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.post; 2 | 3 | import com.springboot.blog.dto.post.PostDto; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | 7 | import java.util.List; 8 | 9 | @Data 10 | @AllArgsConstructor 11 | public class PostResponseDto { 12 | 13 | private List content; 14 | private int page; 15 | private int size; 16 | private Long totalElements; 17 | private int totalPages; 18 | private boolean last; 19 | 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/post/UpdatePostDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.post; 2 | 3 | 4 | import lombok.Data; 5 | 6 | @Data 7 | public class UpdatePostDto extends CreatePostDto { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/role/RoleDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.role; 2 | 3 | import lombok.Data; 4 | 5 | 6 | @Data 7 | public class RoleDto { 8 | 9 | private String role; 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/user/RegisterDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.user; 2 | 3 | 4 | import lombok.Data; 5 | 6 | import javax.validation.constraints.Email; 7 | import javax.validation.constraints.NotEmpty; 8 | import javax.validation.constraints.Pattern; 9 | 10 | @Data 11 | public class RegisterDto { 12 | 13 | @NotEmpty(message = "Name is required!") 14 | private String name; 15 | 16 | @NotEmpty(message = "Lastname is required!") 17 | private String lastname; 18 | 19 | @NotEmpty(message = "Email is required!") 20 | @Email(regexp = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}", 21 | flags = Pattern.Flag.CASE_INSENSITIVE, 22 | message = "Email must be a well-formed email address!") 23 | private String email; 24 | 25 | @NotEmpty(message = "Username is required!") 26 | private String username; 27 | 28 | @NotEmpty 29 | @NotEmpty(message = "Password is required!") 30 | private String password; 31 | 32 | 33 | private void setName(String name) { 34 | this.name = name.trim(); 35 | } 36 | 37 | private void setLastname(String lastname) { 38 | this.lastname = lastname.trim(); 39 | } 40 | 41 | private void setEmail(String email) { 42 | this.email = email.toLowerCase().trim(); 43 | } 44 | 45 | private void setUsername(String username) { 46 | this.username = username.trim(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/user/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.user; 2 | 3 | import com.springboot.blog.entity.Role; 4 | import lombok.Data; 5 | 6 | import java.util.Set; 7 | import java.util.stream.Collectors; 8 | 9 | 10 | @Data 11 | public class UserDto { 12 | 13 | private Long id; 14 | private String name; 15 | private String lastname; 16 | private String email; 17 | private String username; 18 | private Set roles; 19 | 20 | 21 | public void setRoles(Set roles) { 22 | this.roles = roles.stream().map(Role::getRole).collect(Collectors.toSet()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/dto/user/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.dto.user; 2 | 3 | import com.springboot.blog.entity.User; 4 | import com.springboot.blog.security.service.UserDetailsImpl; 5 | import org.mapstruct.Mapper; 6 | import org.mapstruct.Mapping; 7 | import org.mapstruct.factory.Mappers; 8 | 9 | @Mapper 10 | public interface UserMapper { 11 | 12 | UserMapper INSTANCE = Mappers.getMapper(UserMapper.class); 13 | 14 | RegisterDto dtoToEntity(User user); 15 | User entityToDto(RegisterDto dto); 16 | @Mapping(target = "user.roles", ignore = true) 17 | UserDto userDetailsToUserDto(UserDetailsImpl user); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/entity/Comment.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.entity; 2 | 3 | import lombok.*; 4 | import org.hibernate.Hibernate; 5 | import org.hibernate.annotations.CreationTimestamp; 6 | 7 | import javax.persistence.*; 8 | import java.time.LocalDateTime; 9 | import java.util.Objects; 10 | 11 | @Getter 12 | @ToString 13 | @RequiredArgsConstructor 14 | @Setter 15 | @Entity 16 | @Table(name = "comments") 17 | public class Comment { 18 | 19 | @Id 20 | @GeneratedValue(strategy = GenerationType.IDENTITY) 21 | private Long id; 22 | 23 | @Column(nullable = false) 24 | private String name; 25 | 26 | @Column(nullable = false) 27 | private String email; 28 | 29 | @Column(nullable = false) 30 | private String message; 31 | 32 | @CreationTimestamp 33 | @Column(name = "createdAt") 34 | private LocalDateTime createdAt; 35 | 36 | @ManyToOne(fetch = FetchType.LAZY) 37 | @JoinColumn(name = "post_id", nullable = false) 38 | @ToString.Exclude 39 | private Post post; 40 | 41 | 42 | @Override 43 | public boolean equals(Object o) { 44 | if (this == o) return true; 45 | if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; 46 | Comment comment = (Comment) o; 47 | return id != null && Objects.equals(id, comment.id); 48 | } 49 | 50 | @Override 51 | public int hashCode() { 52 | return getClass().hashCode(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/entity/Post.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.entity; 2 | 3 | 4 | import lombok.Getter; 5 | import lombok.RequiredArgsConstructor; 6 | import lombok.Setter; 7 | import lombok.ToString; 8 | import org.hibernate.Hibernate; 9 | import org.hibernate.annotations.CreationTimestamp; 10 | import org.hibernate.annotations.UpdateTimestamp; 11 | 12 | import javax.persistence.*; 13 | import java.time.LocalDateTime; 14 | import java.util.HashSet; 15 | import java.util.Objects; 16 | import java.util.Set; 17 | 18 | @Getter 19 | @Setter 20 | @ToString 21 | @RequiredArgsConstructor 22 | @Entity 23 | @Table(name = "posts") 24 | public class Post { 25 | 26 | @Id 27 | @GeneratedValue(strategy = GenerationType.IDENTITY) 28 | private Long id; 29 | 30 | @Column(name = "title", nullable = false, unique = true) 31 | private String title; 32 | 33 | @Column(name = "description", nullable = false) 34 | private String description; 35 | 36 | @Column(name = "content", nullable = false) 37 | private String content; 38 | 39 | @CreationTimestamp 40 | @Column(name = "createdAt") 41 | private LocalDateTime createdAt; 42 | 43 | @UpdateTimestamp 44 | @Column(name = "updatedAt") 45 | private LocalDateTime updatedAt; 46 | 47 | @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true) 48 | @ToString.Exclude 49 | private Set comments = new HashSet<>(); 50 | 51 | 52 | @Override 53 | public boolean equals(Object o) { 54 | if (this == o) return true; 55 | if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false; 56 | Post post = (Post) o; 57 | return id != null && Objects.equals(id, post.id); 58 | } 59 | 60 | @Override 61 | public int hashCode() { 62 | return getClass().hashCode(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.entity; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.RequiredArgsConstructor; 6 | import lombok.Setter; 7 | 8 | import javax.persistence.*; 9 | 10 | @Getter 11 | @Setter 12 | @Entity 13 | @Table(name = "roles") 14 | @RequiredArgsConstructor 15 | @AllArgsConstructor 16 | public class Role { 17 | 18 | @Id 19 | @GeneratedValue(strategy = GenerationType.IDENTITY) 20 | private Long id; 21 | 22 | @Column(length = 60) 23 | private String role; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.entity; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | import org.hibernate.annotations.CreationTimestamp; 6 | import org.hibernate.annotations.UpdateTimestamp; 7 | 8 | import javax.persistence.*; 9 | import java.time.LocalDateTime; 10 | import java.util.HashSet; 11 | import java.util.Set; 12 | 13 | @Setter 14 | @Getter 15 | @Entity 16 | @Table(name = "users") 17 | public class User { 18 | 19 | @Id 20 | @GeneratedValue(strategy = GenerationType.IDENTITY) 21 | private Long id; 22 | 23 | @Column 24 | private String name; 25 | 26 | @Column 27 | private String lastname; 28 | 29 | @Column(unique = true) 30 | private String email; 31 | 32 | @Column(unique = true) 33 | private String username; 34 | 35 | @Column 36 | private String password; 37 | 38 | @CreationTimestamp 39 | private LocalDateTime createdAt; 40 | 41 | @UpdateTimestamp 42 | private LocalDateTime updatedAt; 43 | 44 | @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 45 | @JoinTable( 46 | name = "users_roles", 47 | joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), 48 | inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") 49 | ) 50 | private Set roles = new HashSet<>(); 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/exception/BlogApiException.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.exception; 2 | 3 | public class BlogApiException extends RuntimeException { 4 | 5 | private final String message; 6 | 7 | public BlogApiException(String message) { 8 | this.message = message; 9 | } 10 | 11 | @Override 12 | public String getMessage() { 13 | return message; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.exception; 2 | 3 | 4 | import com.springboot.blog.utils.ErrorDetails; 5 | import io.jsonwebtoken.security.SecurityException; 6 | import org.apache.tomcat.websocket.AuthenticationException; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.security.access.AccessDeniedException; 10 | import org.springframework.web.bind.annotation.ControllerAdvice; 11 | import org.springframework.web.bind.annotation.ExceptionHandler; 12 | import org.springframework.web.context.request.WebRequest; 13 | import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; 14 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 15 | 16 | import java.util.Date; 17 | 18 | @ControllerAdvice 19 | public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { 20 | 21 | @ExceptionHandler(Exception.class) 22 | public ResponseEntity handleGlobalExceptions(Exception exception, WebRequest request) { 23 | ErrorDetails errorDetails = new ErrorDetails( 24 | new Date(), 25 | exception.getMessage(), 26 | request.getDescription(false) 27 | ); 28 | return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); 29 | } 30 | 31 | @ExceptionHandler(ResourceNotFoundException.class) 32 | public ResponseEntity handleResourceNotFoundException(ResourceNotFoundException exception, WebRequest request) { 33 | ErrorDetails errorDetails = new ErrorDetails( 34 | new Date(), 35 | exception.getMessage(), 36 | request.getDescription(false) 37 | ); 38 | return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); 39 | } 40 | 41 | @ExceptionHandler(BlogApiException.class) 42 | public ResponseEntity handleBlogApiException(BlogApiException exception, WebRequest request) { 43 | ErrorDetails errorDetails = new ErrorDetails( 44 | new Date(), 45 | exception.getMessage(), 46 | request.getDescription(false) 47 | ); 48 | return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST); 49 | } 50 | 51 | @ExceptionHandler(MethodArgumentTypeMismatchException.class) 52 | public ResponseEntity handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex, WebRequest request) { 53 | ErrorDetails errorDetails = new ErrorDetails( 54 | new Date(), 55 | ex.getMessage(), 56 | request.getDescription(false) 57 | ); 58 | return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST); 59 | } 60 | 61 | @ExceptionHandler(AuthenticationException.class) 62 | public ResponseEntity handleAuthenticationException(AuthenticationException ex, WebRequest request) { 63 | ErrorDetails errorDetails = new ErrorDetails( 64 | new Date(), 65 | ex.getMessage(), 66 | request.getDescription(false) 67 | ); 68 | return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST); 69 | } 70 | 71 | @ExceptionHandler(SecurityException.class) 72 | public ResponseEntity handleSecurityException(SecurityException ex, WebRequest request) { 73 | ErrorDetails errorDetails = new ErrorDetails( 74 | new Date(), 75 | ex.getMessage(), 76 | request.getDescription(false) 77 | ); 78 | return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST); 79 | } 80 | 81 | @ExceptionHandler(AccessDeniedException.class) 82 | public final ResponseEntity handleAccessDeniedException(AccessDeniedException ex, WebRequest request) { 83 | ErrorDetails errorDetails = new ErrorDetails( 84 | new Date(), 85 | ex.getMessage(), 86 | request.getDescription(false) 87 | ); 88 | return new ResponseEntity<>(errorDetails, HttpStatus.UNAUTHORIZED); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/exception/ResourceNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | 7 | @ResponseStatus(value = HttpStatus.NOT_FOUND) 8 | public class ResourceNotFoundException extends RuntimeException { 9 | 10 | public ResourceNotFoundException(String resourceName, String fieldName, Long id) { 11 | super(String.format("%s not found with %s: '%s'", resourceName, fieldName, id)); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/exception/ValidationErrorsHandler.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.exception; 2 | 3 | import com.springboot.blog.utils.ValidationErrors; 4 | import org.springframework.core.Ordered; 5 | import org.springframework.core.annotation.Order; 6 | import org.springframework.http.HttpStatus; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.MethodArgumentNotValidException; 9 | import org.springframework.web.bind.annotation.ControllerAdvice; 10 | import org.springframework.web.bind.annotation.ExceptionHandler; 11 | import org.springframework.web.context.request.WebRequest; 12 | 13 | import java.util.*; 14 | 15 | 16 | @Order(Ordered.HIGHEST_PRECEDENCE) 17 | @ControllerAdvice 18 | public class ValidationErrorsHandler { 19 | 20 | @ExceptionHandler(MethodArgumentNotValidException.class) 21 | public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, WebRequest request) { 22 | Map errors = new HashMap<>(); 23 | ex.getBindingResult().getFieldErrors().forEach((error) -> errors.put(error.getField(), error.getDefaultMessage())); 24 | ValidationErrors validationErrors = new ValidationErrors( 25 | new Date(), 26 | errors, 27 | request.getDescription(false) 28 | ); 29 | return new ResponseEntity<>(validationErrors, HttpStatus.BAD_REQUEST); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/repository/CommentRepository.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.repository; 2 | 3 | import com.springboot.blog.entity.Comment; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.List; 7 | 8 | public interface CommentRepository extends JpaRepository { 9 | 10 | List findByPostId(Long postId); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/repository/PostRepository.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.repository; 2 | 3 | import com.springboot.blog.entity.Post; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | 9 | public interface PostRepository extends JpaRepository { 10 | 11 | Optional findByTitle(String title); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.repository; 2 | 3 | import com.springboot.blog.entity.Role; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface RoleRepository extends JpaRepository { 9 | 10 | Optional findByRole(String role); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.repository; 2 | 3 | import com.springboot.blog.entity.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface UserRepository extends JpaRepository { 9 | 10 | Optional findByEmail(String email); 11 | Optional findByUsername(String username); 12 | Optional findByUsernameOrEmail(String username, String email); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/security/jwt/JwtAuthEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.security.jwt; 2 | 3 | import org.springframework.security.core.AuthenticationException; 4 | import org.springframework.security.web.AuthenticationEntryPoint; 5 | import org.springframework.stereotype.Component; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | 11 | @Component 12 | public class JwtAuthEntryPoint implements AuthenticationEntryPoint { 13 | 14 | @Override 15 | public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { 16 | response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/security/jwt/JwtAuthFilter.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.security.jwt; 2 | 3 | import com.springboot.blog.exception.BlogApiException; 4 | import com.springboot.blog.security.service.UserDetailsServiceImpl; 5 | import org.jetbrains.annotations.NotNull; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.security.access.AccessDeniedException; 8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 9 | import org.springframework.security.core.context.SecurityContextHolder; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 12 | import org.springframework.stereotype.Component; 13 | import org.springframework.util.StringUtils; 14 | import org.springframework.web.filter.OncePerRequestFilter; 15 | 16 | import javax.servlet.FilterChain; 17 | import javax.servlet.ServletException; 18 | import javax.servlet.http.HttpServletRequest; 19 | import javax.servlet.http.HttpServletResponse; 20 | import java.io.IOException; 21 | 22 | @Component 23 | public class JwtAuthFilter extends OncePerRequestFilter { 24 | 25 | @Autowired 26 | private JwtUtils jwtUtils; 27 | @Autowired 28 | private UserDetailsServiceImpl userDetailsService; 29 | 30 | 31 | @Override 32 | protected void doFilterInternal( 33 | @NotNull HttpServletRequest request, 34 | @NotNull HttpServletResponse response, 35 | @NotNull FilterChain filterChain) throws ServletException, IOException { 36 | 37 | try { 38 | String jwt = parseJwt(request); 39 | if (jwt != null && jwtUtils.validateJwtToken(jwt)) { 40 | String usernameOrEmail = jwtUtils.getUsernameFromJWT(jwt); 41 | UserDetails userDetails = userDetailsService.loadUserByUsername(usernameOrEmail); 42 | 43 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( 44 | userDetails, 45 | null, 46 | userDetails.getAuthorities() 47 | ); 48 | 49 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 50 | SecurityContextHolder.getContext().setAuthentication(authentication); 51 | } 52 | filterChain.doFilter(request, response); 53 | } catch (AccessDeniedException ex) { 54 | throw new BlogApiException(ex.getMessage()); 55 | } 56 | } 57 | 58 | 59 | 60 | 61 | private String parseJwt(HttpServletRequest request) { 62 | String headerAuth = request.getHeader("Authorization"); 63 | if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) { 64 | return headerAuth.substring(7); 65 | } 66 | return null; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/security/jwt/JwtUtils.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.security.jwt; 2 | 3 | import com.springboot.blog.exception.BlogApiException; 4 | import com.springboot.blog.security.service.UserDetailsImpl; 5 | import io.jsonwebtoken.ExpiredJwtException; 6 | import io.jsonwebtoken.Jwts; 7 | import io.jsonwebtoken.MalformedJwtException; 8 | import io.jsonwebtoken.UnsupportedJwtException; 9 | import io.jsonwebtoken.io.Decoders; 10 | import io.jsonwebtoken.security.Keys; 11 | import io.jsonwebtoken.security.SignatureException; 12 | import org.springframework.beans.factory.annotation.Value; 13 | import org.springframework.security.core.Authentication; 14 | import org.springframework.stereotype.Component; 15 | 16 | import java.security.Key; 17 | import java.util.Date; 18 | 19 | @Component 20 | public class JwtUtils { 21 | 22 | @Value("${app.jwt-secret}") 23 | private String jwtSecret; 24 | 25 | @Value("${app.jwt-expiration-date}") 26 | private int jwtExpirationDate; 27 | 28 | 29 | public Boolean validateJwtToken(String token) { 30 | try { 31 | Jwts.parserBuilder() 32 | .setSigningKey(key()) 33 | .requireIssuer("springboot_rest_api") 34 | .build() 35 | .parse(token); 36 | return true; 37 | } catch (SignatureException ex) { 38 | throw new BlogApiException("Invalid Jwt signature"); 39 | } catch (MalformedJwtException ex) { 40 | throw new BlogApiException("Invalid Jwt token"); 41 | } catch (ExpiredJwtException ex) { 42 | throw new BlogApiException("Expired Jwt token"); 43 | } catch (UnsupportedJwtException ex) { 44 | throw new BlogApiException("Unsupported Jwt token"); 45 | } catch (IllegalArgumentException ex) { 46 | throw new BlogApiException("Jwt claims string is empty"); 47 | } 48 | } 49 | 50 | public String generateJwtToken(Authentication authentication) { 51 | Date currentDate = new Date(); 52 | Date expireDate = new Date(currentDate.getTime() + jwtExpirationDate); 53 | UserDetailsImpl principal = (UserDetailsImpl) authentication.getPrincipal(); 54 | 55 | return Jwts.builder() 56 | .claim("username", principal.getUsername()) 57 | .claim("email", principal.getEmail()) 58 | .setIssuer("springboot_rest_api") 59 | .setIssuedAt(currentDate) 60 | .setExpiration(expireDate) 61 | .signWith(key()) 62 | .compact(); 63 | } 64 | 65 | public String getUsernameFromJWT(String token){ 66 | return Jwts.parserBuilder() 67 | .setSigningKey(key()) 68 | .build() 69 | .parseClaimsJws(token) 70 | .getBody().get("email").toString(); 71 | } 72 | 73 | private Key key() { 74 | return Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret)); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/security/service/UserDetailsImpl.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.security.service; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.springboot.blog.entity.Role; 5 | import com.springboot.blog.entity.User; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Data; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.security.core.GrantedAuthority; 10 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | 13 | import java.util.Collection; 14 | import java.util.Set; 15 | import java.util.stream.Collectors; 16 | 17 | @Data 18 | @RequiredArgsConstructor 19 | @AllArgsConstructor 20 | public class UserDetailsImpl implements UserDetails { 21 | 22 | private Long id; 23 | private String name; 24 | private String lastname; 25 | private String username; 26 | private String email; 27 | 28 | @JsonIgnore 29 | private String password; 30 | 31 | @JsonIgnore 32 | private Set roles; 33 | 34 | 35 | public static UserDetailsImpl build(User user) { 36 | return new UserDetailsImpl( 37 | user.getId(), 38 | user.getName(), 39 | user.getLastname(), 40 | user.getUsername(), 41 | user.getEmail(), 42 | user.getPassword(), 43 | user.getRoles() 44 | ); 45 | } 46 | 47 | @Override 48 | public Collection getAuthorities() { 49 | return roles.stream().map(role -> 50 | new SimpleGrantedAuthority(role.getRole())).collect(Collectors.toList() 51 | ); 52 | } 53 | 54 | @Override 55 | public boolean isAccountNonExpired() { 56 | return true; 57 | } 58 | 59 | @Override 60 | public boolean isAccountNonLocked() { 61 | return true; 62 | } 63 | 64 | @Override 65 | public boolean isCredentialsNonExpired() { 66 | return true; 67 | } 68 | 69 | @Override 70 | public boolean isEnabled() { 71 | return true; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/security/service/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.security.service; 2 | 3 | import com.springboot.blog.entity.User; 4 | import com.springboot.blog.repository.UserRepository; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | import org.springframework.security.core.userdetails.UserDetailsService; 7 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | public class UserDetailsServiceImpl implements UserDetailsService { 12 | 13 | private final UserRepository userRepository; 14 | 15 | public UserDetailsServiceImpl(UserRepository userRepository) { 16 | this.userRepository = userRepository; 17 | } 18 | 19 | @Override 20 | public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException { 21 | User user = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail) 22 | .orElseThrow(() -> new UsernameNotFoundException("User not found with email:" + usernameOrEmail)); 23 | return UserDetailsImpl.build(user); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/service/auth/AuthService.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.service.auth; 2 | 3 | import com.springboot.blog.dto.auth.LoginDto; 4 | import com.springboot.blog.dto.auth.LoginResponseDto; 5 | import com.springboot.blog.dto.user.RegisterDto; 6 | import com.springboot.blog.entity.Role; 7 | import org.springframework.http.ResponseEntity; 8 | 9 | import java.util.Optional; 10 | 11 | public interface AuthService { 12 | 13 | ResponseEntity login(LoginDto dto); 14 | ResponseEntity register(RegisterDto dto); 15 | void createRole(Role role); 16 | Optional findByRole(String roleType); 17 | void addRoleToUser(String email, String roleType); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/service/auth/AuthServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.service.auth; 2 | 3 | import com.springboot.blog.dto.auth.LoginDto; 4 | import com.springboot.blog.dto.auth.LoginResponseDto; 5 | import com.springboot.blog.dto.user.*; 6 | import com.springboot.blog.entity.Role; 7 | import com.springboot.blog.entity.User; 8 | import com.springboot.blog.repository.RoleRepository; 9 | import com.springboot.blog.repository.UserRepository; 10 | import com.springboot.blog.security.jwt.JwtUtils; 11 | import com.springboot.blog.security.service.UserDetailsImpl; 12 | import lombok.AllArgsConstructor; 13 | import org.springframework.beans.BeanUtils; 14 | import org.springframework.http.HttpStatus; 15 | import org.springframework.http.ResponseEntity; 16 | import org.springframework.security.authentication.AuthenticationManager; 17 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 18 | import org.springframework.security.core.Authentication; 19 | import org.springframework.security.core.context.SecurityContextHolder; 20 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 21 | import org.springframework.security.crypto.password.PasswordEncoder; 22 | import org.springframework.stereotype.Service; 23 | 24 | import java.util.Collections; 25 | import java.util.HashSet; 26 | import java.util.Optional; 27 | import java.util.Set; 28 | 29 | @Service 30 | @AllArgsConstructor 31 | public class AuthServiceImpl implements AuthService { 32 | 33 | private final AuthenticationManager authenticationManager; 34 | private final UserRepository userRepository; 35 | private final RoleRepository roleRepository; 36 | private final PasswordEncoder passwordEncoder; 37 | private final JwtUtils jwtUtils; 38 | 39 | 40 | @Override 41 | public ResponseEntity login(LoginDto dto) { 42 | Authentication auth = authenticationManager.authenticate( 43 | new UsernamePasswordAuthenticationToken(dto.getUsernameOrEmail(), dto.getPassword()) 44 | ); 45 | SecurityContextHolder.getContext().setAuthentication(auth); 46 | String token = jwtUtils.generateJwtToken(auth); 47 | UserDetailsImpl principal = (UserDetailsImpl) auth.getPrincipal(); 48 | UserDto user = UserMapper.INSTANCE.userDetailsToUserDto(principal); 49 | return new ResponseEntity<>(new LoginResponseDto(user, token), HttpStatus.OK); 50 | } 51 | 52 | @Override 53 | public ResponseEntity register(RegisterDto dto) { 54 | if (userRepository.findByEmail(dto.getEmail()).isPresent()) { 55 | return new ResponseEntity<>("Email is already registered!", HttpStatus.BAD_REQUEST); 56 | } 57 | if (userRepository.findByUsername(dto.getUsername()).isPresent()) { 58 | return new ResponseEntity<>("Username is already registered!", HttpStatus.BAD_REQUEST); 59 | } 60 | 61 | User user = new User(); 62 | BeanUtils.copyProperties(dto, user); 63 | user.setPassword(passwordEncoder.encode(dto.getPassword())); 64 | addRolesToUser(user); 65 | userRepository.save(user); 66 | return new ResponseEntity<>("User registered!", HttpStatus.CREATED); 67 | } 68 | 69 | @Override 70 | public void createRole(Role role) { 71 | roleRepository.save(role); 72 | } 73 | 74 | @Override 75 | public Optional findByRole(String roleType) { 76 | return roleRepository.findByRole(roleType); 77 | } 78 | 79 | @Override 80 | public void addRoleToUser(String email, String roleType) { 81 | User user = userRepository.findByEmail(email).orElseThrow( 82 | () -> new UsernameNotFoundException("User not found with email:" + email) 83 | ); 84 | Role role = roleRepository.findByRole(roleType).orElse(null); 85 | user.setRoles(Collections.singleton(role)); 86 | } 87 | 88 | 89 | private void addRolesToUser(User user) { 90 | Set roleArr = new HashSet<>(); 91 | roleArr.add(roleRepository.findByRole("ROLE_USER").orElse(null)); 92 | user.setRoles(new HashSet<>(roleArr)); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/service/comment/CommentService.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.service.comment; 2 | 3 | import com.springboot.blog.dto.comment.CommentDto; 4 | import com.springboot.blog.dto.comment.UpdateCommentDto; 5 | 6 | import java.util.List; 7 | 8 | public interface CommentService { 9 | 10 | CommentDto create(Long postId, CommentDto dto); 11 | List getAllByPost(Long postId); 12 | CommentDto getCommentById(Long postId, Long commentId); 13 | CommentDto update(Long postId, Long commentId, UpdateCommentDto dto); 14 | void delete(Long postId, Long commentId); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/service/comment/CommentServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.service.comment; 2 | 3 | 4 | import com.springboot.blog.dto.comment.CommentDto; 5 | import com.springboot.blog.dto.comment.CommentMapper; 6 | import com.springboot.blog.dto.comment.UpdateCommentDto; 7 | import com.springboot.blog.entity.Comment; 8 | import com.springboot.blog.entity.Post; 9 | import com.springboot.blog.exception.BlogApiException; 10 | import com.springboot.blog.exception.ResourceNotFoundException; 11 | import com.springboot.blog.repository.CommentRepository; 12 | import com.springboot.blog.repository.PostRepository; 13 | import lombok.AllArgsConstructor; 14 | import org.springframework.beans.BeanUtils; 15 | import org.springframework.security.access.prepost.PreAuthorize; 16 | import org.springframework.stereotype.Service; 17 | 18 | import java.util.List; 19 | import java.util.stream.Collectors; 20 | 21 | @Service 22 | @AllArgsConstructor 23 | public class CommentServiceImpl implements CommentService { 24 | private final CommentRepository commentRepository; 25 | private final PostRepository postRepository; 26 | 27 | 28 | @Override 29 | @PreAuthorize("hasRole('ADMIN')") 30 | public CommentDto create(Long postId, CommentDto dto) { 31 | Post post = getPostById(postId); 32 | Comment comment = CommentMapper.INSTANCE.dtoToEntity(dto); 33 | comment.setPost(post); 34 | commentRepository.save(comment); 35 | return CommentMapper.INSTANCE.entityToDto(comment); 36 | } 37 | 38 | @Override 39 | public List getAllByPost(Long postId) { 40 | List comments = commentRepository.findByPostId(postId); 41 | return comments.stream().map(CommentMapper.INSTANCE::entityToDto).collect(Collectors.toList()); 42 | } 43 | 44 | @Override 45 | public CommentDto getCommentById(Long postId, Long commentId) { 46 | Post post = getPostById(postId); 47 | Comment comment = getCommentById(commentId); 48 | if (!comment.getPost().getId().equals(post.getId())) { 49 | throw new BlogApiException("Comment does not belong to post!"); 50 | } 51 | return CommentMapper.INSTANCE.entityToDto(comment); 52 | } 53 | 54 | @Override 55 | @PreAuthorize("hasRole('ADMIN')") 56 | public CommentDto update(Long postId, Long commentId, UpdateCommentDto dto) { 57 | Comment comment = getCommentById(commentId); 58 | Post post = getPostById(postId); 59 | if (!comment.getPost().getId().equals(post.getId())) { 60 | throw new BlogApiException("Comment does not belong to post!"); 61 | } 62 | BeanUtils.copyProperties(dto, comment); 63 | commentRepository.save(comment); 64 | return CommentMapper.INSTANCE.entityToDto(comment); 65 | } 66 | 67 | @Override 68 | @PreAuthorize("hasRole('ADMIN')") 69 | public void delete(Long postId, Long commentId) { 70 | Post post = getPostById(postId); 71 | Comment comment = getCommentById(commentId); 72 | if (!comment.getPost().getId().equals(post.getId())) { 73 | throw new BlogApiException("Comment does not belong to post!"); 74 | } 75 | commentRepository.deleteById(commentId); 76 | } 77 | 78 | 79 | private Post getPostById(Long id) { 80 | return postRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Post", "id", id)); 81 | } 82 | 83 | private Comment getCommentById(Long id) { 84 | return commentRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Comment", "id", id)); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/service/post/PostService.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.service.post; 2 | 3 | 4 | import com.springboot.blog.dto.post.CreatePostDto; 5 | import com.springboot.blog.dto.post.PostDto; 6 | import com.springboot.blog.dto.post.UpdatePostDto; 7 | import com.springboot.blog.dto.post.PostResponseDto; 8 | import org.springframework.http.ResponseEntity; 9 | 10 | public interface PostService { 11 | 12 | ResponseEntity create(CreatePostDto dto); 13 | PostResponseDto getAll(int page, int size, String sort, String sortBy); 14 | PostDto getById(Long id); 15 | PostDto update(Long id, UpdatePostDto dto); 16 | void delete(Long id); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/service/post/PostServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.service.post; 2 | 3 | import com.springboot.blog.dto.post.CreatePostDto; 4 | import com.springboot.blog.dto.post.PostDto; 5 | import com.springboot.blog.dto.post.PostMapper; 6 | import com.springboot.blog.dto.post.UpdatePostDto; 7 | import com.springboot.blog.entity.Post; 8 | import com.springboot.blog.exception.BlogApiException; 9 | import com.springboot.blog.exception.ResourceNotFoundException; 10 | import com.springboot.blog.repository.CommentRepository; 11 | import com.springboot.blog.repository.PostRepository; 12 | import com.springboot.blog.dto.post.PostResponseDto; 13 | import lombok.AllArgsConstructor; 14 | import org.springframework.beans.BeanUtils; 15 | import org.springframework.data.domain.Page; 16 | import org.springframework.data.domain.PageRequest; 17 | import org.springframework.data.domain.Pageable; 18 | import org.springframework.data.domain.Sort; 19 | import org.springframework.http.HttpStatus; 20 | import org.springframework.http.ResponseEntity; 21 | import org.springframework.security.access.prepost.PreAuthorize; 22 | import org.springframework.stereotype.Service; 23 | 24 | import java.util.List; 25 | import java.util.stream.Collectors; 26 | 27 | @Service 28 | @AllArgsConstructor 29 | public class PostServiceImpl implements PostService { 30 | private final PostRepository postRepository; 31 | private final CommentRepository commentRepository; 32 | 33 | 34 | @Override 35 | @PreAuthorize("hasRole('ADMIN')") 36 | public ResponseEntity create(CreatePostDto dto) { 37 | findByTitle(dto.getTitle()); 38 | Post post = new Post(); 39 | post.setTitle(dto.getTitle()); 40 | post.setDescription(dto.getDescription()); 41 | post.setContent(dto.getContent()); 42 | postRepository.save(post); 43 | return new ResponseEntity<>(PostMapper.INSTANCE.entityToDto(post), HttpStatus.CREATED); 44 | } 45 | 46 | @Override 47 | public PostResponseDto getAll(int page, int size, String sort, String sortBy) { 48 | Pageable pageable = PageRequest.of(page, size, Sort.Direction.fromString(sort), sortBy); 49 | Page posts = postRepository.findAll(pageable); 50 | List content = posts.stream().map(PostMapper.INSTANCE::entityToDto).collect(Collectors.toList()); 51 | return new PostResponseDto( 52 | content, 53 | posts.getNumber(), 54 | posts.getSize(), 55 | posts.getTotalElements(), 56 | posts.getTotalPages(), 57 | posts.isLast() 58 | ); 59 | } 60 | 61 | @Override 62 | public PostDto getById(Long id) { 63 | Post post = getEntityById(id); 64 | return PostMapper.INSTANCE.entityToDto(post); 65 | } 66 | 67 | @Override 68 | @PreAuthorize("hasRole('ADMIN')") 69 | public PostDto update(Long id, UpdatePostDto dto) { 70 | findByTitle(dto.getTitle()); 71 | Post post = getEntityById(id); 72 | if (post.getTitle().equals(dto.getTitle())) { 73 | throw new BlogApiException("Title already exist! Think new one."); 74 | } 75 | BeanUtils.copyProperties(dto, post); 76 | postRepository.save(post); 77 | return PostMapper.INSTANCE.entityToDto(post); 78 | } 79 | 80 | @Override 81 | @PreAuthorize("hasRole('ADMIN')") 82 | public void delete(Long id) { 83 | Post post = getEntityById(id); 84 | commentRepository.deleteAll(post.getComments()); 85 | postRepository.deleteById(post.getId()); 86 | } 87 | 88 | 89 | private Post getEntityById(Long id) { 90 | return postRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Post", "id", id)); 91 | } 92 | 93 | private void findByTitle(String title) { 94 | if (postRepository.findByTitle(title).isPresent()) 95 | throw new BlogApiException("Title already exist! Think new one."); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/service/user/UserService.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.service.user; 2 | 3 | import com.springboot.blog.entity.User; 4 | 5 | public interface UserService { 6 | 7 | User getUser(String email); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/service/user/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.service.user; 2 | 3 | import com.springboot.blog.entity.User; 4 | import com.springboot.blog.repository.UserRepository; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | 11 | @Service 12 | @RequiredArgsConstructor 13 | @Transactional 14 | public class UserServiceImpl implements UserService { 15 | private final UserRepository userRepository; 16 | 17 | 18 | @Override 19 | public User getUser(String email) { 20 | return userRepository.findByEmail(email).orElseThrow( 21 | () -> new UsernameNotFoundException("User not found with email:" + email) 22 | ); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/utils/AppConstants.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.utils; 2 | 3 | public class AppConstants { 4 | 5 | public static final String DEFAULT_PAGE = "0"; 6 | public static final String DEFAULT_SIZE = "5"; 7 | public static final String DEFAULT_SORT_BY = "id"; 8 | public static final String DEFAULT_SORT_DIRECTION = "desc"; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/utils/ErrorDetails.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.utils; 2 | 3 | import java.util.Date; 4 | 5 | public class ErrorDetails { 6 | 7 | private final Date timestamp; 8 | private final String message; 9 | private final String path; 10 | 11 | public ErrorDetails(Date timestamp, String message, String path) { 12 | this.timestamp = timestamp; 13 | this.message = message; 14 | this.path = path; 15 | } 16 | 17 | public Date getTimestamp() { 18 | return timestamp; 19 | } 20 | 21 | public String getMessage() { 22 | return message; 23 | } 24 | 25 | public String getPath() { 26 | return path; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/springboot/blog/utils/ValidationErrors.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog.utils; 2 | 3 | import java.util.Date; 4 | import java.util.Map; 5 | 6 | public class ValidationErrors { 7 | 8 | private final Date timestamp; 9 | private final Map errors; 10 | private final String path; 11 | 12 | public ValidationErrors(Date timestamp, Map errors, String path) { 13 | this.timestamp = timestamp; 14 | this.errors = errors; 15 | this.path = path; 16 | } 17 | 18 | public Date getTimestamp() { 19 | return timestamp; 20 | } 21 | 22 | public Map getErrors() { 23 | return errors; 24 | } 25 | 26 | public String getPath() { 27 | return path; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url = jdbc:postgresql://localhost:5432/myblog?useSSL=false&serverTimezone=UTC 2 | spring.datasource.username = postgres 3 | spring.datasource.password = postgres 4 | 5 | # hibernate properties 6 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect 7 | spring.jpa.hibernate.ddl-auto = update 8 | 9 | spring.devtools.restart.enabled = true 10 | 11 | 12 | logging.level.org.springframework.security = DEBUG 13 | # Jwt 14 | app.jwt-secret = RQE3VKNbYLx4R6XmXRXMZ6cDc7LmyXuyGJ3qUZK5DzMxq8v72XvuZYi5 15 | app.jwt-expiration-date = 604800000 -------------------------------------------------------------------------------- /src/main/resources/application-prod.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dvun/springboot-blog_rest_api/c381ce3148cc2fb5a091b9010cb75443f5ce907a/src/main/resources/application-prod.properties -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=dev -------------------------------------------------------------------------------- /src/test/java/com/springboot/blog/SpringbootBlogRestApiApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.springboot.blog; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SpringbootBlogRestApiApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | --------------------------------------------------------------------------------