├── .gitignore ├── README.md ├── backend └── twitter-clone │ ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties │ ├── docker-compose.yml │ ├── mvnw │ ├── mvnw.cmd │ ├── pom.xml │ └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── safalifter │ │ │ └── twitterclone │ │ │ ├── TwitterCloneApplication.java │ │ │ ├── bucket │ │ │ └── BucketName.java │ │ │ ├── config │ │ │ ├── AmazonConfig.java │ │ │ ├── BeanConfig.java │ │ │ ├── OpenApiConfig.java │ │ │ └── SecurityConfig.java │ │ │ ├── controller │ │ │ ├── AuthController.java │ │ │ ├── CommentController.java │ │ │ ├── LikeController.java │ │ │ ├── RetweetController.java │ │ │ ├── TweetController.java │ │ │ └── UserController.java │ │ │ ├── dto │ │ │ ├── CommentDto.java │ │ │ ├── LikeDto.java │ │ │ ├── RetweetDto.java │ │ │ ├── TokenDTO.java │ │ │ ├── TweetDto.java │ │ │ └── UserDto.java │ │ │ ├── exc │ │ │ ├── GeneralExceptionHandler.java │ │ │ ├── GenericErrorResponse.java │ │ │ ├── NotFoundException.java │ │ │ └── WrongCredentialsException.java │ │ │ ├── model │ │ │ ├── BaseEntity.java │ │ │ ├── Comment.java │ │ │ ├── Like.java │ │ │ ├── Retweet.java │ │ │ ├── Role.java │ │ │ ├── Tweet.java │ │ │ └── User.java │ │ │ ├── repository │ │ │ ├── CommentRepository.java │ │ │ ├── LikeRepository.java │ │ │ ├── RetweetRepository.java │ │ │ ├── TweetRepository.java │ │ │ └── UserRepository.java │ │ │ ├── request │ │ │ ├── AuthRequest.java │ │ │ ├── CommentCreateRequest.java │ │ │ ├── LikeCreateRequest.java │ │ │ ├── RegisterRequest.java │ │ │ ├── RetweetCreateRequest.java │ │ │ ├── TweetCreateRequest.java │ │ │ ├── UpdateCommentRequest.java │ │ │ ├── UpdateRetweetRequest.java │ │ │ ├── UpdateTweetRequest.java │ │ │ └── UpdateUserRequest.java │ │ │ ├── security │ │ │ ├── JWTAccessDeniedHandler.java │ │ │ ├── JwtAuthenticationEntryPoint.java │ │ │ └── JwtFilter.java │ │ │ └── service │ │ │ ├── AuthService.java │ │ │ ├── CommentService.java │ │ │ ├── FileService.java │ │ │ ├── LikeService.java │ │ │ ├── RetweetService.java │ │ │ ├── S3Service.java │ │ │ ├── TokenService.java │ │ │ ├── TweetService.java │ │ │ ├── UserDetailsServiceImpl.java │ │ │ └── UserService.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── safalifter │ └── twitterclone │ └── TwitterCloneApplicationTests.java └── frontend └── twitter-clone ├── .gitignore ├── README.md ├── craco.config.js ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png └── manifest.json ├── src ├── App.js ├── components │ ├── Box.js │ ├── CommentBox.js │ ├── Divider.js │ ├── FeedItem.js │ ├── FeedList.js │ ├── Modal.js │ ├── MyDropzone.js │ ├── RetweetBox.js │ ├── SideLink.js │ ├── TweetBox.js │ └── UserBox.js ├── icons │ └── Icon.js ├── images │ ├── bird.svg │ ├── defaul-bg.png │ ├── default-profile.png │ └── twitter.svg ├── index.css ├── index.js ├── layout │ ├── Container.js │ ├── Content.js │ ├── Login.js │ ├── Sidebar.js │ ├── Signup.js │ └── Widgets.js ├── pages │ ├── Home.js │ ├── Tweet.js │ └── User.js ├── redux │ ├── configureStore.js │ └── reduxSlice.js ├── reportWebVitals.js └── service │ ├── AuthService.js │ ├── CommentService.js │ ├── LikeService.js │ ├── RetweetService.js │ ├── TweetService.js │ └── UserService.js └── tailwind.config.js /.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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Twitter Clone Full stack Spring-React project

