diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/Instagram-Server-Clone.iml b/.idea/Instagram-Server-Clone.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/Instagram-Server-Clone.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..639900d --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..56b0f6b --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/server/build.gradle b/server/build.gradle new file mode 100644 index 0000000..8e6e05e --- /dev/null +++ b/server/build.gradle @@ -0,0 +1,32 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.1' + id 'io.spring.dependency-management' version '1.1.5' +} + +group = 'instagram' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.projectlombok:lombok:1.18.28' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-security' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/server/gradle/wrapper/gradle-wrapper.jar b/server/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/server/gradle/wrapper/gradle-wrapper.jar differ diff --git a/server/gradle/wrapper/gradle-wrapper.properties b/server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a441313 --- /dev/null +++ b/server/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/server/gradlew b/server/gradlew new file mode 100644 index 0000000..b740cf1 --- /dev/null +++ b/server/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/server/gradlew.bat b/server/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/server/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/server/settings.gradle b/server/settings.gradle new file mode 100644 index 0000000..096502d --- /dev/null +++ b/server/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'server' diff --git a/server/src/main/java/instagram/server/ServerApplication.java b/server/src/main/java/instagram/server/ServerApplication.java new file mode 100644 index 0000000..71c9137 --- /dev/null +++ b/server/src/main/java/instagram/server/ServerApplication.java @@ -0,0 +1,13 @@ +package instagram.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ServerApplication.class, args); + } + +} diff --git a/server/src/main/java/instagram/server/comment/controller/CommentController.java b/server/src/main/java/instagram/server/comment/controller/CommentController.java new file mode 100644 index 0000000..f4a153d --- /dev/null +++ b/server/src/main/java/instagram/server/comment/controller/CommentController.java @@ -0,0 +1,47 @@ +package instagram.server.comment.controller; + +import instagram.server.comment.controller.dto.request.RegisterCommentRequest; +import instagram.server.comment.controller.dto.request.UpdateCommentRequest; +import instagram.server.comment.entity.Comment; +import instagram.server.comment.service.CommentService; +import instagram.server.user.User; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RequiredArgsConstructor +@RestController +public class CommentController { + + private final CommentService commentService; + + @PostMapping("/api/comments") + public ResponseEntity registerComment(@RequestBody RegisterCommentRequest request, @LoginUser User user) { + Comment savedComment = commentService.save(request, user.getId()); + + return ResponseEntity.status(HttpStatus.CREATED) + .body(savedComment); + } + + @GetMapping("/api/comments/{commentId}") + public void findComment(@PathVariable long commentId) { + Comment comment = commentService.findComment(commentId); + + } + + @PutMapping("/api/comments/{commentId}") + public ResponseEntity updateComment(@PathVariable long id, @RequestBody UpdateCommentRequest request) { + Comment updatedComment = commentService.update(id, request); + + return ResponseEntity.ok() + .body(updatedComment); + } +} diff --git a/server/src/main/java/instagram/server/comment/controller/dto/request/RegisterCommentRequest.java b/server/src/main/java/instagram/server/comment/controller/dto/request/RegisterCommentRequest.java new file mode 100644 index 0000000..76da085 --- /dev/null +++ b/server/src/main/java/instagram/server/comment/controller/dto/request/RegisterCommentRequest.java @@ -0,0 +1,20 @@ +package instagram.server.comment.controller.dto.request; + + +import instagram.server.comment.entity.Comment; +import instagram.server.user.User; +import lombok.Getter; + +@Getter +public class RegisterCommentRequest { + + private User user; + private String content; + + public Comment toEntity(User user) { + return comment.builder() + .user(user) + .content(content) + .build(); + } +} diff --git a/server/src/main/java/instagram/server/comment/controller/dto/request/UpdateCommentRequest.java b/server/src/main/java/instagram/server/comment/controller/dto/request/UpdateCommentRequest.java new file mode 100644 index 0000000..7a4a55f --- /dev/null +++ b/server/src/main/java/instagram/server/comment/controller/dto/request/UpdateCommentRequest.java @@ -0,0 +1,12 @@ +package instagram.server.comment.controller.dto.request; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +public class UpdateCommentRequest { + private String content; +} diff --git a/server/src/main/java/instagram/server/comment/controller/dto/response/CommentDto.java b/server/src/main/java/instagram/server/comment/controller/dto/response/CommentDto.java new file mode 100644 index 0000000..afbc693 --- /dev/null +++ b/server/src/main/java/instagram/server/comment/controller/dto/response/CommentDto.java @@ -0,0 +1,29 @@ +package instagram.server.comment.controller.dto.response; + +import instagram.server.comment.entity.Comment; +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter + public class CommentDto { + private final Long commentId; + private final String content; + private final LocalDateTime createdAt; + + @Builder + private CommentDto(Long commentId, String content, LocalDateTime createdAt) { + this.commentId = commentId; + this.content = content; + this.createdAt = createdAt; + } + + public static CommentDto of(Comment comment) { + return CommentDto.builder() + .commentId(comment.getId()) + .content(comment.getContent()) + .createdAt(comment.getCreatedAt()) + .build(); + } +} diff --git a/server/src/main/java/instagram/server/comment/controller/dto/response/CommentResponse.java b/server/src/main/java/instagram/server/comment/controller/dto/response/CommentResponse.java new file mode 100644 index 0000000..434f248 --- /dev/null +++ b/server/src/main/java/instagram/server/comment/controller/dto/response/CommentResponse.java @@ -0,0 +1,22 @@ +package instagram.server.comment.controller.dto.response; + +import instagram.server.comment.entity.Comment; +import lombok.Builder; + +import java.util.List; + +@Builder +public class CommentResponse { + private final String content; + + @Builder + public CommentResponse(String content) { + this.content = content; + } + + public static CommentResponse from(Comment comment) { + return CommentResponse.builder() + .content(comment.getContent()) + .build(); + } +} diff --git a/server/src/main/java/instagram/server/comment/entity/Comment.java b/server/src/main/java/instagram/server/comment/entity/Comment.java new file mode 100644 index 0000000..7f3002e --- /dev/null +++ b/server/src/main/java/instagram/server/comment/entity/Comment.java @@ -0,0 +1,42 @@ +package instagram.server.comment.entity; + +import instagram.server.user.User; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Comment{ + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "comment_id") + private Long id; + + private String content; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @Builder + private Comment(final String content, final User user) { + this.user = user; + this.content = content; + } +} diff --git a/server/src/main/java/instagram/server/comment/repository/CommentRepository.java b/server/src/main/java/instagram/server/comment/repository/CommentRepository.java new file mode 100644 index 0000000..7ea9db1 --- /dev/null +++ b/server/src/main/java/instagram/server/comment/repository/CommentRepository.java @@ -0,0 +1,13 @@ +package instagram.server.comment.repository; + +import instagram.server.comment.entity.Comment; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface CommentRepository extends JpaRepository { + List findAllBy(); + + Optional findById(Long commentId); +} diff --git a/server/src/main/java/instagram/server/comment/service/CommentService.java b/server/src/main/java/instagram/server/comment/service/CommentService.java new file mode 100644 index 0000000..4c912b3 --- /dev/null +++ b/server/src/main/java/instagram/server/comment/service/CommentService.java @@ -0,0 +1,39 @@ +package instagram.server.comment.service; + +import instagram.server.comment.controller.dto.request.RegisterCommentRequest; +import instagram.server.comment.controller.dto.request.UpdateCommentRequest; +import instagram.server.comment.entity.Comment; +import instagram.server.comment.repository.CommentRepository; +import instagram.server.user.UserService; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@RequiredArgsConstructor +@Service +@Transactional +public class CommentService { + + private final CommentRepository commentitory; + private final UserService userService; + + public Comment save(RegisterCommentRequest registerCommentRequest, Long userId) { + Comment comment = registerCommentRequest.toEntity(userService.findUser(userId)); + return commentRepository.save(comment); + } + + public Comment findComment(long id) { + return commentRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("not found : " + id)); + } + + @Transactional + public Comment update(long id, UpdateCommentRequest request) { + Comment comment = commentRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("not found : " + id)); + + comment.update(request.getContent()); + + return comment; + } +} diff --git a/server/src/main/java/instagram/server/like/controller/LikeController.java b/server/src/main/java/instagram/server/like/controller/LikeController.java new file mode 100644 index 0000000..e0a0162 --- /dev/null +++ b/server/src/main/java/instagram/server/like/controller/LikeController.java @@ -0,0 +1,45 @@ +package instagram.server.like.controller; + +import instagram.server.like.entity.Like; +import instagram.server.like.service.LikeService; +import instagram.server.post.controller.dto.request.UpdatePostRequest; +import instagram.server.post.entity.Post; +import instagram.server.user.User; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RequiredArgsConstructor +@RestController +public class LikeController { + + private final LikeService likeService; + + @PostMapping("/api/likes") + public ResponseEntity registerLike(@RequestBody RegisterLikeRequest request, @LoginUser User user) { + Like savedLike = likeService.save(request, user.getId()); + + return ResponseEntity.status(HttpStatus.CREATED) + .body(savedLike); + } + + @GetMapping("/api/likes/{likeId}") + public void findPost(@PathVariable long postId) { + Post post = postService.findPosts(postId); + + } + + @PutMapping("/api/posts/{postId}") + public ResponseEntity updatePost(@PathVariable long postId, @RequestBody UpdatePostRequest request) { + Post updatedPost = postService.update(postId, request); + + return ResponseEntity.ok() + .body(updatedPost); + } +} diff --git a/server/src/main/java/instagram/server/like/controller/dto/response/LikeDto.java b/server/src/main/java/instagram/server/like/controller/dto/response/LikeDto.java new file mode 100644 index 0000000..6164bc5 --- /dev/null +++ b/server/src/main/java/instagram/server/like/controller/dto/response/LikeDto.java @@ -0,0 +1,28 @@ +package instagram.server.like.controller.dto.response; + +import instagram.server.like.entity.Like; +import instagram.server.post.controller.dto.response.PostDto; +import instagram.server.post.entity.Post; +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +public class LikeDto { + private final Long like; + private final Long post; + + @Builder + private LikeDto(Long like, Long post) { + this.like = like; + this.post = post; + } + + public static LikeDto of(Like like) { + return LikeDto.builder() + .like(like.getId()) + .post(like.getId()) + .build(); + } +} \ No newline at end of file diff --git a/server/src/main/java/instagram/server/like/entity/Like.java b/server/src/main/java/instagram/server/like/entity/Like.java new file mode 100644 index 0000000..7e6baac --- /dev/null +++ b/server/src/main/java/instagram/server/like/entity/Like.java @@ -0,0 +1,34 @@ +package instagram.server.like.entity; + +import instagram.server.post.entity.Post; +import instagram.server.user.User; +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Like { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "like_id") + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "post_id") + private Post post; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + @Builder + private Like(final Post post, final User user) { + this.post = post; + this.user = user; + } +} \ No newline at end of file diff --git a/server/src/main/java/instagram/server/like/repository/LikeRepository.java b/server/src/main/java/instagram/server/like/repository/LikeRepository.java new file mode 100644 index 0000000..baf8e90 --- /dev/null +++ b/server/src/main/java/instagram/server/like/repository/LikeRepository.java @@ -0,0 +1,13 @@ +package instagram.server.like.repository; + +import java.util.Optional; + +import instagram.server.like.entity.Like; +import instagram.server.post.entity.Post; +import instagram.server.user.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface LikeRepository extends JpaRepository { + + Optional findByUserAndPost(final User user, final Post post); +} \ No newline at end of file diff --git a/server/src/main/java/instagram/server/like/service/LikeService.java b/server/src/main/java/instagram/server/like/service/LikeService.java new file mode 100644 index 0000000..046af33 --- /dev/null +++ b/server/src/main/java/instagram/server/like/service/LikeService.java @@ -0,0 +1,61 @@ +package instagram.server.like.service; + +import instagram.server.like.controller.dto.response.LikeDto; +import instagram.server.like.entity.Like; +import instagram.server.like.repository.LikeRepository; +import instagram.server.post.entity.Post; +import instagram.server.post.repository.PostRepository; +import instagram.server.user.User; +import instagram.server.user.UserRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import lombok.RequiredArgsConstructor; + +@Service +@Transactional +@RequiredArgsConstructor +public class LikeService { + + private final UserRepository userRepository; + private final PostRepository postRepository; + private final LikeRepository likeRepository; + + public void insert(LikeDto likeDto, Long userId) { + User user = userRepository.findById(userId) + .orElseThrow(() -> new IllegalArgumentException("[Error] 사용자를 찾을 수 없습니다.")); + Post post = postRepository.findById(likeDto.getPostId()) + .orElseThrow(() -> new IllegalArgumentException("[Error] 게시물을 찾을 수 없습니다.")); + + if (likeRepository.findByUserAndPost(user, post).isPresent()) { + throw new IllegalArgumentException("[Error] 이미 좋아요가 눌려있는 상태입니다."); + } + + Like like = Like.builder() + .post(post) + .user(user) + .build(); + + int likeCount = post.getLikeCount(); + postRepository.save(like); + post.updateLikeCount(++likeCount); + } + + public void delete(LikeDto likeDto, Long userId) { + User user = userRepository.findById(userId) + .orElseThrow(() -> new IllegalArgumentException("[Error] 사용자를 찾을 수 없습니다.")); + Post post = postRepository.findById(likeDto.getPostId()) + .orElseThrow(() -> new IllegalArgumentException("[Error] 게시물을 찾을 수 없습니다.")); + + Like like = likeRepository.findByUserAndPost(user, post) + .orElseThrow(() -> new IllegalArgumentException("[Error] 좋아요를 찾을 수 없습니다.")); + + int likeCount = post.getLikeCount(); + likeRepository.delete(like); + post.updateLikeCount(--likeCount); + } + + public boolean isLiked(User user, Post post) { + return likeRepository.findByUserAndPost(user, post).isPresent(); + } +} \ No newline at end of file diff --git a/server/src/main/java/instagram/server/post/controller/PostController.java b/server/src/main/java/instagram/server/post/controller/PostController.java new file mode 100644 index 0000000..e02863c --- /dev/null +++ b/server/src/main/java/instagram/server/post/controller/PostController.java @@ -0,0 +1,45 @@ +package instagram.server.post.controller; + +import instagram.server.post.controller.dto.request.RegisterPostRequest; +import instagram.server.post.controller.dto.request.UpdatePostRequest; +import instagram.server.post.entity.Post; +import instagram.server.post.service.PostService; +import instagram.server.user.User; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RequiredArgsConstructor +@RestController +public class PostController { + + private final PostService postService; + + @PostMapping("/api/posts") + public ResponseEntity registerPost(@RequestBody RegisterPostRequest request, @LoginUser User user) { + Post savedPost = postService.save(request, user.getId()); + + return ResponseEntity.status(HttpStatus.CREATED) + .body(savedPost); + } + + @GetMapping("/api/posts/{postId}") + public void findPost(@PathVariable long postId) { + Post post = postService.findPosts(postId); + + } + + @PutMapping("/api/posts/{postId}") + public ResponseEntity updatePost(@PathVariable long postId, @RequestBody UpdatePostRequest request) { + Post updatedPost = postService.update(postId, request); + + return ResponseEntity.ok() + .body(updatedPost); + } +} diff --git a/server/src/main/java/instagram/server/post/controller/dto/request/RegisterPostRequest.java b/server/src/main/java/instagram/server/post/controller/dto/request/RegisterPostRequest.java new file mode 100644 index 0000000..b497c74 --- /dev/null +++ b/server/src/main/java/instagram/server/post/controller/dto/request/RegisterPostRequest.java @@ -0,0 +1,22 @@ +package instagram.server.post.controller.dto.request; + +import instagram.server.post.entity.Post; +import instagram.server.user.User; +import lombok.Getter; + + +@Getter +public class RegisterPostRequest { + + private User userId; + private String title; + private String content; + + public Post toEntity(User userId) { + return Post.builder() + .user(userId) + .title(title) + .content(content) + .build(); + } +} diff --git a/server/src/main/java/instagram/server/post/controller/dto/request/UpdatePostRequest.java b/server/src/main/java/instagram/server/post/controller/dto/request/UpdatePostRequest.java new file mode 100644 index 0000000..607b0fc --- /dev/null +++ b/server/src/main/java/instagram/server/post/controller/dto/request/UpdatePostRequest.java @@ -0,0 +1,13 @@ +package instagram.server.post.controller.dto.request; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +public class UpdatePostRequest { + private String title; + private String content; +} diff --git a/server/src/main/java/instagram/server/post/controller/dto/response/PostDto.java b/server/src/main/java/instagram/server/post/controller/dto/response/PostDto.java new file mode 100644 index 0000000..5edcb30 --- /dev/null +++ b/server/src/main/java/instagram/server/post/controller/dto/response/PostDto.java @@ -0,0 +1,32 @@ +package instagram.server.post.controller.dto.response; + +import instagram.server.post.entity.Post; +import lombok.Builder; +import lombok.Getter; + +import java.time.LocalDateTime; + +@Getter +public class PostDto { + private final Long post; + private final String title; + private final String content; + private final LocalDateTime createdAt; + + @Builder + private PostDto(Long post, String title, String content, LocalDateTime createdAt) { + this.post = post; + this.title = title; + this.content = content; + this.createdAt = createdAt; + } + + public static PostDto of(Post post) { + return PostDto.builder() + .post(post.getId()) + .title(post.getTitle()) + .content(post.getContent()) + .createdAt(post.getCreatedAt()) + .build(); + } +} diff --git a/server/src/main/java/instagram/server/post/controller/dto/response/PostResponse.java b/server/src/main/java/instagram/server/post/controller/dto/response/PostResponse.java new file mode 100644 index 0000000..fc18d5e --- /dev/null +++ b/server/src/main/java/instagram/server/post/controller/dto/response/PostResponse.java @@ -0,0 +1,23 @@ +package instagram.server.post.controller.dto.response; + +import instagram.server.post.entity.Post; +import lombok.Builder; + +@Builder +public class PostResponse { + private final String title; + private final String content; + + @Builder + public PostResponse(String title, String content) { + this.title = title; + this.content = content; + } + + public static PostResponse from(Post post) { + return PostResponse.builder() + .title(post.getTitle()) + .content(post.getContent()) + .build(); + } +} diff --git a/server/src/main/java/instagram/server/post/entity/Post.java b/server/src/main/java/instagram/server/post/entity/Post.java new file mode 100644 index 0000000..d87574c --- /dev/null +++ b/server/src/main/java/instagram/server/post/entity/Post.java @@ -0,0 +1,48 @@ +package instagram.server.post.entity; + +import instagram.server.user.User; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Entity +@Getter +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class Post { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "postId") + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") // user_id를 외래 키로 사용 + private User user; + + private String title; + private String content; + + @Builder + private Post(User user, String title, String content) { + this.user = user; + this.title = title; + this.content = content; + } + + public void update(String title, String content) { + this.title = title; + this.content = content; + } + +} diff --git a/server/src/main/java/instagram/server/post/repository/PostRepository.java b/server/src/main/java/instagram/server/post/repository/PostRepository.java new file mode 100644 index 0000000..63fed7c --- /dev/null +++ b/server/src/main/java/instagram/server/post/repository/PostRepository.java @@ -0,0 +1,12 @@ +package instagram.server.post.repository; + +import instagram.server.post.entity.Post; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; +import java.util.Optional; + +public interface PostRepository extends JpaRepository { + + Optional findById(Long postId); +} diff --git a/server/src/main/java/instagram/server/post/service/PostService.java b/server/src/main/java/instagram/server/post/service/PostService.java new file mode 100644 index 0000000..6841b42 --- /dev/null +++ b/server/src/main/java/instagram/server/post/service/PostService.java @@ -0,0 +1,39 @@ +package instagram.server.post.service; + +import instagram.server.post.controller.dto.request.RegisterPostRequest; +import instagram.server.post.controller.dto.request.UpdatePostRequest; +import instagram.server.post.entity.Post; +import instagram.server.post.repository.PostRepository; +import instagram.server.user.UserService; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@RequiredArgsConstructor +@Service +@Transactional +public class PostService { + + private final PostRepository postRepository; + private final UserService userService; + + public Post save(RegisterPostRequest registerPostRequest, String username) { + Post post = registerPostRequest.toEntity(userService.findUser(username)); + return postRepository.save(post); + } + + public Post findPosts(long id) { + return postRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("not found : " + id)); + } + + @Transactional + public Post update(long id, UpdatePostRequest request) { + Post post = postRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("not found : " + id)); + + post.update(request.getTitle(), request.getContent()); + + return post; + } +} diff --git a/server/src/main/java/instagram/server/user/AuthController.java b/server/src/main/java/instagram/server/user/AuthController.java new file mode 100644 index 0000000..df85c23 --- /dev/null +++ b/server/src/main/java/instagram/server/user/AuthController.java @@ -0,0 +1,37 @@ +package instagram.server.user; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/auth") +public class AuthController { + + @Autowired + private AuthenticationManager authenticationManager; + + @Autowired + private JwtTokenProvider tokenProvider; + + @Autowired + private UserService userService; + + @PostMapping("/register") + public User registerUser(@RequestBody User user) { + return userService.registerUser(user.getUsername(), user.getPassword()); + } + + @PostMapping("/login") + public String authenticateUser(@RequestBody User user) { + Authentication authentication = authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + return tokenProvider.generateToken(authentication); + } +} diff --git a/server/src/main/java/instagram/server/user/CustomUserDetailsService.java b/server/src/main/java/instagram/server/user/CustomUserDetailsService.java new file mode 100644 index 0000000..2e3f95a --- /dev/null +++ b/server/src/main/java/instagram/server/user/CustomUserDetailsService.java @@ -0,0 +1,22 @@ +package instagram.server.user; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; + +@Service +public class CustomUserDetailsService implements UserDetailsService { + @Autowired + private UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = userRepository.findByUsername(username) + .orElseThrow(() -> new UsernameNotFoundException("User not found")); + return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>()); + } +} diff --git a/server/src/main/java/instagram/server/user/JwtAuthenticationFilter.java b/server/src/main/java/instagram/server/user/JwtAuthenticationFilter.java new file mode 100644 index 0000000..4b05270 --- /dev/null +++ b/server/src/main/java/instagram/server/user/JwtAuthenticationFilter.java @@ -0,0 +1,53 @@ +package instagram.server.user; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Component +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + @Autowired + private JwtTokenProvider tokenProvider; + + @Autowired + private UserDetailsService customUserDetailsService; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + + String jwt = getJwtFromRequest(request); + + if (jwt != null && tokenProvider.validateToken(jwt)) { + String username = tokenProvider.getUsernameFromJWT(jwt); + + UserDetails userDetails = customUserDetailsService.loadUserByUsername(username); + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + filterChain.doFilter(request, response); + } + + private String getJwtFromRequest(HttpServletRequest request) { + String bearerToken = request.getHeader("Authorization"); + if (bearerToken != null && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); + } + return null; + } +} diff --git a/server/src/main/java/instagram/server/user/JwtTokenProvider.java b/server/src/main/java/instagram/server/user/JwtTokenProvider.java new file mode 100644 index 0000000..b6ffe7e --- /dev/null +++ b/server/src/main/java/instagram/server/user/JwtTokenProvider.java @@ -0,0 +1,47 @@ +package instagram.server.user; + +import org.apache.tomcat.util.net.openssl.ciphers.Authentication; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.security.SignatureException; +import java.util.Date; + +@Component +public class JwtTokenProvider { + @Value("${app.jwtSecret}") + private String jwtSecret; + + @Value("${app.jwtExpirationMs}") + private int jwtExpirationMs; + + public String generateToken(Authentication authentication) { + String username = authentication.getName(); + Date now = new Date(); + Date expiryDate = new Date(now.getTime() + jwtExpirationMs); + + return Jwts.builder() + .setSubject(username) + .setIssuedAt(new Date()) + .setExpiration(expiryDate) + .signWith(SignatureAlgorithm.HS512, jwtSecret) + .compact(); + } + + public String getUsernameFromJWT(String token) { + return Jwts.parser() + .setSigningKey(jwtSecret) + .parseClaimsJws(token) + .getBody() + .getSubject(); + } + + public boolean validateToken(String authToken) { + try { + Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); + return true; + } catch (SignatureException | MalformedJwtException | ExpiredJwtException | UnsupportedJwtException | IllegalArgumentException ex) { + return false; + } + } +} diff --git a/server/src/main/java/instagram/server/user/SecurityConfig.java b/server/src/main/java/instagram/server/user/SecurityConfig.java new file mode 100644 index 0000000..d3fa20f --- /dev/null +++ b/server/src/main/java/instagram/server/user/SecurityConfig.java @@ -0,0 +1,53 @@ +package instagram.server.user; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private CustomUserDetailsService customUserDetailsService; + + @Autowired + private JwtAuthenticationFilter jwtAuthenticationFilter; + + @Override + public void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder()); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .csrf().disable() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .authorizeRequests() + .antMatchers("/auth/**").permitAll() + .anyRequest().authenticated(); + + http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + } +} diff --git a/server/src/main/java/instagram/server/user/User.java b/server/src/main/java/instagram/server/user/User.java new file mode 100644 index 0000000..b81e956 --- /dev/null +++ b/server/src/main/java/instagram/server/user/User.java @@ -0,0 +1,47 @@ +package instagram.server.user; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(unique = true) + private String username; + + private String password; + + // Getter와 Setter 메서드 + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/server/src/main/java/instagram/server/user/UserRepository.java b/server/src/main/java/instagram/server/user/UserRepository.java new file mode 100644 index 0000000..494dd39 --- /dev/null +++ b/server/src/main/java/instagram/server/user/UserRepository.java @@ -0,0 +1,10 @@ +package instagram.server.user; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface UserRepository extends JpaRepository { + Optional findByUsername(String username); + Boolean existsByUsername(String username); +} diff --git a/server/src/main/java/instagram/server/user/UserService.java b/server/src/main/java/instagram/server/user/UserService.java new file mode 100644 index 0000000..22fa274 --- /dev/null +++ b/server/src/main/java/instagram/server/user/UserService.java @@ -0,0 +1,30 @@ +package instagram.server.user; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; + +@Service +public class UserService { + @Autowired + private UserRepository userRepository; + + @Autowired + private PasswordEncoder passwordEncoder; + + public User registerUser(String username, String password) { + if (userRepository.existsByUsername(username)) { + throw new RuntimeException("Username already exists"); + } + + User user = new User(); + user.setUsername(username); + user.setPassword(passwordEncoder.encode(password)); + return userRepository.save(user); + } + + public User findUser(String username) { + return userRepository.findByUsername(username) + .orElseThrow(() -> new RuntimeException("User not found")); + } +} diff --git a/server/src/main/resources/application.properties b/server/src/main/resources/application.properties new file mode 100644 index 0000000..e82e2e8 --- /dev/null +++ b/server/src/main/resources/application.properties @@ -0,0 +1,8 @@ +spring.application.name=server +spring.datasource.url=jdbc:mysql://localhost:3306/instagram +spring.datasource.username=root +spring.datasource.password=yourpassword +spring.jpa.hibernate.ddl-auto=update +app.jwtSecret=yourSecretKey +app.jwtExpirationMs=86400000 + diff --git a/server/src/test/java/instagram/server/ServerApplicationTests.java b/server/src/test/java/instagram/server/ServerApplicationTests.java new file mode 100644 index 0000000..6ecca79 --- /dev/null +++ b/server/src/test/java/instagram/server/ServerApplicationTests.java @@ -0,0 +1,13 @@ +package instagram.server; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ServerApplicationTests { + + @Test + void contextLoads() { + } + +}