2 | Ekran Resmi 2023-03-07 13 27 05 3 | Ekran Resmi 2023-03-07 13 05 04 4 | Ekran Resmi 2023-03-07 13 26 43 5 | Ekran Resmi 2023-03-07 13 05 25 6 | Ekran Resmi 2023-03-07 13 06 25 7 | Ekran Resmi 2023-03-07 13 06 29 8 | Ekran Resmi 2023-03-07 13 06 32 9 | Ekran Resmi 2023-03-07 13 07 40 10 | Ekran Resmi 2023-03-07 13 22 18 11 | Ekran Resmi 2023-03-07 13 22 43 12 | Ekran Resmi 2023-03-07 13 25 08 13 | Ekran Resmi 2023-03-07 13 52 42 14 | -------------------------------------------------------------------------------- /backend/twitter-clone/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devxsb/twitter-clone-spring-react/8eec3bb819b2fb42f7ca476d82dfe37d54022b42/backend/twitter-clone/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /backend/twitter-clone/.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 | -------------------------------------------------------------------------------- /backend/twitter-clone/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.1' 2 | 3 | services: 4 | 5 | db: 6 | image: postgres 7 | restart: always 8 | ports: 9 | - "5432:5432" 10 | environment: 11 | POSTGRES_PASSWORD: 55 -------------------------------------------------------------------------------- /backend/twitter-clone/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 | -------------------------------------------------------------------------------- /backend/twitter-clone/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 | -------------------------------------------------------------------------------- /backend/twitter-clone/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.7.7 9 | 10 | 11 | com.safalifter 12 | twitter-clone 13 | 0.0.1-SNAPSHOT 14 | twitter-clone 15 | twitter-clone 16 | 17 | 17 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-data-jpa 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-security 31 | 32 | 33 | com.auth0 34 | java-jwt 35 | 4.0.0 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-devtools 40 | runtime 41 | true 42 | 43 | 44 | org.postgresql 45 | postgresql 46 | runtime 47 | 48 | 49 | org.projectlombok 50 | lombok 51 | true 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-test 56 | test 57 | 58 | 59 | 60 | org.springdoc 61 | springdoc-openapi-ui 62 | 1.6.14 63 | 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-starter-validation 68 | 69 | 70 | 71 | org.modelmapper 72 | modelmapper 73 | 3.1.0 74 | 75 | 76 | 77 | 78 | com.amazonaws 79 | aws-java-sdk 80 | 1.12.410 81 | 82 | 83 | 84 | 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-maven-plugin 89 | 90 | 91 | 92 | org.projectlombok 93 | lombok 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/TwitterCloneApplication.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class TwitterCloneApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(TwitterCloneApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/bucket/BucketName.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.bucket; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | 6 | @RequiredArgsConstructor 7 | @Getter 8 | public enum BucketName { 9 | PROFILE_IMAGE("**********"); // bucket name 10 | private final String bucketName; 11 | } 12 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/config/AmazonConfig.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.config; 2 | 3 | import com.amazonaws.auth.AWSCredentials; 4 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 5 | import com.amazonaws.auth.BasicAWSCredentials; 6 | import com.amazonaws.services.s3.AmazonS3; 7 | import com.amazonaws.services.s3.AmazonS3ClientBuilder; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration 12 | public class AmazonConfig { 13 | 14 | @Bean 15 | public AmazonS3 amazonS3() { 16 | AWSCredentials awsCredentials = new BasicAWSCredentials( 17 | "**********", // access key id 18 | "**********" // secret access key 19 | ); 20 | return AmazonS3ClientBuilder 21 | .standard() 22 | .withRegion("eu-west-1") 23 | .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) 24 | .build(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/config/BeanConfig.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.config; 2 | 3 | import org.modelmapper.ModelMapper; 4 | import org.modelmapper.convention.MatchingStrategies; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 8 | 9 | @Configuration 10 | public class BeanConfig { 11 | 12 | @Bean 13 | public BCryptPasswordEncoder bCryptPasswordEncoder() { 14 | return new BCryptPasswordEncoder(); 15 | } 16 | 17 | @Bean 18 | public ModelMapper getModelMapper() { 19 | ModelMapper modelMapper = new ModelMapper(); 20 | modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE); 21 | return modelMapper; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/config/OpenApiConfig.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.config; 2 | 3 | import io.swagger.v3.oas.models.OpenAPI; 4 | import io.swagger.v3.oas.models.info.Info; 5 | import io.swagger.v3.oas.models.info.License; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | @Configuration 11 | public class OpenApiConfig { 12 | 13 | @Bean 14 | public OpenAPI customOpenAPI(@Value("${application-description}") String description, 15 | @Value("${application-version}") String version, 16 | @Value("${application-license}") String license) { 17 | return new OpenAPI() 18 | .info(new Info().title("Twitter Clone API") 19 | .description(description) 20 | .license(new License().name(license)) 21 | .version(version)); 22 | } 23 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.config; 2 | 3 | import com.safalifter.twitterclone.security.JWTAccessDeniedHandler; 4 | import com.safalifter.twitterclone.security.JwtAuthenticationEntryPoint; 5 | import com.safalifter.twitterclone.security.JwtFilter; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.lang.NonNull; 10 | import org.springframework.security.authentication.AuthenticationManager; 11 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 12 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; 16 | import org.springframework.security.config.http.SessionCreationPolicy; 17 | import org.springframework.security.web.SecurityFilterChain; 18 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 19 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 20 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 21 | 22 | @Configuration 23 | @EnableGlobalMethodSecurity(prePostEnabled = true) 24 | @EnableWebSecurity 25 | @RequiredArgsConstructor 26 | public class SecurityConfig { 27 | private final JwtFilter jwtFilter; 28 | private final JwtAuthenticationEntryPoint authenticationEntryPoint; 29 | private final JWTAccessDeniedHandler accessDeniedHandler; 30 | 31 | @Bean 32 | public AuthenticationManager authenticationManager(final AuthenticationConfiguration authenticationConfiguration) throws Exception { 33 | return authenticationConfiguration.getAuthenticationManager(); 34 | } 35 | 36 | @Bean 37 | public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { 38 | return http 39 | .headers().frameOptions().disable().and() 40 | .csrf().disable() 41 | .cors().and() 42 | .authorizeRequests(auth -> { 43 | auth.anyRequest().permitAll(); 44 | }) 45 | .formLogin().disable() 46 | .httpBasic().disable() 47 | .exceptionHandling().accessDeniedHandler(accessDeniedHandler) 48 | .authenticationEntryPoint(authenticationEntryPoint) 49 | .and() 50 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 51 | .and() 52 | .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class) 53 | .build(); 54 | } 55 | 56 | @Bean 57 | public WebSecurityCustomizer webSecurityCustomizer() { 58 | return (web) -> web.ignoring().antMatchers( 59 | "/v1/auth/**", 60 | "/swagger-resources/**", 61 | "/swagger-ui.html/**", 62 | "/swagger-resources/**", 63 | "/swagger-ui/**", 64 | "/v3/api-docs/**"); 65 | } 66 | 67 | @Bean 68 | public WebMvcConfigurer corsConfigurer() { 69 | return new WebMvcConfigurer() { 70 | @Override 71 | public void addCorsMappings(@NonNull CorsRegistry registry) { 72 | registry.addMapping("/**") 73 | .allowedMethods("*"); 74 | } 75 | }; 76 | } 77 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.controller; 2 | 3 | import com.safalifter.twitterclone.dto.TokenDTO; 4 | import com.safalifter.twitterclone.dto.UserDto; 5 | import com.safalifter.twitterclone.request.AuthRequest; 6 | import com.safalifter.twitterclone.request.RegisterRequest; 7 | import com.safalifter.twitterclone.service.AuthService; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestBody; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | import javax.validation.Valid; 16 | 17 | @RestController 18 | @RequestMapping("/v1/auth") 19 | @RequiredArgsConstructor 20 | public class AuthController { 21 | private final AuthService authService; 22 | 23 | @PostMapping("/login") 24 | ResponseEntity handleLogin(@RequestBody AuthRequest request) { 25 | return ResponseEntity.ok(authService.login(request)); 26 | } 27 | 28 | @PostMapping("/signup") 29 | ResponseEntity handleSignUp(@Valid @RequestBody RegisterRequest request) { 30 | return ResponseEntity.ok(authService.signup(request)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/controller/CommentController.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.controller; 2 | 3 | import com.safalifter.twitterclone.dto.CommentDto; 4 | import com.safalifter.twitterclone.request.CommentCreateRequest; 5 | import com.safalifter.twitterclone.request.UpdateCommentRequest; 6 | import com.safalifter.twitterclone.service.CommentService; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | @RestController 12 | @RequestMapping("/v1/comments") 13 | @RequiredArgsConstructor 14 | public class CommentController { 15 | private final CommentService commentService; 16 | 17 | @PostMapping 18 | ResponseEntity create(@RequestBody CommentCreateRequest request) { 19 | return ResponseEntity.status(201).body(commentService.create(request)); 20 | } 21 | 22 | @GetMapping("/{id}") 23 | ResponseEntity getCommentById(@PathVariable Long id) { 24 | return ResponseEntity.status(200).body(commentService.getCommentById(id)); 25 | } 26 | 27 | @PutMapping("/{id}") 28 | ResponseEntity updateCommentById(@PathVariable Long id, 29 | @RequestBody UpdateCommentRequest request) { 30 | return ResponseEntity.status(200).body(commentService.updateCommentById(id, request)); 31 | } 32 | 33 | @DeleteMapping("/{id}") 34 | public ResponseEntity deleteCommentById(@PathVariable Long id) { 35 | commentService.deleteCommentById(id); 36 | return ResponseEntity.ok().build(); 37 | } 38 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/controller/LikeController.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.controller; 2 | 3 | import com.safalifter.twitterclone.dto.LikeDto; 4 | import com.safalifter.twitterclone.request.LikeCreateRequest; 5 | import com.safalifter.twitterclone.service.LikeService; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | @RestController 11 | @RequestMapping("/v1/likes") 12 | @RequiredArgsConstructor 13 | public class LikeController { 14 | private final LikeService likeService; 15 | 16 | @PostMapping 17 | ResponseEntity create(@RequestBody LikeCreateRequest request) { 18 | return ResponseEntity.status(201).body(likeService.create(request)); 19 | } 20 | 21 | @DeleteMapping("/{id}") 22 | public ResponseEntity deleteLikeById(@PathVariable Long id) { 23 | likeService.deleteLikeById(id); 24 | return ResponseEntity.ok().build(); 25 | } 26 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/controller/RetweetController.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.controller; 2 | 3 | import com.safalifter.twitterclone.dto.RetweetDto; 4 | import com.safalifter.twitterclone.request.RetweetCreateRequest; 5 | import com.safalifter.twitterclone.request.UpdateRetweetRequest; 6 | import com.safalifter.twitterclone.service.RetweetService; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | @RestController 12 | @RequestMapping("/v1/retweets") 13 | @RequiredArgsConstructor 14 | public class RetweetController { 15 | private final RetweetService retweetService; 16 | 17 | @PostMapping 18 | ResponseEntity create(@RequestBody RetweetCreateRequest request) { 19 | return ResponseEntity.status(201).body(retweetService.create(request)); 20 | } 21 | 22 | @GetMapping("/{id}") 23 | ResponseEntity getRetweetById(@PathVariable Long id) { 24 | return ResponseEntity.status(200).body(retweetService.getRetweetById(id)); 25 | } 26 | 27 | @PutMapping("/{id}") 28 | ResponseEntity updateRetweetById(@PathVariable Long id, 29 | @RequestBody UpdateRetweetRequest request) { 30 | return ResponseEntity.status(200).body(retweetService.updateRetweetById(id, request)); 31 | } 32 | 33 | @DeleteMapping("/{id}") 34 | public ResponseEntity deleteRetweetById(@PathVariable Long id) { 35 | retweetService.deleteRetweetById(id); 36 | return ResponseEntity.ok().build(); 37 | } 38 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/controller/TweetController.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.controller; 2 | 3 | import com.safalifter.twitterclone.dto.CommentDto; 4 | import com.safalifter.twitterclone.dto.LikeDto; 5 | import com.safalifter.twitterclone.dto.RetweetDto; 6 | import com.safalifter.twitterclone.dto.TweetDto; 7 | import com.safalifter.twitterclone.request.TweetCreateRequest; 8 | import com.safalifter.twitterclone.request.UpdateTweetRequest; 9 | import com.safalifter.twitterclone.service.CommentService; 10 | import com.safalifter.twitterclone.service.LikeService; 11 | import com.safalifter.twitterclone.service.RetweetService; 12 | import com.safalifter.twitterclone.service.TweetService; 13 | import lombok.RequiredArgsConstructor; 14 | import org.springframework.data.domain.Page; 15 | import org.springframework.data.domain.Pageable; 16 | import org.springframework.data.domain.Sort; 17 | import org.springframework.data.web.PageableDefault; 18 | import org.springframework.http.ResponseEntity; 19 | import org.springframework.web.bind.annotation.*; 20 | 21 | @RestController 22 | @RequestMapping("/v1/tweets") 23 | @RequiredArgsConstructor 24 | public class TweetController { 25 | private final TweetService tweetService; 26 | private final LikeService likeService; 27 | private final RetweetService retweetService; 28 | private final CommentService commentService; 29 | 30 | @PostMapping 31 | ResponseEntity create(@RequestBody TweetCreateRequest request) { 32 | return ResponseEntity.status(201).body(tweetService.create(request)); 33 | } 34 | 35 | @GetMapping 36 | ResponseEntity> getTweets(@PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable page) { 37 | return ResponseEntity.status(200).body(tweetService.getTweets(page)); 38 | } 39 | 40 | @GetMapping("/{id}") 41 | ResponseEntity getTweetById(@PathVariable Long id) { 42 | return ResponseEntity.status(200).body(tweetService.getTweetById(id)); 43 | } 44 | 45 | @PutMapping("/{id}") 46 | ResponseEntity updateTweetById(@PathVariable Long id, 47 | @RequestBody UpdateTweetRequest request) { 48 | return ResponseEntity.status(200).body(tweetService.updateTweetById(id, request)); 49 | } 50 | 51 | @DeleteMapping("/{id}") 52 | public ResponseEntity deleteTweetById(@PathVariable Long id) { 53 | tweetService.deleteTweetById(id); 54 | return ResponseEntity.ok().build(); 55 | } 56 | 57 | @GetMapping("/{id}/likes") 58 | ResponseEntity> getTweetsLikesByTweetId(@PathVariable Long id, 59 | @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable page) { 60 | return ResponseEntity.status(200).body(likeService.getTweetsLikesByTweetId(id, page)); 61 | } 62 | 63 | @GetMapping("/{id}/comments") 64 | ResponseEntity> getTweetsCommentsByTweetId(@PathVariable Long id, 65 | @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable page) { 66 | return ResponseEntity.status(200).body(commentService.getTweetsCommentsByTweetId(id, page)); 67 | } 68 | 69 | @GetMapping("/{id}/retweets") 70 | ResponseEntity> getTweetsRetweetsByTweetId(@PathVariable Long id, 71 | @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable page) { 72 | return ResponseEntity.status(200).body(retweetService.getTweetsRetweetsByTweetId(id, page)); 73 | } 74 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.controller; 2 | 3 | import com.safalifter.twitterclone.dto.LikeDto; 4 | import com.safalifter.twitterclone.dto.TweetDto; 5 | import com.safalifter.twitterclone.dto.UserDto; 6 | import com.safalifter.twitterclone.request.UpdateUserRequest; 7 | import com.safalifter.twitterclone.service.FileService; 8 | import com.safalifter.twitterclone.service.LikeService; 9 | import com.safalifter.twitterclone.service.TweetService; 10 | import com.safalifter.twitterclone.service.UserService; 11 | import lombok.RequiredArgsConstructor; 12 | import org.springframework.data.domain.Page; 13 | import org.springframework.data.domain.Pageable; 14 | import org.springframework.data.domain.Sort; 15 | import org.springframework.data.web.PageableDefault; 16 | import org.springframework.http.MediaType; 17 | import org.springframework.http.ResponseEntity; 18 | import org.springframework.web.bind.annotation.*; 19 | import org.springframework.web.multipart.MultipartFile; 20 | 21 | import javax.validation.Valid; 22 | 23 | @RestController 24 | @RequestMapping("/v1/users") 25 | @RequiredArgsConstructor 26 | public class UserController { 27 | private final UserService userService; 28 | private final TweetService tweetService; 29 | private final LikeService likeService; 30 | private final FileService fileService; 31 | 32 | @GetMapping 33 | ResponseEntity> getUsers(@PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable page) { 34 | return ResponseEntity.status(200).body(userService.getUsers(page)); 35 | } 36 | 37 | @GetMapping("/{username}") 38 | ResponseEntity getUserByUsername(@PathVariable String username) { 39 | return ResponseEntity.status(200).body(userService.getUserByUsername(username)); 40 | } 41 | 42 | @PutMapping("/{id}") 43 | ResponseEntity updateUserById(@PathVariable Long id, 44 | @Valid @RequestBody UpdateUserRequest request) { 45 | return ResponseEntity.status(200).body(userService.updateUserById(id, request)); 46 | } 47 | 48 | @DeleteMapping("/{id}") 49 | public ResponseEntity deleteUserById(@PathVariable Long id) { 50 | userService.deleteUserById(id); 51 | return ResponseEntity.ok().build(); 52 | } 53 | 54 | @GetMapping("/{id}/tweets") 55 | ResponseEntity> getUsersTweetsByUserId(@PathVariable Long id, 56 | @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable page) { 57 | return ResponseEntity.status(200).body(tweetService.getUsersTweetsByUserId(id, page)); 58 | } 59 | 60 | @GetMapping("/{id}/likes") 61 | ResponseEntity> getUsersLikesByUserId(@PathVariable Long id, 62 | @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable page) { 63 | return ResponseEntity.status(200).body(likeService.getUsersLikesByUserId(id, page)); 64 | } 65 | 66 | @PostMapping( 67 | value = "/{username}/image/upload", 68 | consumes = MediaType.MULTIPART_FORM_DATA_VALUE, 69 | produces = MediaType.APPLICATION_JSON_VALUE) 70 | ResponseEntity uploadUserProfileImage(@PathVariable String username, 71 | @RequestParam("file") MultipartFile file) { 72 | fileService.uploadProfileImage(username, file); 73 | return ResponseEntity.ok().build(); 74 | } 75 | 76 | @GetMapping("/{username}/image/download") 77 | ResponseEntity downloadUserProfileImage(@PathVariable String username) { 78 | return ResponseEntity.ok(fileService.downloadProfileImage(username)); 79 | } 80 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/dto/CommentDto.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.dto; 2 | 3 | import lombok.Data; 4 | 5 | import java.time.LocalDateTime; 6 | import java.util.List; 7 | 8 | @Data 9 | public class CommentDto { 10 | private Long id; 11 | private String text; 12 | private Long userId; 13 | private Long tweetId; 14 | private String name; 15 | private String username; 16 | private LocalDateTime creationTimestamp; 17 | private List likes; 18 | private List retweets; 19 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/dto/LikeDto.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.dto; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class LikeDto { 7 | private long id; 8 | private long userId; 9 | private long tweetId; 10 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/dto/RetweetDto.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.dto; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class RetweetDto { 7 | private Long id; 8 | private String text; 9 | private Long userId; 10 | private Long tweetId; 11 | } 12 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/dto/TokenDTO.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.dto; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | @Data 7 | @Builder 8 | public class TokenDTO { 9 | private String accessToken; 10 | private long userId; 11 | private String username; 12 | } 13 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/dto/TweetDto.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.dto; 2 | 3 | import lombok.Data; 4 | 5 | import java.time.LocalDateTime; 6 | import java.util.List; 7 | 8 | @Data 9 | public class TweetDto { 10 | private Long id; 11 | private String text; 12 | private Long userId; 13 | private String name; 14 | private String username; 15 | private String userProfileImageLink; 16 | private LocalDateTime creationTimestamp; 17 | private List likes; 18 | private List comments; 19 | private List retweets; 20 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/dto/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.dto; 2 | 3 | import lombok.Data; 4 | 5 | import java.time.LocalDate; 6 | import java.time.LocalDateTime; 7 | import java.util.List; 8 | 9 | @Data 10 | public class UserDto { 11 | private long id; 12 | private String name; 13 | private String email; 14 | private String username; 15 | private LocalDate birthday; 16 | private String bio; 17 | private String location; 18 | private String webSite; 19 | private LocalDateTime creationTimestamp; 20 | private List tweets; 21 | private List likes; 22 | private String profileImageLink; 23 | } 24 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/exc/GeneralExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.exc; 2 | 3 | import org.springframework.http.HttpHeaders; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.validation.FieldError; 7 | import org.springframework.web.bind.MethodArgumentNotValidException; 8 | import org.springframework.web.bind.annotation.ExceptionHandler; 9 | import org.springframework.web.bind.annotation.RestControllerAdvice; 10 | import org.springframework.web.context.request.WebRequest; 11 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 12 | 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | @RestControllerAdvice 17 | public class GeneralExceptionHandler extends ResponseEntityExceptionHandler { 18 | 19 | @Override 20 | protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, 21 | HttpHeaders headers, HttpStatus status, WebRequest request) { 22 | Map errors = new HashMap<>(); 23 | ex.getBindingResult().getAllErrors() 24 | .forEach(x -> errors.put(((FieldError) x).getField(), x.getDefaultMessage())); 25 | return ResponseEntity.badRequest().body(errors); 26 | } 27 | 28 | @ExceptionHandler(NotFoundException.class) 29 | public ResponseEntity notFoundException(NotFoundException exception) { 30 | Map errors = new HashMap<>(); 31 | errors.put("error", exception.getMessage()); 32 | return new ResponseEntity<>(errors, HttpStatus.NOT_FOUND); 33 | } 34 | 35 | @ExceptionHandler(WrongCredentialsException.class) 36 | public ResponseEntity usernameOrPasswordInvalidException(WrongCredentialsException exception) { 37 | Map errors = new HashMap<>(); 38 | errors.put("error", exception.getMessage()); 39 | return new ResponseEntity<>(errors, HttpStatus.UNAUTHORIZED); 40 | } 41 | 42 | @ExceptionHandler(GenericErrorResponse.class) 43 | public ResponseEntity genericError(GenericErrorResponse exception) { 44 | Map errors = new HashMap<>(); 45 | errors.put("error", exception.getMessage()); 46 | return new ResponseEntity<>(errors, exception.getHttpStatus()); 47 | } 48 | 49 | @ExceptionHandler(Exception.class) 50 | public final ResponseEntity handleAllException(Exception ex, WebRequest request) { 51 | Map errors = new HashMap<>(); 52 | errors.put("error", ex.getMessage()); 53 | return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); 54 | } 55 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/exc/GenericErrorResponse.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.exc; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | import org.springframework.http.HttpStatus; 6 | 7 | @Builder 8 | @Getter 9 | public class GenericErrorResponse extends RuntimeException { 10 | private final String message; 11 | private final HttpStatus httpStatus; 12 | 13 | public GenericErrorResponse(String message, HttpStatus httpStatus) { 14 | super(message); 15 | this.message = message; 16 | this.httpStatus = httpStatus; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/exc/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.exc; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | @ResponseStatus(HttpStatus.NOT_FOUND) 7 | public class NotFoundException extends RuntimeException { 8 | public NotFoundException(String message) { 9 | super(message); 10 | } 11 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/exc/WrongCredentialsException.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.exc; 2 | 3 | 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.web.bind.annotation.ResponseStatus; 6 | 7 | @ResponseStatus(HttpStatus.UNAUTHORIZED) 8 | public class WrongCredentialsException extends RuntimeException { 9 | public WrongCredentialsException(String message) { 10 | super(message); 11 | } 12 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/model/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.experimental.SuperBuilder; 6 | import org.hibernate.annotations.CreationTimestamp; 7 | import org.hibernate.annotations.UpdateTimestamp; 8 | 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.GenerationType; 11 | import javax.persistence.Id; 12 | import javax.persistence.MappedSuperclass; 13 | import java.io.Serializable; 14 | import java.time.LocalDateTime; 15 | 16 | @MappedSuperclass 17 | @SuperBuilder 18 | @RequiredArgsConstructor 19 | @Getter 20 | public abstract class BaseEntity implements Serializable { 21 | @Id 22 | @GeneratedValue(strategy = GenerationType.IDENTITY) 23 | private Long id; 24 | 25 | @CreationTimestamp 26 | private LocalDateTime creationTimestamp; 27 | 28 | @UpdateTimestamp 29 | private LocalDateTime updateTimeStamp; 30 | } 31 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/model/Comment.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Setter; 6 | import lombok.experimental.SuperBuilder; 7 | 8 | import javax.persistence.*; 9 | import java.util.List; 10 | 11 | @Entity 12 | @SuperBuilder 13 | @RequiredArgsConstructor 14 | @Getter 15 | @Setter 16 | public class Comment extends BaseEntity { 17 | private String text; 18 | 19 | @ManyToOne(fetch = FetchType.LAZY) 20 | @JoinColumn(referencedColumnName = "id", nullable = false) 21 | private Tweet tweet; 22 | 23 | @ManyToOne(fetch = FetchType.LAZY) 24 | @JoinColumn(referencedColumnName = "id", nullable = false) 25 | private User user; 26 | 27 | @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) 28 | private List likes; 29 | 30 | @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) 31 | private List retweets; 32 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/model/Like.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Setter; 6 | import lombok.experimental.SuperBuilder; 7 | 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.JoinColumn; 11 | import javax.persistence.ManyToOne; 12 | 13 | @Entity(name = "likes") 14 | @SuperBuilder 15 | @RequiredArgsConstructor 16 | @Getter 17 | @Setter 18 | public class Like extends BaseEntity { 19 | @ManyToOne(fetch = FetchType.LAZY) 20 | @JoinColumn(referencedColumnName = "id", nullable = false) 21 | private User user; 22 | 23 | @ManyToOne(fetch = FetchType.LAZY) 24 | @JoinColumn(referencedColumnName = "id", nullable = false) 25 | private Tweet tweet; 26 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/model/Retweet.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Setter; 6 | import lombok.experimental.SuperBuilder; 7 | 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.JoinColumn; 11 | import javax.persistence.ManyToOne; 12 | 13 | @Entity 14 | @SuperBuilder 15 | @RequiredArgsConstructor 16 | @Getter 17 | @Setter 18 | public class Retweet extends BaseEntity { 19 | private String text; 20 | 21 | @ManyToOne(fetch = FetchType.LAZY) 22 | @JoinColumn(referencedColumnName = "id", nullable = false) 23 | private Tweet tweet; 24 | 25 | @ManyToOne(fetch = FetchType.LAZY) 26 | @JoinColumn(referencedColumnName = "id", nullable = false) 27 | private User user; 28 | } 29 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.model; 2 | 3 | public enum Role { 4 | ADMIN, USER 5 | } 6 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/model/Tweet.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Setter; 6 | import lombok.experimental.SuperBuilder; 7 | 8 | import javax.persistence.*; 9 | import java.util.List; 10 | 11 | @Entity 12 | @SuperBuilder 13 | @RequiredArgsConstructor 14 | @Getter 15 | @Setter 16 | public class Tweet extends BaseEntity { 17 | private String text; 18 | 19 | @ManyToOne 20 | @JoinColumn(referencedColumnName = "id", nullable = false) 21 | private User user; 22 | 23 | @OneToMany(mappedBy = "tweet", cascade = CascadeType.ALL, fetch = FetchType.LAZY) 24 | private List likes; 25 | 26 | @OneToMany(mappedBy = "tweet", cascade = CascadeType.ALL, fetch = FetchType.LAZY) 27 | private List comments; 28 | 29 | @OneToMany(mappedBy = "tweet", cascade = CascadeType.ALL, fetch = FetchType.LAZY) 30 | private List retweets; 31 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/model/User.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.model; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.Setter; 6 | import lombok.experimental.SuperBuilder; 7 | 8 | import javax.persistence.*; 9 | import java.time.LocalDate; 10 | import java.util.List; 11 | 12 | @Entity(name = "users") 13 | @SuperBuilder 14 | @RequiredArgsConstructor 15 | @Getter 16 | @Setter 17 | public class User extends BaseEntity { 18 | private String name; 19 | 20 | @Column(unique = true) 21 | private String email; 22 | // unique problem will resolve with auth 23 | @Column(unique = true) 24 | private String username; 25 | 26 | private String password; 27 | 28 | private LocalDate birthday; 29 | 30 | private String bio; 31 | 32 | private String location; 33 | 34 | private String webSite; 35 | 36 | private String profileImageLink; 37 | 38 | @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) 39 | private List tweets; 40 | 41 | @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) 42 | private List likes; 43 | 44 | @Enumerated(EnumType.STRING) 45 | private Role role; 46 | } 47 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/repository/CommentRepository.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.repository; 2 | 3 | import com.safalifter.twitterclone.model.Comment; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | 8 | public interface CommentRepository extends JpaRepository { 9 | Page findCommentsByTweet_Id(Long id, Pageable page); 10 | } 11 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/repository/LikeRepository.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.repository; 2 | 3 | import com.safalifter.twitterclone.model.Like; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | 8 | import java.util.Optional; 9 | 10 | public interface LikeRepository extends JpaRepository { 11 | Page findLikesByUser_Id(Long userId, Pageable page); 12 | 13 | Page findLikesByTweet_Id(Long tweetId, Pageable page); 14 | 15 | Optional findLikeByUser_IdAndTweet_Id(Long userId, Long tweetId); 16 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/repository/RetweetRepository.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.repository; 2 | 3 | import com.safalifter.twitterclone.model.Retweet; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | 8 | public interface RetweetRepository extends JpaRepository { 9 | Page findRetweetsByTweet_Id(Long id, Pageable page); 10 | } 11 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/repository/TweetRepository.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.repository; 2 | 3 | import com.safalifter.twitterclone.model.Tweet; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | 8 | public interface TweetRepository extends JpaRepository { 9 | Page findAllByUser_Id(Long id, Pageable page); 10 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.repository; 2 | 3 | import com.safalifter.twitterclone.model.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface UserRepository extends JpaRepository { 9 | Optional findByUsername(String username); 10 | } 11 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/AuthRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class AuthRequest { 7 | private String username; 8 | private String password; 9 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/CommentCreateRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class CommentCreateRequest { 7 | private String text; 8 | private Long userId; 9 | private Long tweetId; 10 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/LikeCreateRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class LikeCreateRequest { 7 | private long userId; 8 | private long tweetId; 9 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/RegisterRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | import javax.validation.constraints.Email; 6 | import javax.validation.constraints.NotBlank; 7 | import javax.validation.constraints.Pattern; 8 | import javax.validation.constraints.Size; 9 | import java.time.LocalDate; 10 | 11 | @Getter 12 | public class RegisterRequest { 13 | private String name; 14 | 15 | @NotBlank(message = "Username mustn't be blank") 16 | private String username; 17 | 18 | @NotBlank(message = "Email mustn't be blank") 19 | @Email 20 | private String email; 21 | 22 | @NotBlank(message = "Password mustn't be blank") 23 | @Size(min = 8, max = 16) 24 | @Pattern(message = "Password must have at least 1 uppercase 1 lowercase and 1 number", 25 | regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).*$") 26 | private String password; 27 | 28 | private LocalDate birthday; 29 | } 30 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/RetweetCreateRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class RetweetCreateRequest { 7 | private String text; 8 | private Long userId; 9 | private Long tweetId; 10 | } 11 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/TweetCreateRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class TweetCreateRequest { 7 | private String text; 8 | private Long userId; 9 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/UpdateCommentRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class UpdateCommentRequest { 7 | private String text; 8 | } 9 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/UpdateRetweetRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class UpdateRetweetRequest { 7 | private String text; 8 | } 9 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/UpdateTweetRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class UpdateTweetRequest { 7 | private String text; 8 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/request/UpdateUserRequest.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.request; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public class UpdateUserRequest { 7 | private String name; 8 | private String bio; 9 | private String location; 10 | private String webSite; 11 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/security/JWTAccessDeniedHandler.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.security; 2 | 3 | import org.springframework.security.access.AccessDeniedException; 4 | import org.springframework.security.web.access.AccessDeniedHandler; 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 JWTAccessDeniedHandler implements AccessDeniedHandler { 13 | @Override 14 | public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { 15 | response.setContentType("application/json"); 16 | response.setStatus(HttpServletResponse.SC_FORBIDDEN); 17 | response.getOutputStream().println("{ \"error\": \"" + accessDeniedException.getMessage() + "\" }"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/security/JwtAuthenticationEntryPoint.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.security; 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 JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { 13 | @Override 14 | public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { 15 | response.setContentType("application/json"); 16 | response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 17 | response.getOutputStream().println("{ \"error\": \"" + authException.getMessage() + "\" }"); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/security/JwtFilter.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.security; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.safalifter.twitterclone.service.TokenService; 5 | import com.safalifter.twitterclone.service.UserDetailsServiceImpl; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.http.HttpHeaders; 8 | import org.springframework.lang.NonNull; 9 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.core.userdetails.UserDetails; 12 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 13 | import org.springframework.stereotype.Component; 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 | import java.io.PrintWriter; 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | @Component 26 | @RequiredArgsConstructor 27 | public class JwtFilter extends OncePerRequestFilter { 28 | private final TokenService tokenService; 29 | private final UserDetailsServiceImpl userDetailsService; 30 | 31 | @Override 32 | protected void doFilterInternal(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { 33 | 34 | String header = request.getHeader(HttpHeaders.AUTHORIZATION); 35 | if (header == null || !header.startsWith("Bearer ")) { 36 | filterChain.doFilter(request, response); 37 | return; 38 | } 39 | String token = header.substring(7); 40 | String username; 41 | try { 42 | username = tokenService.verifyJWT(token).getSubject(); 43 | } catch (Exception e) { 44 | sendError(response, e); 45 | return; 46 | } 47 | if (username == null) { 48 | filterChain.doFilter(request, response); 49 | return; 50 | } 51 | UserDetails userDetails = userDetailsService.loadUserByUsername(username); 52 | UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); 53 | authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 54 | SecurityContextHolder.getContext().setAuthentication(authenticationToken); 55 | filterChain.doFilter(request, response); 56 | } 57 | 58 | private void sendError(HttpServletResponse res, Exception e) throws IOException { 59 | res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); 60 | res.setContentType("application/json"); 61 | PrintWriter out = res.getWriter(); 62 | Map errors = new HashMap<>(); 63 | ObjectMapper mapper = new ObjectMapper(); 64 | errors.put("error", e.getMessage()); 65 | out.println(mapper.writeValueAsString(errors)); 66 | out.flush(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/AuthService.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.safalifter.twitterclone.dto.TokenDTO; 4 | import com.safalifter.twitterclone.dto.UserDto; 5 | import com.safalifter.twitterclone.exc.WrongCredentialsException; 6 | import com.safalifter.twitterclone.request.AuthRequest; 7 | import com.safalifter.twitterclone.request.RegisterRequest; 8 | import lombok.RequiredArgsConstructor; 9 | import org.modelmapper.ModelMapper; 10 | import org.springframework.security.authentication.AuthenticationManager; 11 | import org.springframework.security.authentication.BadCredentialsException; 12 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 | import org.springframework.security.core.Authentication; 14 | import org.springframework.stereotype.Service; 15 | 16 | @Service 17 | @RequiredArgsConstructor 18 | public class AuthService { 19 | private final AuthenticationManager authenticationManager; 20 | private final UserService userService; 21 | private final TokenService tokenService; 22 | private final ModelMapper modelMapper; 23 | 24 | public TokenDTO login(AuthRequest request) { 25 | try { 26 | Authentication auth = authenticationManager 27 | .authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())); 28 | return TokenDTO 29 | .builder() 30 | .accessToken(tokenService.generateToken(auth)) 31 | .userId(userService.findUserByUsername(request.getUsername()).getId()) 32 | .username(request.getUsername()) 33 | .build(); 34 | } catch (final BadCredentialsException badCredentialsException) { 35 | throw new WrongCredentialsException("Invalid Username or Password"); 36 | } 37 | } 38 | 39 | public UserDto signup(RegisterRequest request) { 40 | return modelMapper.map(userService.create(request), UserDto.class); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/CommentService.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.safalifter.twitterclone.dto.CommentDto; 4 | import com.safalifter.twitterclone.exc.NotFoundException; 5 | import com.safalifter.twitterclone.model.Comment; 6 | import com.safalifter.twitterclone.model.Tweet; 7 | import com.safalifter.twitterclone.model.User; 8 | import com.safalifter.twitterclone.repository.CommentRepository; 9 | import com.safalifter.twitterclone.request.CommentCreateRequest; 10 | import com.safalifter.twitterclone.request.UpdateCommentRequest; 11 | import lombok.RequiredArgsConstructor; 12 | import org.modelmapper.ModelMapper; 13 | import org.springframework.data.domain.Page; 14 | import org.springframework.data.domain.Pageable; 15 | import org.springframework.stereotype.Service; 16 | 17 | @Service 18 | @RequiredArgsConstructor 19 | public class CommentService { 20 | private final CommentRepository commentRepository; 21 | private final UserService userService; 22 | private final TweetService tweetService; 23 | private final ModelMapper modelMapper; 24 | 25 | public CommentDto create(CommentCreateRequest request) { 26 | User user = userService.findUserById(request.getUserId()); 27 | Tweet tweet = tweetService.findTweetById(request.getTweetId()); 28 | Comment comment = Comment.builder() 29 | .text(request.getText()) 30 | .user(user) 31 | .tweet(tweet).build(); 32 | return modelMapper.map(commentRepository.save(comment), CommentDto.class); 33 | } 34 | 35 | public CommentDto getCommentById(Long id) { 36 | return modelMapper.map(findCommentById(id), CommentDto.class); 37 | } 38 | 39 | public CommentDto updateCommentById(Long id, UpdateCommentRequest request) { 40 | Comment inDB = findCommentById(id); 41 | inDB.setText(request.getText()); 42 | return modelMapper.map(commentRepository.save(inDB), CommentDto.class); 43 | } 44 | 45 | public void deleteCommentById(Long id) { 46 | Comment inDB = findCommentById(id); 47 | commentRepository.delete(inDB); 48 | } 49 | 50 | protected Comment findCommentById(Long id) { 51 | return commentRepository.findById(id) 52 | .orElseThrow(() -> new NotFoundException("Comment not found!")); 53 | } 54 | 55 | public Page getTweetsCommentsByTweetId(Long id, Pageable page) { 56 | Tweet inDB = tweetService.findTweetById(id); 57 | return commentRepository.findCommentsByTweet_Id(inDB.getId(), page) 58 | .map(x -> modelMapper.map(x, CommentDto.class)); 59 | } 60 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/FileService.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.safalifter.twitterclone.bucket.BucketName; 4 | import com.safalifter.twitterclone.model.User; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.web.multipart.MultipartFile; 8 | 9 | import java.io.IOException; 10 | import java.util.*; 11 | 12 | import static org.apache.http.entity.ContentType.*; 13 | 14 | @Service 15 | @RequiredArgsConstructor 16 | public class FileService { 17 | private final UserService userService; 18 | private final S3Service s3Service; 19 | 20 | public void uploadProfileImage(String username, MultipartFile file) { 21 | if (file.isEmpty()) 22 | throw new IllegalStateException("Cannot upload empty file"); 23 | if (!Arrays.asList(IMAGE_JPEG.getMimeType(), IMAGE_PNG.getMimeType(), IMAGE_GIF.getMimeType()) 24 | .contains(file.getContentType())) 25 | throw new IllegalStateException("File must be an image [" + file.getContentType() + "]"); 26 | 27 | User inDB = userService.findUserByUsername(username); 28 | 29 | Map metaData = new HashMap<>(); 30 | metaData.put("Content-Type", file.getContentType()); 31 | metaData.put("Content-Length", String.valueOf(file.getSize())); 32 | 33 | String path = String.format("%s/%s", BucketName.PROFILE_IMAGE.getBucketName(), inDB.getUsername()); 34 | String fileName = String.format("%s-%s", file.getOriginalFilename(), UUID.randomUUID()); 35 | try { 36 | s3Service.save(path, fileName, file.getInputStream(), Optional.of(metaData)); 37 | userService.updateUserProfileImage(fileName, username); 38 | } catch (IOException e) { 39 | throw new IllegalStateException(e); 40 | } 41 | } 42 | 43 | public byte[] downloadProfileImage(String username) { 44 | User inDB = userService.findUserByUsername(username); 45 | String path = String.format("%s/%s", 46 | BucketName.PROFILE_IMAGE.getBucketName(), 47 | inDB.getUsername()); 48 | return Optional.ofNullable(inDB.getProfileImageLink()) 49 | .map(key -> s3Service.download(path, key)) 50 | .orElse(new byte[0]); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/LikeService.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.safalifter.twitterclone.dto.LikeDto; 4 | import com.safalifter.twitterclone.exc.NotFoundException; 5 | import com.safalifter.twitterclone.model.Like; 6 | import com.safalifter.twitterclone.model.Tweet; 7 | import com.safalifter.twitterclone.model.User; 8 | import com.safalifter.twitterclone.repository.LikeRepository; 9 | import com.safalifter.twitterclone.request.LikeCreateRequest; 10 | import lombok.RequiredArgsConstructor; 11 | import org.modelmapper.ModelMapper; 12 | import org.springframework.data.domain.Page; 13 | import org.springframework.data.domain.Pageable; 14 | import org.springframework.stereotype.Service; 15 | 16 | @Service 17 | @RequiredArgsConstructor 18 | public class LikeService { 19 | private final LikeRepository likeRepository; 20 | private final UserService userService; 21 | private final TweetService tweetService; 22 | private final ModelMapper modelMapper; 23 | 24 | // return null to disallow the creation of multiple likes 25 | public LikeDto create(LikeCreateRequest request) { 26 | User user = userService.findUserById(request.getUserId()); 27 | Tweet tweet = tweetService.findTweetById(request.getTweetId()); 28 | Like like = Like.builder() 29 | .tweet(tweet) 30 | .user(user).build(); 31 | if (!checkUserLikedForThisTweet(request.getUserId(), request.getTweetId())) 32 | return modelMapper.map(likeRepository.save(like), LikeDto.class); 33 | return null; 34 | } 35 | 36 | public void deleteLikeById(Long id) { 37 | Like toBeDeletedLike = findLikeById(id); 38 | likeRepository.delete(toBeDeletedLike); 39 | } 40 | 41 | protected Like findLikeById(Long id) { 42 | return likeRepository.findById(id) 43 | .orElseThrow(() -> new NotFoundException("Like not found")); 44 | } 45 | 46 | protected boolean checkUserLikedForThisTweet(Long userId, Long tweetId) { 47 | return likeRepository.findLikeByUser_IdAndTweet_Id(userId, tweetId).isPresent(); 48 | } 49 | 50 | public Page getTweetsLikesByTweetId(Long id, Pageable page) { 51 | Tweet inDB = tweetService.findTweetById(id); 52 | return likeRepository.findLikesByTweet_Id(inDB.getId(), page) 53 | .map(x -> modelMapper.map(x, LikeDto.class)); 54 | } 55 | 56 | public Page getUsersLikesByUserId(Long id, Pageable page) { 57 | User inDB = userService.findUserById(id); 58 | return likeRepository.findLikesByUser_Id(inDB.getId(), page) 59 | .map(x -> modelMapper.map(x, LikeDto.class)); 60 | } 61 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/RetweetService.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.safalifter.twitterclone.dto.RetweetDto; 4 | import com.safalifter.twitterclone.exc.NotFoundException; 5 | import com.safalifter.twitterclone.model.Retweet; 6 | import com.safalifter.twitterclone.model.Tweet; 7 | import com.safalifter.twitterclone.model.User; 8 | import com.safalifter.twitterclone.repository.RetweetRepository; 9 | import com.safalifter.twitterclone.request.RetweetCreateRequest; 10 | import com.safalifter.twitterclone.request.UpdateRetweetRequest; 11 | import lombok.RequiredArgsConstructor; 12 | import org.modelmapper.ModelMapper; 13 | import org.springframework.data.domain.Page; 14 | import org.springframework.data.domain.Pageable; 15 | import org.springframework.stereotype.Service; 16 | 17 | @Service 18 | @RequiredArgsConstructor 19 | public class RetweetService { 20 | private final RetweetRepository retweetRepository; 21 | private final UserService userService; 22 | private final TweetService tweetService; 23 | private final ModelMapper modelMapper; 24 | 25 | public RetweetDto create(RetweetCreateRequest request) { 26 | User user = userService.findUserById(request.getUserId()); 27 | Tweet tweet = tweetService.findTweetById(request.getTweetId()); 28 | Retweet retweet = Retweet.builder() 29 | .text(request.getText()) 30 | .user(user) 31 | .tweet(tweet).build(); 32 | return modelMapper.map(retweetRepository.save(retweet), RetweetDto.class); 33 | } 34 | 35 | public RetweetDto getRetweetById(Long id) { 36 | return modelMapper.map(findRetweetById(id), RetweetDto.class); 37 | } 38 | 39 | public RetweetDto updateRetweetById(Long id, UpdateRetweetRequest request) { 40 | Retweet inDB = findRetweetById(id); 41 | inDB.setText(request.getText()); 42 | return modelMapper.map(retweetRepository.save(inDB), RetweetDto.class); 43 | } 44 | 45 | public void deleteRetweetById(Long id) { 46 | Retweet inDB = findRetweetById(id); 47 | retweetRepository.delete(inDB); 48 | } 49 | 50 | protected Retweet findRetweetById(Long id) { 51 | return retweetRepository.findById(id) 52 | .orElseThrow(() -> new NotFoundException("Retweet not found!")); 53 | } 54 | 55 | public Page getTweetsRetweetsByTweetId(Long id, Pageable page) { 56 | Tweet inDB = tweetService.findTweetById(id); 57 | return retweetRepository.findRetweetsByTweet_Id(inDB.getId(), page) 58 | .map(x -> modelMapper.map(x, RetweetDto.class)); 59 | } 60 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/S3Service.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.amazonaws.AmazonServiceException; 4 | import com.amazonaws.services.s3.AmazonS3; 5 | import com.amazonaws.services.s3.model.ObjectMetadata; 6 | import com.amazonaws.services.s3.model.S3Object; 7 | import com.amazonaws.services.s3.model.S3ObjectInputStream; 8 | import com.amazonaws.util.IOUtils; 9 | import lombok.RequiredArgsConstructor; 10 | import org.springframework.stereotype.Service; 11 | 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.util.Map; 15 | import java.util.Optional; 16 | 17 | @Service 18 | @RequiredArgsConstructor 19 | public class S3Service { 20 | private final AmazonS3 s3; 21 | 22 | public void save(String path, 23 | String fileName, 24 | InputStream inputStream, 25 | Optional> optionalMetaData) { 26 | 27 | ObjectMetadata objectMetadata = new ObjectMetadata(); 28 | optionalMetaData.ifPresent((map) -> { 29 | if (!map.isEmpty()) { 30 | map.forEach(objectMetadata::addUserMetadata); 31 | } 32 | }); 33 | 34 | try { 35 | s3.putObject(path, fileName, inputStream, objectMetadata); 36 | } catch (AmazonServiceException e) { 37 | throw new IllegalStateException("Failed to store file to s3", e); 38 | } 39 | } 40 | 41 | public byte[] download(String path, String key) { 42 | try { 43 | S3Object object = s3.getObject(path, key); 44 | S3ObjectInputStream inputStream = object.getObjectContent(); 45 | return IOUtils.toByteArray(inputStream); 46 | } catch (AmazonServiceException | IOException e) { 47 | throw new IllegalStateException("Failed to download file to s3", e); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/TokenService.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.auth0.jwt.JWT; 4 | import com.auth0.jwt.JWTVerifier; 5 | import com.auth0.jwt.algorithms.Algorithm; 6 | import com.auth0.jwt.interfaces.DecodedJWT; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.security.core.Authentication; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.stereotype.Service; 11 | 12 | import java.nio.charset.StandardCharsets; 13 | import java.util.Date; 14 | 15 | @Service 16 | public class TokenService { 17 | @Value("${jwt-variables.KEY}") 18 | private String KEY; 19 | 20 | @Value("${jwt-variables.ISSUER}") 21 | private String ISSUER; 22 | 23 | @Value("${jwt-variables.EXPIRES_ACCESS_TOKEN_MINUTE}") 24 | private Integer EXPIRES_ACCESS_TOKEN_MINUTE; 25 | 26 | public String generateToken(Authentication auth) { 27 | String username = ((UserDetails) auth.getPrincipal()).getUsername(); 28 | return JWT.create() 29 | .withSubject(username) 30 | .withExpiresAt(new Date(System.currentTimeMillis() + (EXPIRES_ACCESS_TOKEN_MINUTE * 60 * 1000))) 31 | .withIssuer(ISSUER) 32 | .sign(Algorithm.HMAC256(KEY.getBytes())); 33 | } 34 | 35 | public DecodedJWT verifyJWT(String token) { 36 | Algorithm algorithm = Algorithm.HMAC256(KEY.getBytes(StandardCharsets.UTF_8)); 37 | JWTVerifier verifier = JWT.require(algorithm).acceptExpiresAt(EXPIRES_ACCESS_TOKEN_MINUTE * 60).build(); 38 | try { 39 | return verifier.verify(token); 40 | } catch (Exception e) { 41 | throw new RuntimeException(e.getMessage().toString()); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/TweetService.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.safalifter.twitterclone.dto.TweetDto; 4 | import com.safalifter.twitterclone.exc.NotFoundException; 5 | import com.safalifter.twitterclone.model.Tweet; 6 | import com.safalifter.twitterclone.model.User; 7 | import com.safalifter.twitterclone.repository.TweetRepository; 8 | import com.safalifter.twitterclone.request.TweetCreateRequest; 9 | import com.safalifter.twitterclone.request.UpdateTweetRequest; 10 | import lombok.RequiredArgsConstructor; 11 | import org.modelmapper.ModelMapper; 12 | import org.springframework.data.domain.Page; 13 | import org.springframework.data.domain.Pageable; 14 | import org.springframework.stereotype.Service; 15 | 16 | @Service 17 | @RequiredArgsConstructor 18 | public class TweetService { 19 | private final TweetRepository tweetRepository; 20 | private final UserService userService; 21 | private final ModelMapper modelMapper; 22 | 23 | public TweetDto create(TweetCreateRequest request) { 24 | User inDB = userService.findUserById(request.getUserId()); 25 | Tweet tweet = Tweet.builder() 26 | .text(request.getText()) 27 | .user(inDB).build(); 28 | return modelMapper.map(tweetRepository.save(tweet), TweetDto.class); 29 | } 30 | 31 | public Page getTweets(Pageable page) { 32 | return tweetRepository.findAll(page).map(x -> modelMapper.map(x, TweetDto.class)); 33 | } 34 | 35 | public TweetDto getTweetById(Long id) { 36 | return modelMapper.map(findTweetById(id), TweetDto.class); 37 | } 38 | 39 | public TweetDto updateTweetById(Long id, UpdateTweetRequest request) { 40 | Tweet inDB = findTweetById(id); 41 | inDB.setText(request.getText()); 42 | return modelMapper.map(tweetRepository.save(inDB), TweetDto.class); 43 | } 44 | 45 | public void deleteTweetById(Long id) { 46 | Tweet inDB = findTweetById(id); 47 | tweetRepository.delete(inDB); 48 | } 49 | 50 | protected Tweet findTweetById(Long id) { 51 | return tweetRepository.findById(id) 52 | .orElseThrow(() -> new NotFoundException("Tweet not found!")); 53 | } 54 | 55 | public Page getUsersTweetsByUserId(Long id, Pageable page) { 56 | User inDB = userService.findUserById(id); 57 | return tweetRepository.findAllByUser_Id(inDB.getId(), page) 58 | .map(x -> modelMapper.map(x, TweetDto.class)); 59 | } 60 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.safalifter.twitterclone.model.User; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.stream.Collectors; 12 | import java.util.stream.Stream; 13 | 14 | @Service 15 | @RequiredArgsConstructor 16 | public class UserDetailsServiceImpl implements UserDetailsService { 17 | private final UserService userService; 18 | 19 | @Override 20 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 21 | User user = userService.findUserByUsername(username); 22 | var roles = Stream.of(user.getRole()) 23 | .map(x -> new SimpleGrantedAuthority(x.name())) 24 | .collect(Collectors.toList()); 25 | return new org.springframework.security.core.userdetails.User(username, user.getPassword(), roles); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/java/com/safalifter/twitterclone/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone.service; 2 | 3 | import com.safalifter.twitterclone.dto.UserDto; 4 | import com.safalifter.twitterclone.exc.NotFoundException; 5 | import com.safalifter.twitterclone.model.Role; 6 | import com.safalifter.twitterclone.model.User; 7 | import com.safalifter.twitterclone.repository.UserRepository; 8 | import com.safalifter.twitterclone.request.RegisterRequest; 9 | import com.safalifter.twitterclone.request.UpdateUserRequest; 10 | import lombok.RequiredArgsConstructor; 11 | import org.modelmapper.ModelMapper; 12 | import org.springframework.data.domain.Page; 13 | import org.springframework.data.domain.Pageable; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | import org.springframework.stereotype.Service; 16 | 17 | import java.util.Optional; 18 | 19 | @Service 20 | @RequiredArgsConstructor 21 | public class UserService { 22 | private final UserRepository userRepository; 23 | private final ModelMapper modelMapper; 24 | private final PasswordEncoder passwordEncoder; 25 | 26 | public UserDto create(RegisterRequest request) { 27 | User user = User.builder() 28 | .name(request.getName()) 29 | .email(request.getEmail()) 30 | .username(request.getUsername()) 31 | .password(passwordEncoder.encode(request.getPassword())) 32 | .birthday(request.getBirthday()) 33 | .role(Role.USER).build(); 34 | return modelMapper.map(userRepository.save(user), UserDto.class); 35 | } 36 | 37 | public Page getUsers(Pageable page) { 38 | return userRepository.findAll(page) 39 | .map(x -> modelMapper.map(x, UserDto.class)); 40 | } 41 | 42 | public UserDto getUserById(Long id) { // will be used 43 | User inDB = findUserById(id); 44 | return modelMapper.map(inDB, UserDto.class); 45 | } 46 | 47 | public UserDto getUserByUsername(String username) { 48 | return modelMapper.map(findUserByUsername(username), UserDto.class); 49 | } 50 | 51 | public UserDto updateUserById(Long id, UpdateUserRequest request) { // password and username will be added 52 | User inDB = findUserById(id); 53 | inDB.setName(Optional.ofNullable(request.getName()).orElse(inDB.getName())); 54 | inDB.setBio(Optional.ofNullable(request.getBio()).orElse(inDB.getBio())); 55 | inDB.setLocation(Optional.ofNullable(request.getLocation()).orElse(inDB.getLocation())); 56 | inDB.setWebSite(Optional.ofNullable(request.getWebSite()).orElse(inDB.getWebSite())); 57 | return modelMapper.map(userRepository.save(inDB), UserDto.class); 58 | } 59 | 60 | public void deleteUserById(Long id) { 61 | User inDB = findUserById(id); 62 | userRepository.delete(inDB); 63 | } 64 | 65 | public void updateUserProfileImage(String file, String username) { 66 | User inDB = findUserByUsername(username); 67 | inDB.setProfileImageLink(file); 68 | userRepository.save(inDB); 69 | } 70 | 71 | protected User findUserById(Long id) { 72 | return userRepository.findById(id).orElseThrow(() -> new NotFoundException("User not found!")); 73 | } 74 | 75 | protected User findUserByUsername(String username) { 76 | return userRepository.findByUsername(username).orElseThrow(() -> new NotFoundException("User not found!")); 77 | } 78 | } -------------------------------------------------------------------------------- /backend/twitter-clone/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | spring.jpa.hibernate.ddl-auto=create 3 | spring.jpa.database=postgresql 4 | spring.datasource.url=jdbc:postgresql://localhost:5432/twitter 5 | spring.datasource.username=postgres 6 | spring.datasource.password=55 7 | 8 | springdoc.swagger-ui.path=/swagger-ui.html 9 | application-description=Twitter Clone Application 10 | application-license=Twitter API Licence 11 | application-version=1.0 12 | 13 | jwt-variables.KEY=twitter 14 | jwt-variables.EXPIRES_ACCESS_TOKEN_MINUTE=200000 15 | jwt-variables.ISSUER=safalifter 16 | 17 | spring.servlet.multipart.max-file-size= 10MB -------------------------------------------------------------------------------- /backend/twitter-clone/src/test/java/com/safalifter/twitterclone/TwitterCloneApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.safalifter.twitterclone; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class TwitterCloneApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /frontend/twitter-clone/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* -------------------------------------------------------------------------------- /frontend/twitter-clone/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 35 | 36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. 39 | 40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /frontend/twitter-clone/craco.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | style: { 3 | postcss: { 4 | plugins: [require("tailwindcss"), require("autoprefixer")], 5 | }, 6 | }, 7 | }; 8 | -------------------------------------------------------------------------------- /frontend/twitter-clone/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "twitter-clone", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@craco/craco": "^6.1.2", 7 | "@emotion/react": "^11.10.5", 8 | "@emotion/styled": "^11.10.5", 9 | "@mui/icons-material": "^5.11.0", 10 | "@mui/material": "^5.11.6", 11 | "@reduxjs/toolkit": "^1.9.1", 12 | "@testing-library/jest-dom": "^5.12.0", 13 | "@testing-library/react": "^11.2.6", 14 | "@testing-library/user-event": "^12.8.3", 15 | "axios": "^1.2.4", 16 | "react": "^17.0.2", 17 | "react-dom": "^17.0.2", 18 | "react-dropzone": "^14.2.3", 19 | "react-redux": "^8.0.5", 20 | "react-router-dom": "^6.8.0", 21 | "react-scripts": "4.0.3", 22 | "react-twitter-widgets": "^1.10.0", 23 | "web-vitals": "^1.1.1" 24 | }, 25 | "scripts": { 26 | "start": "craco start", 27 | "build": "craco build", 28 | "test": "craco test", 29 | "eject": "react-scripts eject" 30 | }, 31 | "eslintConfig": { 32 | "extends": [ 33 | "react-app", 34 | "react-app/jest" 35 | ] 36 | }, 37 | "browserslist": { 38 | "production": [ 39 | ">0.2%", 40 | "not dead", 41 | "not op_mini all" 42 | ], 43 | "development": [ 44 | "last 1 chrome version", 45 | "last 1 firefox version", 46 | "last 1 safari version" 47 | ] 48 | }, 49 | "devDependencies": { 50 | "autoprefixer": "^9.8.6", 51 | "postcss": "^7.0.35", 52 | "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.1.2" 53 | }, 54 | "proxy": "http://localhost:8080/v1" 55 | } 56 | -------------------------------------------------------------------------------- /frontend/twitter-clone/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devxsb/twitter-clone-spring-react/8eec3bb819b2fb42f7ca476d82dfe37d54022b42/frontend/twitter-clone/public/favicon.ico -------------------------------------------------------------------------------- /frontend/twitter-clone/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /frontend/twitter-clone/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devxsb/twitter-clone-spring-react/8eec3bb819b2fb42f7ca476d82dfe37d54022b42/frontend/twitter-clone/public/logo192.png -------------------------------------------------------------------------------- /frontend/twitter-clone/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devxsb/twitter-clone-spring-react/8eec3bb819b2fb42f7ca476d82dfe37d54022b42/frontend/twitter-clone/public/logo512.png -------------------------------------------------------------------------------- /frontend/twitter-clone/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /frontend/twitter-clone/src/App.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import {useSelector} from "react-redux"; 3 | import Home from "./pages/Home"; 4 | import {Route, Routes} from "react-router-dom"; 5 | import Login from "./layout/Login"; 6 | import Signup from "./layout/Signup"; 7 | import Tweet from "./pages/Tweet"; 8 | import Container from "./layout/Container"; 9 | import Sidebar from "./layout/Sidebar"; 10 | import Content from "./layout/Content"; 11 | import Widgets from "./layout/Widgets"; 12 | import User from "./pages/User"; 13 | 14 | const App = () => { 15 | const currentUser = useSelector(state => state.reduxSlice.currentUser) 16 | return ( 17 | <> 18 | {currentUser ? 19 | 20 | 21 | 22 | }/> 23 | }/> 24 | }/> 25 | 26 | 27 | : 28 | 29 | }/> 30 | }/> 31 | }/> 32 | 33 | } 34 | 35 | ); 36 | }; 37 | 38 | export default App; 39 | -------------------------------------------------------------------------------- /frontend/twitter-clone/src/components/Box.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import {EmojiIcon, GIFIcon, ImageIcon, PollIcon, ScheduleIcon} from "../icons/Icon"; 3 | 4 | const Box = ({content, setContentFunc, sendFunc, submit, placeHolder}) => { 5 | return ( 6 |
7 |