From f7e6e8a5bc2757eed25846458818a58218de4c86 Mon Sep 17 00:00:00 2001 From: Byung Wook Park Date: Wed, 21 Jul 2021 17:53:36 +0900 Subject: [PATCH] =?UTF-8?q?[BE]=20=EC=BD=94=EB=94=A9=20=EC=BB=A8=EB=B0=B4?= =?UTF-8?q?=EC=85=98=EC=9D=84=20=EC=A0=95=ED=95=98=EA=B8=B0=20=EC=9C=84?= =?UTF-8?q?=ED=95=B4=20=EC=A0=84=EC=B2=B4=EC=A0=81=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=A6=AC=ED=8C=A9=ED=86=A0=EB=A7=81=ED=95=9C=EB=8B=A4.=20(#236?= =?UTF-8?q?)=20(#238)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: 코딩 컨밴션을 맞추며 전체적으로 리팩터링 * [BE] 특정 사용자의 프로젝트 이름을 중복 사용하지 못하게 수정 (#218) (#235) * feat: 프로젝트 이름 중복 체크 로직 추가 * test: 프로젝트 이름 중복에 대한 테스트 코드 추가 * feat: 프로젝트 이름 중복에 대한 인수 테스트 추가 * refactor: asciidoc 파일명 수정 * refactor: 가독성 좋게 코드 수정 * [BE] 비회원 댓글 비밀번호만 체크하는 API 만들기 / 관리자 댓글 삭제 기능 (#217) (#230) * feat: 비로그인 유저 비밀번호 확인 api 구현 및 테스트 작성 * test: 비밀번호 일치하지 않는 경우 테스트 작성 및 restdoc 작성 * chore: gitignore 설정 추가 * feat: 관리자 댓글 삭제 기능 구현 및 테스트 작성 * docs: restdoc adoc 작성 * refactor: 메소드 네이밍 변경 Co-authored-by: JinYoung Park * [BE] 카카오 프사를 바꿨을 경우, 서버의 카카오 프로필 데이터가 업데이트 되지 않는 문제를 해결한다. (#202) (#231) * refactor: 카카오에서 받아온 데이터기준으로 사용자 정보 업데이트 하도록 리팩터링 * feat: jpa 테스트 격리를 위한 클래스 구현 * refactor: 병렬 테스트 구현 - junit5 Parallel Execution 적용 * refactor: 모든 테스트가 병렬적으로 수행되도록 리팩터링 * refactor: 병렬 수행 설정 수정 - 테스트 클래스는 병렬도 수행된다. - 테스트 클래스 내의 메서드들은 순차적으로 수행된다. * refactor: 서브 모듈 수정 * refactor: optional 변수명 수정 * refactor: 불필요한 로직제거 - 빈생성시 afterPropertiesSet에서 자동 초기화 되므로 체크 안해도 된다고 판단함 Co-authored-by: JinYoung Park * style: 코드 포메팅 수정 Co-authored-by: jaeseongDev Co-authored-by: Sehwan_Jang <68985748+Sehwan-Jang@users.noreply.github.com> Co-authored-by: JinYoung Park --- .../java/com/darass/darass/WebConfig.java | 4 +- .../oauth/AuthenticationPrincipalConfig.java | 6 +- .../oauth/api/domain/UserInfoProvider.java | 8 +- .../auth/oauth/api/domain/dto/Profile.java | 5 +- ...thenticationPrincipalArgumentResolver.java | 3 +- .../oauth/controller/OAuthController.java | 2 +- .../RequiredLoginArgumentResolver.java | 11 +- .../{controller => }/dto/TokenResponse.java | 2 +- .../AuthorizationExtractor.java | 2 +- .../infrastructure/JwtTokenProvider.java | 20 +- .../auth/oauth/service/OAuthService.java | 20 +- .../comment/controller/CommentController.java | 34 +- .../controller/dto/CommentDeleteRequest.java | 13 - .../darass/darass/comment/domain/Comment.java | 7 +- .../darass/comment/domain/Comments.java | 6 +- .../dto/CommentCreateRequest.java | 5 +- .../comment/dto/CommentDeleteRequest.java | 13 + .../{controller => }/dto/CommentResponse.java | 9 +- .../dto/CommentUpdateRequest.java | 13 +- .../comment/repository/CommentRepository.java | 3 - .../comment/service/CommentService.java | 37 +- .../common/JpaAuditingConfiguration.java | 9 +- .../darass/common/domain/BaseTimeEntity.java | 9 +- .../exception/dto/ExceptionResponse.java | 3 +- .../httpbasicexception/CustomException.java | 2 +- .../project/controller/ProjectController.java | 30 +- .../darass/darass/project/domain/Project.java | 16 +- .../domain/RandomSecretKeyFactory.java | 3 +- .../project/domain/SecretKeyFactory.java | 3 +- .../dto/ProjectCreateRequest.java | 7 +- .../{controller => }/dto/ProjectResponse.java | 9 +- .../project/repository/ProjectRepository.java | 8 +- .../project/service/ProjectService.java | 31 +- .../user/controller/UserController.java | 28 +- .../darass/darass/user/domain/GuestUser.java | 5 +- .../darass/user/domain/SocialLoginUser.java | 2 +- .../com/darass/darass/user/domain/User.java | 15 +- .../dto/PasswordCheckRequest.java | 7 +- .../dto/PasswordCheckResponse.java | 2 +- .../controller => user}/dto/UserResponse.java | 8 +- .../dto/UserUpdateRequest.java | 2 +- .../repository/SocialLoginUserRepository.java | 3 +- .../darass/user/service/UserService.java | 23 +- backend/src/main/resources/logback-access.xml | 14 +- backend/src/main/resources/logback.xml | 30 +- .../oauth/acceptance/AuthAcceptanceTest.java | 5 +- .../api/domain/UserInfoProviderTest.java | 3 +- .../AuthorizationExtractorTest.java | 5 +- .../auth/oauth/service/OAuthServiceTest.java | 2 +- .../acceptance/CommentAcceptanceTest.java | 367 +++++++++--------- .../controller/ControllerAdviceTest.java | 2 +- .../acceptance/ProjectAcceptanceTest.java | 4 +- .../project/service/ProjectServiceTest.java | 4 +- .../user/controller/UserAcceptanceTest.java | 215 +++++----- .../darass/user/service/UserServiceTest.java | 4 +- .../src/test/resources/application.properties | 2 +- 56 files changed, 569 insertions(+), 536 deletions(-) rename backend/src/main/java/com/darass/darass/auth/oauth/{controller => }/dto/TokenResponse.java (85%) delete mode 100644 backend/src/main/java/com/darass/darass/comment/controller/dto/CommentDeleteRequest.java rename backend/src/main/java/com/darass/darass/comment/{controller => }/dto/CommentCreateRequest.java (77%) create mode 100644 backend/src/main/java/com/darass/darass/comment/dto/CommentDeleteRequest.java rename backend/src/main/java/com/darass/darass/comment/{controller => }/dto/CommentResponse.java (82%) rename backend/src/main/java/com/darass/darass/comment/{controller => }/dto/CommentUpdateRequest.java (66%) rename backend/src/main/java/com/darass/darass/project/{controller => }/dto/ProjectCreateRequest.java (83%) rename backend/src/main/java/com/darass/darass/project/{controller => }/dto/ProjectResponse.java (78%) rename backend/src/main/java/com/darass/darass/user/{controller => }/dto/PasswordCheckRequest.java (72%) rename backend/src/main/java/com/darass/darass/user/{controller => }/dto/PasswordCheckResponse.java (82%) rename backend/src/main/java/com/darass/darass/{comment/controller => user}/dto/UserResponse.java (81%) rename backend/src/main/java/com/darass/darass/user/{controller => }/dto/UserUpdateRequest.java (84%) diff --git a/backend/src/main/java/com/darass/darass/WebConfig.java b/backend/src/main/java/com/darass/darass/WebConfig.java index 872756df5..c8904a5b5 100644 --- a/backend/src/main/java/com/darass/darass/WebConfig.java +++ b/backend/src/main/java/com/darass/darass/WebConfig.java @@ -10,7 +10,7 @@ public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") - .allowedOrigins("*") - .allowedMethods("*"); + .allowedOrigins("*") + .allowedMethods("*"); } } diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/AuthenticationPrincipalConfig.java b/backend/src/main/java/com/darass/darass/auth/oauth/AuthenticationPrincipalConfig.java index 807b0374f..ae931abc4 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/AuthenticationPrincipalConfig.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/AuthenticationPrincipalConfig.java @@ -3,13 +3,13 @@ import com.darass.darass.auth.oauth.controller.AuthenticationPrincipalArgumentResolver; import com.darass.darass.auth.oauth.controller.RequiredLoginArgumentResolver; import com.darass.darass.auth.oauth.service.OAuthService; +import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import java.util.List; - @Configuration @RequiredArgsConstructor public class AuthenticationPrincipalConfig implements WebMvcConfigurer { @@ -17,7 +17,7 @@ public class AuthenticationPrincipalConfig implements WebMvcConfigurer { private final OAuthService oAuthService; @Override - public void addArgumentResolvers(List argumentResolvers) { + public void addArgumentResolvers(List argumentResolvers) { argumentResolvers.add(createAuthenticationPrincipalArgumentResolver()); argumentResolvers.add(createRequiredLoginArgumentResolver()); } diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/api/domain/UserInfoProvider.java b/backend/src/main/java/com/darass/darass/auth/oauth/api/domain/UserInfoProvider.java index 236144fb0..02b2e97fc 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/api/domain/UserInfoProvider.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/api/domain/UserInfoProvider.java @@ -8,6 +8,7 @@ import com.darass.darass.user.domain.SocialLoginUser; import java.nio.charset.StandardCharsets; import java.util.Collections; +import java.util.Objects; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -32,11 +33,11 @@ public SocialLoginUser findSocialLoginUser(String accessToken) { try { SocialLoginResponse socialLoginResponse = restTemplate.postForObject(KAKAO_API_SERVER_URI, apiRequest, SocialLoginResponse.class); - return parseUser(socialLoginResponse); + return parseUser(Objects.requireNonNull(socialLoginResponse)); } catch (HttpClientErrorException e) { throw ExceptionWithMessageAndCode.INVALID_JWT_TOKEN.getException(); - } + } // TODO: null 포인터 예외 잡아야한다. } private HttpEntity prepareRequest(String accessToken) { @@ -53,7 +54,7 @@ private SocialLoginUser parseUser(SocialLoginResponse socialLoginResponse) { String email = kaKaoAccount.getEmail(); Profile profile = socialLoginResponse.getKaKaoAccount().getProfile(); String nickname = profile.getNickname(); - String profileImageUrl = profile.getThumbnail_image_url(); + String profileImageUrl = profile.getThumbnailImageUrl(); return SocialLoginUser .builder() @@ -63,6 +64,5 @@ private SocialLoginUser parseUser(SocialLoginResponse socialLoginResponse) { .email(email) .profileImageUrl(profileImageUrl) .build(); - } } diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/api/domain/dto/Profile.java b/backend/src/main/java/com/darass/darass/auth/oauth/api/domain/dto/Profile.java index bffb0879a..2247da831 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/api/domain/dto/Profile.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/api/domain/dto/Profile.java @@ -1,5 +1,6 @@ package com.darass.darass.auth.oauth.api.domain.dto; +import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -11,5 +12,7 @@ public class Profile { private String nickname; - private String thumbnail_image_url; + @JsonProperty("thumbnail_image_url") + private String thumbnailImageUrl; + } diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/controller/AuthenticationPrincipalArgumentResolver.java b/backend/src/main/java/com/darass/darass/auth/oauth/controller/AuthenticationPrincipalArgumentResolver.java index 48ef2779f..2f232ff6c 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/controller/AuthenticationPrincipalArgumentResolver.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/controller/AuthenticationPrincipalArgumentResolver.java @@ -27,7 +27,8 @@ public boolean supportsParameter(MethodParameter parameter) { @Override public User resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { - String accessToken = AuthorizationExtractor.extract(Objects.requireNonNull(webRequest.getNativeRequest(HttpServletRequest.class))); + String accessToken = AuthorizationExtractor + .extract(Objects.requireNonNull(webRequest.getNativeRequest(HttpServletRequest.class))); if (Objects.isNull(accessToken) || accessToken.isEmpty()) { return new GuestUser(); diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/controller/OAuthController.java b/backend/src/main/java/com/darass/darass/auth/oauth/controller/OAuthController.java index 15f5d0937..99162b20a 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/controller/OAuthController.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/controller/OAuthController.java @@ -1,6 +1,6 @@ package com.darass.darass.auth.oauth.controller; -import com.darass.darass.auth.oauth.controller.dto.TokenResponse; +import com.darass.darass.auth.oauth.dto.TokenResponse; import com.darass.darass.auth.oauth.service.OAuthService; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/controller/RequiredLoginArgumentResolver.java b/backend/src/main/java/com/darass/darass/auth/oauth/controller/RequiredLoginArgumentResolver.java index f84725ab3..59b577608 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/controller/RequiredLoginArgumentResolver.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/controller/RequiredLoginArgumentResolver.java @@ -5,6 +5,8 @@ import com.darass.darass.auth.oauth.service.OAuthService; import com.darass.darass.exception.ExceptionWithMessageAndCode; import com.darass.darass.user.domain.User; +import java.util.Objects; +import javax.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; @@ -12,9 +14,6 @@ import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; -import javax.servlet.http.HttpServletRequest; -import java.util.Objects; - @RequiredArgsConstructor public class RequiredLoginArgumentResolver implements HandlerMethodArgumentResolver { @@ -27,9 +26,9 @@ public boolean supportsParameter(MethodParameter parameter) { @Override public User resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, - NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { - String accessToken = AuthorizationExtractor.extract(Objects.requireNonNull(webRequest.getNativeRequest( - HttpServletRequest.class))); + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { + String accessToken = AuthorizationExtractor + .extract(Objects.requireNonNull(webRequest.getNativeRequest(HttpServletRequest.class))); if (Objects.isNull(accessToken)) { throw ExceptionWithMessageAndCode.SHOULD_LOGIN.getException(); diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/controller/dto/TokenResponse.java b/backend/src/main/java/com/darass/darass/auth/oauth/dto/TokenResponse.java similarity index 85% rename from backend/src/main/java/com/darass/darass/auth/oauth/controller/dto/TokenResponse.java rename to backend/src/main/java/com/darass/darass/auth/oauth/dto/TokenResponse.java index 6f4110965..a2749af70 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/controller/dto/TokenResponse.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/dto/TokenResponse.java @@ -1,4 +1,4 @@ -package com.darass.darass.auth.oauth.controller.dto; +package com.darass.darass.auth.oauth.dto; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/infrastructure/AuthorizationExtractor.java b/backend/src/main/java/com/darass/darass/auth/oauth/infrastructure/AuthorizationExtractor.java index 6ebe043c6..695d74d9b 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/infrastructure/AuthorizationExtractor.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/infrastructure/AuthorizationExtractor.java @@ -1,7 +1,7 @@ package com.darass.darass.auth.oauth.infrastructure; -import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; +import javax.servlet.http.HttpServletRequest; public class AuthorizationExtractor { diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/infrastructure/JwtTokenProvider.java b/backend/src/main/java/com/darass/darass/auth/oauth/infrastructure/JwtTokenProvider.java index 7b23b745f..7f9065191 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/infrastructure/JwtTokenProvider.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/infrastructure/JwtTokenProvider.java @@ -1,17 +1,21 @@ package com.darass.darass.auth.oauth.infrastructure; import com.darass.darass.exception.ExceptionWithMessageAndCode; -import io.jsonwebtoken.*; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.SignatureAlgorithm; +import java.util.Date; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import java.util.Date; - @Component public class JwtTokenProvider { @Value("${security.jwt.token.secret-key}") private String secretKey; + @Value("${security.jwt.token.expire-length}") private long validityInMilliseconds; @@ -21,11 +25,11 @@ public String createAccessToken(String payload) { Date validity = new Date(now.getTime() + validityInMilliseconds); return Jwts.builder() - .setClaims(claims) - .setIssuedAt(now) - .setExpiration(validity) - .signWith(SignatureAlgorithm.HS256, secretKey) - .compact(); + .setClaims(claims) + .setIssuedAt(now) + .setExpiration(validity) + .signWith(SignatureAlgorithm.HS256, secretKey) + .compact(); } public String getPayload(String accessToken) { diff --git a/backend/src/main/java/com/darass/darass/auth/oauth/service/OAuthService.java b/backend/src/main/java/com/darass/darass/auth/oauth/service/OAuthService.java index 98d98c067..b1c280576 100644 --- a/backend/src/main/java/com/darass/darass/auth/oauth/service/OAuthService.java +++ b/backend/src/main/java/com/darass/darass/auth/oauth/service/OAuthService.java @@ -1,31 +1,35 @@ package com.darass.darass.auth.oauth.service; import com.darass.darass.auth.oauth.api.domain.UserInfoProvider; -import com.darass.darass.auth.oauth.controller.dto.TokenResponse; +import com.darass.darass.auth.oauth.dto.TokenResponse; import com.darass.darass.auth.oauth.infrastructure.JwtTokenProvider; import com.darass.darass.exception.ExceptionWithMessageAndCode; import com.darass.darass.user.domain.SocialLoginUser; import com.darass.darass.user.repository.SocialLoginUserRepository; +import java.util.Optional; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.Optional; - -@Service -@AllArgsConstructor @Transactional +@AllArgsConstructor +@Service public class OAuthService { private SocialLoginUserRepository socialLoginUserRepository; + private JwtTokenProvider jwtTokenProvider; - private UserInfoProvider userInfoProvider; + + private UserInfoProvider userInfoProvider; //TODO: Mocking시 final 못붙이는 문제가 있다. public TokenResponse oauthLogin(String oauthAccessToken) { SocialLoginUser socialLoginUser = userInfoProvider.findSocialLoginUser(oauthAccessToken); - Optional possibleSocialLoginUser = socialLoginUserRepository.findByOauthId(socialLoginUser.getOauthId()); - if (possibleSocialLoginUser.isEmpty()) { + Optional possibleSocialLoginUser = socialLoginUserRepository + .findByOauthId(socialLoginUser.getOauthId()); + + if (possibleSocialLoginUser.isEmpty()) { //TODO: 옵셔널로 변경 가능? + socialLoginUserRepository.save(socialLoginUser); return TokenResponse.of(jwtTokenProvider.createAccessToken(socialLoginUser.getId().toString())); } diff --git a/backend/src/main/java/com/darass/darass/comment/controller/CommentController.java b/backend/src/main/java/com/darass/darass/comment/controller/CommentController.java index da372a4d1..f145f2cf7 100644 --- a/backend/src/main/java/com/darass/darass/comment/controller/CommentController.java +++ b/backend/src/main/java/com/darass/darass/comment/controller/CommentController.java @@ -1,35 +1,45 @@ package com.darass.darass.comment.controller; import com.darass.darass.auth.oauth.domain.AuthenticationPrincipal; -import com.darass.darass.comment.controller.dto.CommentCreateRequest; -import com.darass.darass.comment.controller.dto.CommentDeleteRequest; -import com.darass.darass.comment.controller.dto.CommentResponse; -import com.darass.darass.comment.controller.dto.CommentUpdateRequest; +import com.darass.darass.comment.dto.CommentCreateRequest; +import com.darass.darass.comment.dto.CommentDeleteRequest; +import com.darass.darass.comment.dto.CommentResponse; +import com.darass.darass.comment.dto.CommentUpdateRequest; import com.darass.darass.comment.service.CommentService; import com.darass.darass.user.domain.User; +import java.util.List; +import javax.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import javax.validation.Valid; -import java.util.List; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; -@RestController -@RequestMapping("/api/v1/comments") @RequiredArgsConstructor +@RequestMapping("/api/v1/comments") +@RestController public class CommentController { private final CommentService commentService; @GetMapping - public ResponseEntity> read(@RequestParam("url") String url, @RequestParam("projectKey") String projectKey) { + public ResponseEntity> read(@RequestParam("url") String url, + @RequestParam("projectKey") String projectKey) { List commentResponses = commentService.findAllCommentsByUrlAndProjectKey(url, projectKey); return ResponseEntity.status(HttpStatus.OK).body(commentResponses); } @PostMapping - public ResponseEntity save(@AuthenticationPrincipal User user, @Valid @RequestBody CommentCreateRequest commentRequest) { + public ResponseEntity save(@AuthenticationPrincipal User user, + @Valid @RequestBody CommentCreateRequest commentRequest) { CommentResponse commentResponse = commentService.save(user, commentRequest); return ResponseEntity.status(HttpStatus.CREATED).body(commentResponse); } diff --git a/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentDeleteRequest.java b/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentDeleteRequest.java deleted file mode 100644 index 6c40e3797..000000000 --- a/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentDeleteRequest.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.darass.darass.comment.controller.dto; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; - -@Getter -@AllArgsConstructor -public class CommentDeleteRequest { - - private Long guestUserId; - private String guestUserPassword; -} diff --git a/backend/src/main/java/com/darass/darass/comment/domain/Comment.java b/backend/src/main/java/com/darass/darass/comment/domain/Comment.java index 68d009b5d..8a2def8bf 100644 --- a/backend/src/main/java/com/darass/darass/comment/domain/Comment.java +++ b/backend/src/main/java/com/darass/darass/comment/domain/Comment.java @@ -14,9 +14,9 @@ import lombok.Getter; import lombok.NoArgsConstructor; -@Entity -@NoArgsConstructor @Getter +@NoArgsConstructor +@Entity public class Comment extends BaseTimeEntity { @Id @@ -32,6 +32,7 @@ public class Comment extends BaseTimeEntity { private Project project; private String url; + private String content; @Builder @@ -55,7 +56,7 @@ public boolean match(String url, String projectKey) { return this.url.equals(url) && project.isSame(projectKey); } - public Long getUserId(){ + public Long getUserId() { return user.getId(); } diff --git a/backend/src/main/java/com/darass/darass/comment/domain/Comments.java b/backend/src/main/java/com/darass/darass/comment/domain/Comments.java index b19fb2542..18c9afc98 100644 --- a/backend/src/main/java/com/darass/darass/comment/domain/Comments.java +++ b/backend/src/main/java/com/darass/darass/comment/domain/Comments.java @@ -2,15 +2,13 @@ import java.util.List; import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +@RequiredArgsConstructor public class Comments { private final List comments; - public Comments(List comments) { - this.comments = comments; - } - public List match(String url, String projectKey) { return comments.stream() .filter(it -> it.match(url, projectKey)) diff --git a/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentCreateRequest.java b/backend/src/main/java/com/darass/darass/comment/dto/CommentCreateRequest.java similarity index 77% rename from backend/src/main/java/com/darass/darass/comment/controller/dto/CommentCreateRequest.java rename to backend/src/main/java/com/darass/darass/comment/dto/CommentCreateRequest.java index c39c433c5..608f518dc 100644 --- a/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentCreateRequest.java +++ b/backend/src/main/java/com/darass/darass/comment/dto/CommentCreateRequest.java @@ -1,5 +1,6 @@ -package com.darass.darass.comment.controller.dto; +package com.darass.darass.comment.dto; +import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; @@ -14,10 +15,12 @@ public class CommentCreateRequest { private String guestPassword; + @NotBlank private String projectSecretKey; @NotNull private String content; + @NotBlank private String url; } diff --git a/backend/src/main/java/com/darass/darass/comment/dto/CommentDeleteRequest.java b/backend/src/main/java/com/darass/darass/comment/dto/CommentDeleteRequest.java new file mode 100644 index 000000000..a319f19bc --- /dev/null +++ b/backend/src/main/java/com/darass/darass/comment/dto/CommentDeleteRequest.java @@ -0,0 +1,13 @@ +package com.darass.darass.comment.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class CommentDeleteRequest { + + private final Long guestUserId; + + private final String guestUserPassword; +} diff --git a/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentResponse.java b/backend/src/main/java/com/darass/darass/comment/dto/CommentResponse.java similarity index 82% rename from backend/src/main/java/com/darass/darass/comment/controller/dto/CommentResponse.java rename to backend/src/main/java/com/darass/darass/comment/dto/CommentResponse.java index fe77bd06b..a1e80bc61 100644 --- a/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentResponse.java +++ b/backend/src/main/java/com/darass/darass/comment/dto/CommentResponse.java @@ -1,14 +1,14 @@ -package com.darass.darass.comment.controller.dto; +package com.darass.darass.comment.dto; import com.darass.darass.comment.domain.Comment; +import com.darass.darass.user.dto.UserResponse; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import java.time.LocalDateTime; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; -import java.time.LocalDateTime; - @Getter @AllArgsConstructor @NoArgsConstructor @@ -27,6 +27,7 @@ public class CommentResponse { private UserResponse user; public static CommentResponse of(Comment comment, UserResponse userResponse) { - return new CommentResponse(comment.getId(), comment.getContent(), comment.getCreatedDate(), comment.getModifiedDate(), userResponse); + return new CommentResponse(comment.getId(), comment.getContent(), comment.getCreatedDate(), + comment.getModifiedDate(), userResponse); } } diff --git a/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentUpdateRequest.java b/backend/src/main/java/com/darass/darass/comment/dto/CommentUpdateRequest.java similarity index 66% rename from backend/src/main/java/com/darass/darass/comment/controller/dto/CommentUpdateRequest.java rename to backend/src/main/java/com/darass/darass/comment/dto/CommentUpdateRequest.java index 4951ddb13..27bc82fe2 100644 --- a/backend/src/main/java/com/darass/darass/comment/controller/dto/CommentUpdateRequest.java +++ b/backend/src/main/java/com/darass/darass/comment/dto/CommentUpdateRequest.java @@ -1,19 +1,22 @@ -package com.darass.darass.comment.controller.dto; +package com.darass.darass.comment.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; @Getter -@AllArgsConstructor @NoArgsConstructor +@AllArgsConstructor +@RequiredArgsConstructor public class CommentUpdateRequest { private Long guestUserId; + private String guestUserPassword; + + @NonNull private String content; - public CommentUpdateRequest(String content) { - this.content = content; - } } diff --git a/backend/src/main/java/com/darass/darass/comment/repository/CommentRepository.java b/backend/src/main/java/com/darass/darass/comment/repository/CommentRepository.java index f13aac891..47e7937c7 100644 --- a/backend/src/main/java/com/darass/darass/comment/repository/CommentRepository.java +++ b/backend/src/main/java/com/darass/darass/comment/repository/CommentRepository.java @@ -3,9 +3,6 @@ import com.darass.darass.comment.domain.Comment; import org.springframework.data.jpa.repository.JpaRepository; -import java.util.List; - public interface CommentRepository extends JpaRepository { - List findByUrl(String url); } diff --git a/backend/src/main/java/com/darass/darass/comment/service/CommentService.java b/backend/src/main/java/com/darass/darass/comment/service/CommentService.java index 3625ba200..b2e7853f3 100644 --- a/backend/src/main/java/com/darass/darass/comment/service/CommentService.java +++ b/backend/src/main/java/com/darass/darass/comment/service/CommentService.java @@ -1,18 +1,18 @@ package com.darass.darass.comment.service; -import com.darass.darass.comment.controller.dto.CommentCreateRequest; -import com.darass.darass.comment.controller.dto.CommentDeleteRequest; -import com.darass.darass.comment.controller.dto.CommentResponse; -import com.darass.darass.comment.controller.dto.CommentUpdateRequest; -import com.darass.darass.comment.controller.dto.UserResponse; import com.darass.darass.comment.domain.Comment; import com.darass.darass.comment.domain.Comments; +import com.darass.darass.comment.dto.CommentCreateRequest; +import com.darass.darass.comment.dto.CommentDeleteRequest; +import com.darass.darass.comment.dto.CommentResponse; +import com.darass.darass.comment.dto.CommentUpdateRequest; import com.darass.darass.comment.repository.CommentRepository; import com.darass.darass.exception.ExceptionWithMessageAndCode; import com.darass.darass.project.domain.Project; import com.darass.darass.project.repository.ProjectRepository; import com.darass.darass.user.domain.GuestUser; import com.darass.darass.user.domain.User; +import com.darass.darass.user.dto.UserResponse; import com.darass.darass.user.repository.UserRepository; import java.util.List; import java.util.stream.Collectors; @@ -20,14 +20,14 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -@Service -@Transactional @RequiredArgsConstructor +@Transactional +@Service public class CommentService { private final CommentRepository commentRepository; - private final ProjectRepository projects; - private final UserRepository users; + private final ProjectRepository projectRepository; + private final UserRepository userRepository; public CommentResponse save(User user, CommentCreateRequest commentRequest) { if (!user.isLoginUser()) { @@ -35,13 +35,13 @@ public CommentResponse save(User user, CommentCreateRequest commentRequest) { } Project project = getBySecretKey(commentRequest); Comment comment = savedComment(user, commentRequest, project); - String userType = users.findUserTypeById(user.getId()); - String profileImageUrl = users.findProfileImageUrlById(user.getId()); + String userType = userRepository.findUserTypeById(user.getId()); + String profileImageUrl = userRepository.findProfileImageUrlById(user.getId()); return CommentResponse.of(comment, UserResponse.of(comment.getUser(), userType, profileImageUrl)); } private Project getBySecretKey(CommentCreateRequest commentRequest) { - return projects.findBySecretKey(commentRequest.getProjectSecretKey()) + return projectRepository.findBySecretKey(commentRequest.getProjectSecretKey()) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_PROJECT::getException); } @@ -60,10 +60,9 @@ private User savedGuestUser(CommentCreateRequest commentRequest) { .nickName(commentRequest.getGuestNickName()) .password(commentRequest.getGuestPassword()) .build(); - return users.save(user); + return userRepository.save(user); } - public List findAllCommentsByUrlAndProjectKey(String url, String projectKey) { Comments comments = new Comments(commentRepository.findAll()); List matchedComments = comments.match(url, projectKey); @@ -71,16 +70,16 @@ public List findAllCommentsByUrlAndProjectKey(String url, Strin return matchedComments.stream() .map(comment -> CommentResponse.of( - comment, UserResponse.of( + comment, UserResponse.of( //TODO: UserResponse 정적 팩터리 메서드 생성자에 User만 넣어준다. comment.getUser(), - users.findUserTypeById(comment.getUserId()), - users.findProfileImageUrlById(comment.getUserId()) + userRepository.findUserTypeById(comment.getUserId()), + userRepository.findProfileImageUrlById(comment.getUserId()) ) )) .collect(Collectors.toList()); } - public void updateContent(Long id, User user, CommentUpdateRequest request) { + public void updateContent(Long id, User user, CommentUpdateRequest request) { //TODO: 리팩터링 고민 user = findRegisteredUser(user, request.getGuestUserId(), request.getGuestUserPassword()); Comment comment = findCommentById(id); @@ -121,7 +120,7 @@ private Comment findCommentById(Long id) { private User findRegisteredUser(User user, Long guestUserId, String guestUserPassword) { if (!user.isLoginUser()) { - user = users.findById(guestUserId) + user = userRepository.findById(guestUserId) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_USER::getException); validateGuestUser(user, guestUserPassword); } diff --git a/backend/src/main/java/com/darass/darass/common/JpaAuditingConfiguration.java b/backend/src/main/java/com/darass/darass/common/JpaAuditingConfiguration.java index 5732d0bd3..acccaa96c 100644 --- a/backend/src/main/java/com/darass/darass/common/JpaAuditingConfiguration.java +++ b/backend/src/main/java/com/darass/darass/common/JpaAuditingConfiguration.java @@ -1,16 +1,15 @@ package com.darass.darass.common; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Optional; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.auditing.DateTimeProvider; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Optional; - -@Configuration @EnableJpaAuditing(dateTimeProviderRef = "utcDateTimeProvider") +@Configuration public class JpaAuditingConfiguration { @Bean diff --git a/backend/src/main/java/com/darass/darass/common/domain/BaseTimeEntity.java b/backend/src/main/java/com/darass/darass/common/domain/BaseTimeEntity.java index 73bc65145..2edca74c3 100644 --- a/backend/src/main/java/com/darass/darass/common/domain/BaseTimeEntity.java +++ b/backend/src/main/java/com/darass/darass/common/domain/BaseTimeEntity.java @@ -1,18 +1,17 @@ package com.darass.darass.common.domain; +import java.time.LocalDateTime; import javax.persistence.Column; +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; import lombok.Getter; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import javax.persistence.EntityListeners; -import javax.persistence.MappedSuperclass; -import java.time.LocalDateTime; - @Getter -@MappedSuperclass @EntityListeners(AuditingEntityListener.class) +@MappedSuperclass public abstract class BaseTimeEntity { @CreatedDate diff --git a/backend/src/main/java/com/darass/darass/exception/dto/ExceptionResponse.java b/backend/src/main/java/com/darass/darass/exception/dto/ExceptionResponse.java index ba7337d7c..9d3dcd82e 100644 --- a/backend/src/main/java/com/darass/darass/exception/dto/ExceptionResponse.java +++ b/backend/src/main/java/com/darass/darass/exception/dto/ExceptionResponse.java @@ -4,11 +4,12 @@ import lombok.Getter; import lombok.NoArgsConstructor; +@Getter @AllArgsConstructor @NoArgsConstructor -@Getter public class ExceptionResponse { private String message; + private Integer code; } diff --git a/backend/src/main/java/com/darass/darass/exception/httpbasicexception/CustomException.java b/backend/src/main/java/com/darass/darass/exception/httpbasicexception/CustomException.java index c71efb4ba..22b1b9670 100644 --- a/backend/src/main/java/com/darass/darass/exception/httpbasicexception/CustomException.java +++ b/backend/src/main/java/com/darass/darass/exception/httpbasicexception/CustomException.java @@ -5,7 +5,7 @@ @Getter public class CustomException extends RuntimeException { - private Integer code; + private final Integer code; public CustomException(String message, Integer code) { super(message); diff --git a/backend/src/main/java/com/darass/darass/project/controller/ProjectController.java b/backend/src/main/java/com/darass/darass/project/controller/ProjectController.java index c70eb69de..cc2a24058 100644 --- a/backend/src/main/java/com/darass/darass/project/controller/ProjectController.java +++ b/backend/src/main/java/com/darass/darass/project/controller/ProjectController.java @@ -1,30 +1,35 @@ package com.darass.darass.project.controller; import com.darass.darass.auth.oauth.domain.RequiredLogin; -import com.darass.darass.project.controller.dto.ProjectCreateRequest; -import com.darass.darass.project.controller.dto.ProjectResponse; import com.darass.darass.project.domain.RandomSecretKeyFactory; +import com.darass.darass.project.dto.ProjectCreateRequest; +import com.darass.darass.project.dto.ProjectResponse; import com.darass.darass.project.service.ProjectService; import com.darass.darass.user.domain.User; +import java.util.List; +import javax.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import javax.validation.Valid; -import java.util.List; +import org.springframework.web.bind.annotation.DeleteMapping; +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.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; -@RestController -@RequestMapping("/api/v1/projects") @RequiredArgsConstructor -@Validated +@RequestMapping("/api/v1/projects") +@RestController public class ProjectController { private final ProjectService projectService; @PostMapping - public ResponseEntity save(@Valid @RequestBody ProjectCreateRequest projectRequest, @RequiredLogin User user) { + public ResponseEntity save(@Valid @RequestBody ProjectCreateRequest projectRequest, + @RequiredLogin User user) { ProjectResponse projectResponse = projectService.save(projectRequest, user, new RandomSecretKeyFactory()); return ResponseEntity.status(HttpStatus.CREATED).body(projectResponse); } @@ -40,9 +45,10 @@ public ResponseEntity findById(@PathVariable("id") Long project ProjectResponse projectResponse = projectService.findByIdAndUserId(projectId, user.getId()); return ResponseEntity.ok(projectResponse); } + @GetMapping("/user-id") public ResponseEntity findUserIdBySecretKey(@RequestParam("secretKey") String secretKey) { - ProjectResponse projectResponse = projectService.findUserIdBySecretKey(secretKey); + ProjectResponse projectResponse = projectService.findUserIdBySecretKey(secretKey); return ResponseEntity.ok(projectResponse); } diff --git a/backend/src/main/java/com/darass/darass/project/domain/Project.java b/backend/src/main/java/com/darass/darass/project/domain/Project.java index 7687bdffe..c97311a2b 100644 --- a/backend/src/main/java/com/darass/darass/project/domain/Project.java +++ b/backend/src/main/java/com/darass/darass/project/domain/Project.java @@ -1,13 +1,7 @@ package com.darass.darass.project.domain; -import static javax.persistence.CascadeType.ALL; -import static javax.persistence.FetchType.LAZY; - -import com.darass.darass.comment.domain.Comment; import com.darass.darass.common.domain.BaseTimeEntity; import com.darass.darass.user.domain.User; -import java.util.ArrayList; -import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -15,7 +9,6 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; @@ -24,7 +17,6 @@ import lombok.NoArgsConstructor; -@Entity @NoArgsConstructor @Getter @Table(uniqueConstraints = { @@ -32,15 +24,9 @@ name = "SECRET_KEY_UNIQUE", columnNames = {"secretKey"} )}) +@Entity public class Project extends BaseTimeEntity { - private static final int ASCII_CODE_OF_0 = 48; - private static final int ASCII_CODE_OF_z = 122; - private static final int TARGET_STRING_LENGTH = 10; - private static final int ASCII_CODE_OF_9 = 57; - private static final int ASCII_CODE_OF_A = 65; - private static final int ASCII_CODE_OF_Z = 90; - private static final int ASCII_CODE_OF_a = 97; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; diff --git a/backend/src/main/java/com/darass/darass/project/domain/RandomSecretKeyFactory.java b/backend/src/main/java/com/darass/darass/project/domain/RandomSecretKeyFactory.java index 203999b5b..2b899b72e 100644 --- a/backend/src/main/java/com/darass/darass/project/domain/RandomSecretKeyFactory.java +++ b/backend/src/main/java/com/darass/darass/project/domain/RandomSecretKeyFactory.java @@ -2,7 +2,8 @@ import java.util.Random; -public class RandomSecretKeyFactory implements SecretKeyFactory{ +public class RandomSecretKeyFactory implements SecretKeyFactory { + private static final int ASCII_CODE_OF_0 = 48; private static final int ASCII_CODE_OF_z = 122; private static final int TARGET_STRING_LENGTH = 15; diff --git a/backend/src/main/java/com/darass/darass/project/domain/SecretKeyFactory.java b/backend/src/main/java/com/darass/darass/project/domain/SecretKeyFactory.java index bfd11355b..b656b1a8b 100644 --- a/backend/src/main/java/com/darass/darass/project/domain/SecretKeyFactory.java +++ b/backend/src/main/java/com/darass/darass/project/domain/SecretKeyFactory.java @@ -1,7 +1,6 @@ package com.darass.darass.project.domain; -import java.util.Random; - public interface SecretKeyFactory { + String createSecretKey(); } diff --git a/backend/src/main/java/com/darass/darass/project/controller/dto/ProjectCreateRequest.java b/backend/src/main/java/com/darass/darass/project/dto/ProjectCreateRequest.java similarity index 83% rename from backend/src/main/java/com/darass/darass/project/controller/dto/ProjectCreateRequest.java rename to backend/src/main/java/com/darass/darass/project/dto/ProjectCreateRequest.java index d5dbb3d47..e0852e2e0 100644 --- a/backend/src/main/java/com/darass/darass/project/controller/dto/ProjectCreateRequest.java +++ b/backend/src/main/java/com/darass/darass/project/dto/ProjectCreateRequest.java @@ -1,13 +1,12 @@ -package com.darass.darass.project.controller.dto; +package com.darass.darass.project.dto; +import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; -import javax.validation.constraints.NotNull; - -@NoArgsConstructor @Getter +@NoArgsConstructor @AllArgsConstructor public class ProjectCreateRequest { diff --git a/backend/src/main/java/com/darass/darass/project/controller/dto/ProjectResponse.java b/backend/src/main/java/com/darass/darass/project/dto/ProjectResponse.java similarity index 78% rename from backend/src/main/java/com/darass/darass/project/controller/dto/ProjectResponse.java rename to backend/src/main/java/com/darass/darass/project/dto/ProjectResponse.java index 75a2d0f17..8f249e553 100644 --- a/backend/src/main/java/com/darass/darass/project/controller/dto/ProjectResponse.java +++ b/backend/src/main/java/com/darass/darass/project/dto/ProjectResponse.java @@ -1,4 +1,4 @@ -package com.darass.darass.project.controller.dto; +package com.darass.darass.project.dto; import com.darass.darass.project.domain.Project; import lombok.AllArgsConstructor; @@ -11,19 +11,22 @@ public class ProjectResponse { private Long id; + private String name; + private String secretKey; + private Long userId; public ProjectResponse(Long userId) { this.userId = userId; } - public static ProjectResponse of(Project project) { + public static ProjectResponse from(Project project) { return new ProjectResponse(project.getId(), project.getName(), project.getSecretKey(), null); } - public static ProjectResponse of(Long userId){ + public static ProjectResponse from(Long userId) { return new ProjectResponse(userId); } } diff --git a/backend/src/main/java/com/darass/darass/project/repository/ProjectRepository.java b/backend/src/main/java/com/darass/darass/project/repository/ProjectRepository.java index 3fbfa49dc..dce732ba7 100644 --- a/backend/src/main/java/com/darass/darass/project/repository/ProjectRepository.java +++ b/backend/src/main/java/com/darass/darass/project/repository/ProjectRepository.java @@ -1,16 +1,16 @@ package com.darass.darass.project.repository; -import com.darass.darass.project.controller.dto.ProjectResponse; import com.darass.darass.project.domain.Project; -import org.springframework.data.jpa.repository.JpaRepository; - +import com.darass.darass.project.dto.ProjectResponse; import java.util.List; import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; public interface ProjectRepository extends JpaRepository { + Optional findBySecretKey(String projectSecretKey); - List findByUserId(Long userId); + List findByUserId(Long userId); //TODO: List 반환하도록 수정 Optional findByIdAndUserId(Long projectId, Long userId); diff --git a/backend/src/main/java/com/darass/darass/project/service/ProjectService.java b/backend/src/main/java/com/darass/darass/project/service/ProjectService.java index 4c27c6f86..2672650a6 100644 --- a/backend/src/main/java/com/darass/darass/project/service/ProjectService.java +++ b/backend/src/main/java/com/darass/darass/project/service/ProjectService.java @@ -1,10 +1,10 @@ package com.darass.darass.project.service; import com.darass.darass.exception.ExceptionWithMessageAndCode; -import com.darass.darass.project.controller.dto.ProjectCreateRequest; -import com.darass.darass.project.controller.dto.ProjectResponse; import com.darass.darass.project.domain.Project; import com.darass.darass.project.domain.SecretKeyFactory; +import com.darass.darass.project.dto.ProjectCreateRequest; +import com.darass.darass.project.dto.ProjectResponse; import com.darass.darass.project.repository.ProjectRepository; import com.darass.darass.user.domain.User; import java.util.List; @@ -14,12 +14,12 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -@Service -@Transactional @RequiredArgsConstructor +@Transactional +@Service public class ProjectService { - private final ProjectRepository projects; + private final ProjectRepository projectRepository; public ProjectResponse save(ProjectCreateRequest projectRequest, User user, SecretKeyFactory secretKeyFactory) { validateDuplicateProjectName(projectRequest, user); @@ -28,19 +28,20 @@ public ProjectResponse save(ProjectCreateRequest projectRequest, User user, Secr .secretKeyFactory(secretKeyFactory) .user(user) .build(); + try { - projects.save(project); + projectRepository.save(project); } catch (DataIntegrityViolationException e) { if (e.getLocalizedMessage().contains("SECRET_KEY_UNIQUE")) { throw ExceptionWithMessageAndCode.DUPLICATE_PROJECT_SECRET_KEY.getException(); } throw ExceptionWithMessageAndCode.INTERNAL_SERVER.getException(); } - return ProjectResponse.of(project); + return ProjectResponse.from(project); } private void validateDuplicateProjectName(ProjectCreateRequest projectRequest, User user) { - Optional possibleProject = projects + Optional possibleProject = projectRepository .findByNameAndUserId(projectRequest.getName(), user.getId()); possibleProject.ifPresent(project -> { throw ExceptionWithMessageAndCode.DUPLICATE_PROJECT_NAME.getException(); @@ -48,27 +49,27 @@ private void validateDuplicateProjectName(ProjectCreateRequest projectRequest, U } public List findByUserId(Long id) { - return projects.findByUserId(id); + return projectRepository.findByUserId(id); } public ProjectResponse findByIdAndUserId(Long projectId, Long userId) { - Project project = projects.findByIdAndUserId(projectId, userId) + Project project = projectRepository.findByIdAndUserId(projectId, userId) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_PROJECT::getException); - return ProjectResponse.of(project); + return ProjectResponse.from(project); } public void deleteByIdAndUserId(Long projectId, Long userId) { - if (!projects.existsByIdAndUserId(projectId, userId)) { + if (!projectRepository.existsByIdAndUserId(projectId, userId)) { throw ExceptionWithMessageAndCode.NOT_FOUND_PROJECT.getException(); } - projects.deleteByIdAndUserId(projectId, userId); + projectRepository.deleteByIdAndUserId(projectId, userId); } public ProjectResponse findUserIdBySecretKey(String secretKey) { - Optional expectedProject = projects.findBySecretKey(secretKey); + Optional expectedProject = projectRepository.findBySecretKey(secretKey); Project project = expectedProject.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_PROJECT::getException); - return ProjectResponse.of(project.getUser().getId()); + return ProjectResponse.from(project.getUser().getId()); } } diff --git a/backend/src/main/java/com/darass/darass/user/controller/UserController.java b/backend/src/main/java/com/darass/darass/user/controller/UserController.java index 285915265..03b249e49 100644 --- a/backend/src/main/java/com/darass/darass/user/controller/UserController.java +++ b/backend/src/main/java/com/darass/darass/user/controller/UserController.java @@ -1,22 +1,26 @@ package com.darass.darass.user.controller; import com.darass.darass.auth.oauth.domain.RequiredLogin; -import com.darass.darass.comment.controller.dto.UserResponse; -import com.darass.darass.user.controller.dto.PasswordCheckRequest; -import com.darass.darass.user.controller.dto.PasswordCheckResponse; -import com.darass.darass.user.controller.dto.UserUpdateRequest; +import com.darass.darass.user.dto.PasswordCheckRequest; +import com.darass.darass.user.dto.PasswordCheckResponse; import com.darass.darass.user.domain.User; +import com.darass.darass.user.dto.UserResponse; +import com.darass.darass.user.dto.UserUpdateRequest; import com.darass.darass.user.service.UserService; import javax.validation.Valid; import lombok.AllArgsConstructor; import org.springframework.http.ResponseEntity; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; -@RestController -@RequestMapping("/api/v1/users") @AllArgsConstructor -@Validated +@RequestMapping("/api/v1/users") +@RestController public class UserController { private final UserService userService; @@ -28,7 +32,8 @@ public ResponseEntity find(@RequiredLogin User user) { } @PatchMapping - public ResponseEntity updateNickname(@RequiredLogin User user, @Valid @RequestBody UserUpdateRequest userUpdateRequest) { + public ResponseEntity updateNickname(@RequiredLogin User user, + @Valid @RequestBody UserUpdateRequest userUpdateRequest) { UserResponse userResponse = userService.updateNickName(user.getId(), userUpdateRequest); return ResponseEntity.ok(userResponse); } @@ -40,7 +45,8 @@ public ResponseEntity delete(@RequiredLogin User user) { } @GetMapping("/check-password") - public ResponseEntity checkGuestUserPassword(@ModelAttribute PasswordCheckRequest passwordCheckRequest) { + public ResponseEntity checkGuestUserPassword( + @ModelAttribute PasswordCheckRequest passwordCheckRequest) { PasswordCheckResponse passwordCheckResponse = userService.checkGuestUserPassword(passwordCheckRequest); return ResponseEntity.ok(passwordCheckResponse); } diff --git a/backend/src/main/java/com/darass/darass/user/domain/GuestUser.java b/backend/src/main/java/com/darass/darass/user/domain/GuestUser.java index a33164eaa..b42b5111a 100644 --- a/backend/src/main/java/com/darass/darass/user/domain/GuestUser.java +++ b/backend/src/main/java/com/darass/darass/user/domain/GuestUser.java @@ -1,11 +1,10 @@ package com.darass.darass.user.domain; +import javax.persistence.Entity; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; -import javax.persistence.Entity; - @NoArgsConstructor @Getter @Entity @@ -20,7 +19,7 @@ private GuestUser(String nickName, String password) { } @Override - public String getProfileImageUrl(){ + public String getProfileImageUrl() { return "guestProfileImageUrl"; } diff --git a/backend/src/main/java/com/darass/darass/user/domain/SocialLoginUser.java b/backend/src/main/java/com/darass/darass/user/domain/SocialLoginUser.java index 9554db246..6a4bef0c4 100644 --- a/backend/src/main/java/com/darass/darass/user/domain/SocialLoginUser.java +++ b/backend/src/main/java/com/darass/darass/user/domain/SocialLoginUser.java @@ -8,9 +8,9 @@ import lombok.Getter; import lombok.NoArgsConstructor; +@Getter @NoArgsConstructor @Entity -@Getter public class SocialLoginUser extends User { private String email; diff --git a/backend/src/main/java/com/darass/darass/user/domain/User.java b/backend/src/main/java/com/darass/darass/user/domain/User.java index 65ccdd5a7..5470c726f 100644 --- a/backend/src/main/java/com/darass/darass/user/domain/User.java +++ b/backend/src/main/java/com/darass/darass/user/domain/User.java @@ -5,7 +5,6 @@ import com.darass.darass.comment.domain.Comment; import com.darass.darass.common.domain.BaseTimeEntity; -import com.darass.darass.project.domain.Project; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; @@ -20,29 +19,25 @@ import lombok.Getter; import lombok.NoArgsConstructor; -@Entity -@Inheritance(strategy = InheritanceType.JOINED) -@DiscriminatorColumn(name = "user_type") @Getter @NoArgsConstructor +@Inheritance(strategy = InheritanceType.JOINED) +@DiscriminatorColumn(name = "user_type") +@Entity public abstract class User extends BaseTimeEntity { + @OneToMany(mappedBy = "user", fetch = LAZY, cascade = ALL, orphanRemoval = true) + private final List comments = new ArrayList<>(); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @Column(nullable = false) private String nickName; - @Column private String profileImageUrl; - @Column(name = "user_type", insertable = false, updatable = false) private String userType; - @OneToMany(mappedBy = "user", fetch = LAZY, cascade = ALL, orphanRemoval = true) - private List comments = new ArrayList<>(); - public User(String nickName) { this.nickName = nickName; } diff --git a/backend/src/main/java/com/darass/darass/user/controller/dto/PasswordCheckRequest.java b/backend/src/main/java/com/darass/darass/user/dto/PasswordCheckRequest.java similarity index 72% rename from backend/src/main/java/com/darass/darass/user/controller/dto/PasswordCheckRequest.java rename to backend/src/main/java/com/darass/darass/user/dto/PasswordCheckRequest.java index 47a7c060d..4c0300760 100644 --- a/backend/src/main/java/com/darass/darass/user/controller/dto/PasswordCheckRequest.java +++ b/backend/src/main/java/com/darass/darass/user/dto/PasswordCheckRequest.java @@ -1,11 +1,8 @@ -package com.darass.darass.user.controller.dto; +package com.darass.darass.user.dto; +import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import javax.validation.constraints.NotNull; @Getter @AllArgsConstructor diff --git a/backend/src/main/java/com/darass/darass/user/controller/dto/PasswordCheckResponse.java b/backend/src/main/java/com/darass/darass/user/dto/PasswordCheckResponse.java similarity index 82% rename from backend/src/main/java/com/darass/darass/user/controller/dto/PasswordCheckResponse.java rename to backend/src/main/java/com/darass/darass/user/dto/PasswordCheckResponse.java index 4892d240d..17b0b0a71 100644 --- a/backend/src/main/java/com/darass/darass/user/controller/dto/PasswordCheckResponse.java +++ b/backend/src/main/java/com/darass/darass/user/dto/PasswordCheckResponse.java @@ -1,4 +1,4 @@ -package com.darass.darass.user.controller.dto; +package com.darass.darass.user.dto; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/backend/src/main/java/com/darass/darass/comment/controller/dto/UserResponse.java b/backend/src/main/java/com/darass/darass/user/dto/UserResponse.java similarity index 81% rename from backend/src/main/java/com/darass/darass/comment/controller/dto/UserResponse.java rename to backend/src/main/java/com/darass/darass/user/dto/UserResponse.java index cb24575df..bfc763378 100644 --- a/backend/src/main/java/com/darass/darass/comment/controller/dto/UserResponse.java +++ b/backend/src/main/java/com/darass/darass/user/dto/UserResponse.java @@ -1,16 +1,15 @@ -package com.darass.darass.comment.controller.dto; +package com.darass.darass.user.dto; import com.darass.darass.user.domain.User; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import java.time.LocalDateTime; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; -@AllArgsConstructor @Getter +@AllArgsConstructor @NoArgsConstructor public class UserResponse { @@ -29,6 +28,7 @@ public class UserResponse { private LocalDateTime modifiedDate; public static UserResponse of(User user, String type, String profileImageUrl) { - return new UserResponse(user.getId(), user.getNickName(), type, profileImageUrl, user.getCreatedDate(), user.getModifiedDate()); + return new UserResponse(user.getId(), user.getNickName(), type, profileImageUrl, user.getCreatedDate(), + user.getModifiedDate()); } } diff --git a/backend/src/main/java/com/darass/darass/user/controller/dto/UserUpdateRequest.java b/backend/src/main/java/com/darass/darass/user/dto/UserUpdateRequest.java similarity index 84% rename from backend/src/main/java/com/darass/darass/user/controller/dto/UserUpdateRequest.java rename to backend/src/main/java/com/darass/darass/user/dto/UserUpdateRequest.java index 88fd47706..4b487b177 100644 --- a/backend/src/main/java/com/darass/darass/user/controller/dto/UserUpdateRequest.java +++ b/backend/src/main/java/com/darass/darass/user/dto/UserUpdateRequest.java @@ -1,4 +1,4 @@ -package com.darass.darass.user.controller.dto; +package com.darass.darass.user.dto; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; diff --git a/backend/src/main/java/com/darass/darass/user/repository/SocialLoginUserRepository.java b/backend/src/main/java/com/darass/darass/user/repository/SocialLoginUserRepository.java index edbad50ae..75dc1971f 100644 --- a/backend/src/main/java/com/darass/darass/user/repository/SocialLoginUserRepository.java +++ b/backend/src/main/java/com/darass/darass/user/repository/SocialLoginUserRepository.java @@ -1,9 +1,8 @@ package com.darass.darass.user.repository; import com.darass.darass.user.domain.SocialLoginUser; -import org.springframework.data.jpa.repository.JpaRepository; - import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; public interface SocialLoginUserRepository extends JpaRepository { diff --git a/backend/src/main/java/com/darass/darass/user/service/UserService.java b/backend/src/main/java/com/darass/darass/user/service/UserService.java index b4aade63d..0cc089438 100644 --- a/backend/src/main/java/com/darass/darass/user/service/UserService.java +++ b/backend/src/main/java/com/darass/darass/user/service/UserService.java @@ -1,33 +1,32 @@ package com.darass.darass.user.service; -import com.darass.darass.comment.controller.dto.UserResponse; import com.darass.darass.exception.ExceptionWithMessageAndCode; -import com.darass.darass.user.controller.dto.PasswordCheckRequest; -import com.darass.darass.user.controller.dto.PasswordCheckResponse; -import com.darass.darass.user.controller.dto.UserUpdateRequest; +import com.darass.darass.user.dto.PasswordCheckRequest; +import com.darass.darass.user.dto.PasswordCheckResponse; import com.darass.darass.user.domain.User; +import com.darass.darass.user.dto.UserResponse; +import com.darass.darass.user.dto.UserUpdateRequest; import com.darass.darass.user.repository.UserRepository; import java.util.Optional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -@Service -@Transactional @RequiredArgsConstructor +@Transactional +@Service public class UserService { - private final UserRepository users; + private final UserRepository userRepository; public UserResponse findById(Long id) { - Optional possibleUser = users.findById(id); + Optional possibleUser = userRepository.findById(id); User user = possibleUser.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_USER::getException); - return UserResponse.of(user, user.getUserType(), user.getProfileImageUrl()); } public UserResponse updateNickName(Long id, UserUpdateRequest userUpdateRequest) { - Optional expectedUser = users.findById(id); + Optional expectedUser = userRepository.findById(id); User user = expectedUser.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_USER::getException); user.changeNickName(userUpdateRequest.getNickName()); @@ -35,11 +34,11 @@ public UserResponse updateNickName(Long id, UserUpdateRequest userUpdateRequest) } public void deleteById(Long id) { - users.deleteById(id); + userRepository.deleteById(id); } public PasswordCheckResponse checkGuestUserPassword(PasswordCheckRequest passwordCheckRequest) { - Optional expectedUser = users.findById(passwordCheckRequest.getGuestUserId()); + Optional expectedUser = userRepository.findById(passwordCheckRequest.getGuestUserId()); User user = expectedUser.orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_USER::getException); if (user.isValidGuestPassword(passwordCheckRequest.getGuestUserPassword())) { diff --git a/backend/src/main/resources/logback-access.xml b/backend/src/main/resources/logback-access.xml index 01c8bbd47..912682dd7 100644 --- a/backend/src/main/resources/logback-access.xml +++ b/backend/src/main/resources/logback-access.xml @@ -1,17 +1,17 @@ - - - /var/log/application-logs/%d{yyyyMM}/%d{yyyy-MM-dd-HH}.access.log - 6 - 5GB - - + %n###### HTTP Request ######%n%fullRequest%n###### HTTP Response ######%n%fullResponse%n%n + + + /var/log/application-logs/%d{yyyyMM}/%d{yyyy-MM-dd-HH}.access.log + 6 + 5GB + diff --git a/backend/src/main/resources/logback.xml b/backend/src/main/resources/logback.xml index 55d3f348c..6562b32ea 100644 --- a/backend/src/main/resources/logback.xml +++ b/backend/src/main/resources/logback.xml @@ -1,6 +1,6 @@ - + %green(%d{yyyy-MM-dd HH:mm:ss.SSS}) [%thread] %highlight([%level]) %logger - %cyan(%msg%n) @@ -9,26 +9,32 @@ - + - + + + UTF-8 + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%level] %logger - %msg%n + + /var/log/application-logs/%d{yyyyMM}/%d{yyyy-MM-dd}.log 6 5GB + + + + UTF-8 %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%level] %logger - %msg%n - UTF-8 - - - ERROR ACCEPT @@ -39,17 +45,11 @@ 6 5GB - - - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%level] %logger - %msg%n - - UTF-8 - - - + + \ No newline at end of file diff --git a/backend/src/test/java/com/darass/darass/auth/oauth/acceptance/AuthAcceptanceTest.java b/backend/src/test/java/com/darass/darass/auth/oauth/acceptance/AuthAcceptanceTest.java index 1808c8a57..b63efb9a9 100644 --- a/backend/src/test/java/com/darass/darass/auth/oauth/acceptance/AuthAcceptanceTest.java +++ b/backend/src/test/java/com/darass/darass/auth/oauth/acceptance/AuthAcceptanceTest.java @@ -12,7 +12,7 @@ import com.darass.darass.AcceptanceTest; import com.darass.darass.auth.oauth.api.domain.UserInfoProvider; -import com.darass.darass.auth.oauth.controller.dto.TokenResponse; +import com.darass.darass.auth.oauth.dto.TokenResponse; import com.darass.darass.auth.oauth.infrastructure.JwtTokenProvider; import com.darass.darass.auth.oauth.service.OAuthService; import com.darass.darass.exception.ExceptionWithMessageAndCode; @@ -79,7 +79,8 @@ public void login_success() throws Exception { @DisplayName("올바르지 않은 oauth2 토큰을 보낼 경우 로그인을 실패하고 JWT 토큰을 발급 받지 못한다.") public void login_fail() throws Exception { // given - given(userInfoProvider.findSocialLoginUser(oauthAccessToken)).willThrow(ExceptionWithMessageAndCode.INVALID_JWT_TOKEN.getException()); + given(userInfoProvider.findSocialLoginUser(oauthAccessToken)) + .willThrow(ExceptionWithMessageAndCode.INVALID_JWT_TOKEN.getException()); // when ResultActions resultActions = 토큰_발급_요청(oauthAccessToken); diff --git a/backend/src/test/java/com/darass/darass/auth/oauth/api/domain/UserInfoProviderTest.java b/backend/src/test/java/com/darass/darass/auth/oauth/api/domain/UserInfoProviderTest.java index 8af967b3f..605bdd0ef 100644 --- a/backend/src/test/java/com/darass/darass/auth/oauth/api/domain/UserInfoProviderTest.java +++ b/backend/src/test/java/com/darass/darass/auth/oauth/api/domain/UserInfoProviderTest.java @@ -15,7 +15,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Isolated; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.http.MediaType; @@ -49,7 +48,7 @@ void findSocialLoginUser() throws JsonProcessingException { assertThat(socialLoginUser.getNickName()).isEqualTo(profile.getNickname()); assertThat(socialLoginUser.getEmail()).isEqualTo(kaKaoAccount.getEmail()); - assertThat(socialLoginUser.getProfileImageUrl()).isEqualTo(profile.getThumbnail_image_url()); + assertThat(socialLoginUser.getProfileImageUrl()).isEqualTo(profile.getThumbnailImageUrl()); } diff --git a/backend/src/test/java/com/darass/darass/auth/oauth/infrastructure/AuthorizationExtractorTest.java b/backend/src/test/java/com/darass/darass/auth/oauth/infrastructure/AuthorizationExtractorTest.java index b472c9298..4a5ee76b1 100644 --- a/backend/src/test/java/com/darass/darass/auth/oauth/infrastructure/AuthorizationExtractorTest.java +++ b/backend/src/test/java/com/darass/darass/auth/oauth/infrastructure/AuthorizationExtractorTest.java @@ -1,13 +1,11 @@ package com.darass.darass.auth.oauth.infrastructure; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.parallel.ExecutionMode.CONCURRENT; import com.darass.darass.SpringContainerTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; import org.springframework.mock.web.MockHttpServletRequest; @DisplayName("AuthorizationExtractor 클래스") @@ -37,7 +35,8 @@ void extract_success1() { @DisplayName("extract 메서드는 엑세스 토큰 뒤에 추가 정보가 콤마를 기준으로 붙어 있는 Authorization 헤더를 가지는 httpServletRequest가 주어진다면, 엑세스 토큰을 파싱헤서 반환한다.") @Test void extract_success2() { - mockHttpServletRequest.addHeader("authorization", bearerAuthType + accessToken + ", Basic YXNkZnNhZGZzYWRmOlZLdDVOMVhk"); + mockHttpServletRequest + .addHeader("authorization", bearerAuthType + accessToken + ", Basic YXNkZnNhZGZzYWRmOlZLdDVOMVhk"); AuthorizationExtractor authorizationExtractor = new AuthorizationExtractor(); assertThat(AuthorizationExtractor.extract(mockHttpServletRequest)).isEqualTo(accessToken); diff --git a/backend/src/test/java/com/darass/darass/auth/oauth/service/OAuthServiceTest.java b/backend/src/test/java/com/darass/darass/auth/oauth/service/OAuthServiceTest.java index 388ebc8c0..491d2a142 100644 --- a/backend/src/test/java/com/darass/darass/auth/oauth/service/OAuthServiceTest.java +++ b/backend/src/test/java/com/darass/darass/auth/oauth/service/OAuthServiceTest.java @@ -5,7 +5,7 @@ import com.darass.darass.SpringContainerTest; import com.darass.darass.auth.oauth.api.domain.UserInfoProvider; -import com.darass.darass.auth.oauth.controller.dto.TokenResponse; +import com.darass.darass.auth.oauth.dto.TokenResponse; import com.darass.darass.auth.oauth.infrastructure.JwtTokenProvider; import com.darass.darass.user.domain.OAuthPlatform; import com.darass.darass.user.domain.SocialLoginUser; diff --git a/backend/src/test/java/com/darass/darass/comment/acceptance/CommentAcceptanceTest.java b/backend/src/test/java/com/darass/darass/comment/acceptance/CommentAcceptanceTest.java index d9617bbe9..fc29f13db 100644 --- a/backend/src/test/java/com/darass/darass/comment/acceptance/CommentAcceptanceTest.java +++ b/backend/src/test/java/com/darass/darass/comment/acceptance/CommentAcceptanceTest.java @@ -1,16 +1,34 @@ package com.darass.darass.comment.acceptance; +import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; +import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.relaxedRequestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.relaxedResponseFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; +import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.darass.darass.AcceptanceTest; import com.darass.darass.auth.oauth.infrastructure.JwtTokenProvider; -import com.darass.darass.comment.controller.dto.CommentCreateRequest; -import com.darass.darass.comment.controller.dto.CommentResponse; -import com.darass.darass.comment.controller.dto.CommentUpdateRequest; -import com.darass.darass.comment.controller.dto.UserResponse; +import com.darass.darass.comment.dto.CommentCreateRequest; +import com.darass.darass.comment.dto.CommentResponse; +import com.darass.darass.comment.dto.CommentUpdateRequest; import com.darass.darass.project.domain.Project; import com.darass.darass.project.domain.RandomSecretKeyFactory; import com.darass.darass.project.repository.ProjectRepository; import com.darass.darass.user.domain.OAuthPlatform; import com.darass.darass.user.domain.SocialLoginUser; +import com.darass.darass.user.dto.UserResponse; import com.darass.darass.user.repository.UserRepository; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; @@ -21,15 +39,6 @@ import org.springframework.restdocs.payload.JsonFieldType; import org.springframework.test.web.servlet.ResultActions; -import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; -import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; -import static org.springframework.restdocs.payload.PayloadDocumentation.*; -import static org.springframework.restdocs.request.RequestDocumentation.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @DisplayName("Comment 인수 테스트") public class CommentAcceptanceTest extends AcceptanceTest { @@ -46,23 +55,23 @@ public class CommentAcceptanceTest extends AcceptanceTest { private void setUpProject() { project = Project.builder() - .name("project") - .secretKeyFactory(new RandomSecretKeyFactory()) - .user(socialLoginUser) - .build(); + .name("project") + .secretKeyFactory(new RandomSecretKeyFactory()) + .user(socialLoginUser) + .build(); projects.save(project); secretKey = project.getSecretKey(); } private void setUpUser() { socialLoginUser = SocialLoginUser - .builder() - .nickName("nickname") - .oauthId("abc13gag") - .oauthPlatform(OAuthPlatform.KAKAO) - .email("qkrwotjd1445@naver.com") - .profileImageUrl("https://imageUrl") - .build(); + .builder() + .nickName("nickname") + .oauthId("abc13gag") + .oauthPlatform(OAuthPlatform.KAKAO) + .email("qkrwotjd1445@naver.com") + .profileImageUrl("https://imageUrl") + .build(); users.save(socialLoginUser); token = jwtTokenProvider.createAccessToken(socialLoginUser.getId().toString()); } @@ -108,26 +117,26 @@ void saveLoginUser() throws Exception { @DisplayName("/api/v1/comments POST - 성공 (비로그인 유저)") void saveGuestUser() throws Exception { 비로그인_댓글_등록됨("content", "url").andDo( - document("api/v1/comments/post/success-guest-user", - requestFields( - fieldWithPath("guestNickName").type(JsonFieldType.STRING).description("비로그인 유저 닉네입"), - fieldWithPath("guestPassword").type(JsonFieldType.STRING).description("비로그인 유저 비밀번호"), - fieldWithPath("projectSecretKey").type(JsonFieldType.STRING).description("프로젝트 시크릿 키"), - fieldWithPath("content").type(JsonFieldType.STRING).description("댓글 내용"), - fieldWithPath("url").type(JsonFieldType.STRING).description("url") - ), - relaxedResponseFields( - fieldWithPath("id").type(JsonFieldType.NUMBER).description("댓글 id"), - fieldWithPath("content").type(JsonFieldType.STRING).description("댓글 내용"), - fieldWithPath("createdDate").type(JsonFieldType.STRING).description("댓글 생성 시점"), - fieldWithPath("modifiedDate").type(JsonFieldType.STRING).description("댓글 수정 시점"), - fieldWithPath("user").type(JsonFieldType.OBJECT).description("댓글 작성 유저 정보"), - fieldWithPath("user.id").type(JsonFieldType.NUMBER).description("유저 id"), - fieldWithPath("user.createdDate").type(JsonFieldType.STRING).description("유저 생성 시점"), - fieldWithPath("user.modifiedDate").type(JsonFieldType.STRING).description("유저 수정 시점"), - fieldWithPath("user.nickName").type(JsonFieldType.STRING).description("유저 닉네임"), - fieldWithPath("user.type").type(JsonFieldType.STRING).description("유저 유형") - )) + document("api/v1/comments/post/success-guest-user", + requestFields( + fieldWithPath("guestNickName").type(JsonFieldType.STRING).description("비로그인 유저 닉네입"), + fieldWithPath("guestPassword").type(JsonFieldType.STRING).description("비로그인 유저 비밀번호"), + fieldWithPath("projectSecretKey").type(JsonFieldType.STRING).description("프로젝트 시크릿 키"), + fieldWithPath("content").type(JsonFieldType.STRING).description("댓글 내용"), + fieldWithPath("url").type(JsonFieldType.STRING).description("url") + ), + relaxedResponseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("댓글 id"), + fieldWithPath("content").type(JsonFieldType.STRING).description("댓글 내용"), + fieldWithPath("createdDate").type(JsonFieldType.STRING).description("댓글 생성 시점"), + fieldWithPath("modifiedDate").type(JsonFieldType.STRING).description("댓글 수정 시점"), + fieldWithPath("user").type(JsonFieldType.OBJECT).description("댓글 작성 유저 정보"), + fieldWithPath("user.id").type(JsonFieldType.NUMBER).description("유저 id"), + fieldWithPath("user.createdDate").type(JsonFieldType.STRING).description("유저 생성 시점"), + fieldWithPath("user.modifiedDate").type(JsonFieldType.STRING).description("유저 수정 시점"), + fieldWithPath("user.nickName").type(JsonFieldType.STRING).description("유저 닉네임"), + fieldWithPath("user.type").type(JsonFieldType.STRING).description("유저 유형") + )) ); } @@ -135,17 +144,17 @@ void saveGuestUser() throws Exception { @DisplayName("/api/v1/comments POST - 프로젝트 시크릿 키 존재하지 않는 경우") void saveWithInvalidSecretKey() throws Exception { mockMvc.perform(post("/api/v1/comments") - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(new CommentCreateRequest("guest", "password", "invalidKey", "content", "url")))) - .andExpect(status().isNotFound()) - .andExpect(jsonPath("$.code").value(700)) - .andDo( - document("api/v1/comments/post/fail-missing-project-key", - responseFields( - fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), - fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") - )) - ); + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(new CommentCreateRequest("guest", "password", "invalidKey", "content", "url")))) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.code").value(700)) + .andDo( + document("api/v1/comments/post/fail-missing-project-key", + responseFields( + fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), + fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") + )) + ); } @Test @@ -155,29 +164,29 @@ void read() throws Exception { 소셜_로그인_댓글_등록됨("content2", "url"); mockMvc.perform(get("/api/v1/comments") - .contentType(MediaType.APPLICATION_JSON) - .param("url", "url") - .param("projectKey", secretKey)) - .andExpect(status().isOk()) - .andDo(document("api/v1/comments/get/success", - requestParameters( - parameterWithName("url").description("조회 url"), - parameterWithName("projectKey").description("프로젝트 시크릿 키") - ), - responseFields( - fieldWithPath("[].createdDate").type(JsonFieldType.STRING).description("댓글 생성 시점"), - fieldWithPath("[].modifiedDate").type(JsonFieldType.STRING).description("댓글 수정 시점"), - fieldWithPath("[].id").type(JsonFieldType.NUMBER).description("댓글 id"), - fieldWithPath("[].content").type(JsonFieldType.STRING).description("댓글 내용"), - fieldWithPath("[].user").type(JsonFieldType.OBJECT).description("댓글 작성 유저 정보"), - fieldWithPath("[].user.createdDate").type(JsonFieldType.STRING).description("유저 생성 시점"), - fieldWithPath("[].user.modifiedDate").type(JsonFieldType.STRING).description("유저 수정 시점"), - fieldWithPath("[].user.id").type(JsonFieldType.NUMBER).description("유저 id"), - fieldWithPath("[].user.nickName").type(JsonFieldType.STRING).description("유저 닉네임"), - fieldWithPath("[].user.type").type(JsonFieldType.STRING).description("유저 타입"), - fieldWithPath("[].user.profileImageUrl").type(JsonFieldType.STRING).description("유저 프로필 이미지") - ) - )); + .contentType(MediaType.APPLICATION_JSON) + .param("url", "url") + .param("projectKey", secretKey)) + .andExpect(status().isOk()) + .andDo(document("api/v1/comments/get/success", + requestParameters( + parameterWithName("url").description("조회 url"), + parameterWithName("projectKey").description("프로젝트 시크릿 키") + ), + responseFields( + fieldWithPath("[].createdDate").type(JsonFieldType.STRING).description("댓글 생성 시점"), + fieldWithPath("[].modifiedDate").type(JsonFieldType.STRING).description("댓글 수정 시점"), + fieldWithPath("[].id").type(JsonFieldType.NUMBER).description("댓글 id"), + fieldWithPath("[].content").type(JsonFieldType.STRING).description("댓글 내용"), + fieldWithPath("[].user").type(JsonFieldType.OBJECT).description("댓글 작성 유저 정보"), + fieldWithPath("[].user.createdDate").type(JsonFieldType.STRING).description("유저 생성 시점"), + fieldWithPath("[].user.modifiedDate").type(JsonFieldType.STRING).description("유저 수정 시점"), + fieldWithPath("[].user.id").type(JsonFieldType.NUMBER).description("유저 id"), + fieldWithPath("[].user.nickName").type(JsonFieldType.STRING).description("유저 닉네임"), + fieldWithPath("[].user.type").type(JsonFieldType.STRING).description("유저 타입"), + fieldWithPath("[].user.profileImageUrl").type(JsonFieldType.STRING).description("유저 프로필 이미지") + ) + )); } @Test @@ -187,22 +196,22 @@ void updateByLoginUser() throws Exception { Long commentId = commentResponse.getId(); mockMvc.perform(patch("/api/v1/comments/{id}", commentId) - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + token) - .content(asJsonString(new CommentUpdateRequest("updateContent"))) + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", "Bearer " + token) + .content(asJsonString(new CommentUpdateRequest("updateContent"))) ) - .andExpect(status().isNoContent()) - .andDo(document("api/v1/comments/patch/success-login-user", - requestHeaders( - headerWithName("Authorization").description("JWT - Bearer 토큰") - ), - pathParameters( - parameterWithName("id").description("수정할 댓글 id") - ), - relaxedRequestFields( - fieldWithPath("content").type(JsonFieldType.STRING).description("수정 내용") - ) - )); + .andExpect(status().isNoContent()) + .andDo(document("api/v1/comments/patch/success-login-user", + requestHeaders( + headerWithName("Authorization").description("JWT - Bearer 토큰") + ), + pathParameters( + parameterWithName("id").description("수정할 댓글 id") + ), + relaxedRequestFields( + fieldWithPath("content").type(JsonFieldType.STRING).description("수정 내용") + ) + )); } @Test @@ -213,19 +222,19 @@ void updateByGuestUser() throws Exception { Long commentId = commentResponse.getId(); mockMvc.perform(patch("/api/v1/comments/{id}", commentId) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(new CommentUpdateRequest(userResponse.getId(), "password", "updateContent")))) - .andExpect(status().isNoContent()) - .andDo(document("api/v1/comments/patch/success-guest-user", - pathParameters( - parameterWithName("id").description("수정할 댓글 id") - ), - requestFields( - fieldWithPath("guestUserId").type(JsonFieldType.NUMBER).description("비로그인 작성자 id"), - fieldWithPath("guestUserPassword").type(JsonFieldType.STRING).description("비로그인 작성자 비밀번호"), - fieldWithPath("content").type(JsonFieldType.STRING).description("수정 내용") - ) - )); + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(new CommentUpdateRequest(userResponse.getId(), "password", "updateContent")))) + .andExpect(status().isNoContent()) + .andDo(document("api/v1/comments/patch/success-guest-user", + pathParameters( + parameterWithName("id").description("수정할 댓글 id") + ), + requestFields( + fieldWithPath("guestUserId").type(JsonFieldType.NUMBER).description("비로그인 작성자 id"), + fieldWithPath("guestUserPassword").type(JsonFieldType.STRING).description("비로그인 작성자 비밀번호"), + fieldWithPath("content").type(JsonFieldType.STRING).description("수정 내용") + ) + )); } @Test @@ -236,17 +245,17 @@ void updateUnauthorized() throws Exception { Long commentId2 = commentResponse2.getId(); mockMvc.perform(patch("/api/v1/comments/{id}", commentId2) - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + token) - .content(asJsonString(new CommentUpdateRequest("updateContent")))) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.code").value(903)) - .andDo(document("api/v1/comments/patch/fail-not-mine", - responseFields( - fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), - fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") - ) - )); + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", "Bearer " + token) + .content(asJsonString(new CommentUpdateRequest("updateContent")))) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.code").value(903)) + .andDo(document("api/v1/comments/patch/fail-not-mine", + responseFields( + fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), + fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") + ) + )); } @Test @@ -257,16 +266,16 @@ void updateInvalidGuestPassword() throws Exception { UserResponse user = commentResponse.getUser(); mockMvc.perform(patch("/api/v1/comments/{id}", commentId) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(new CommentUpdateRequest(user.getId(), "invalid", "updateContent")))) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.code").value(901)) - .andDo(document("api/v1/comments/patch/fail-guest-password-wrong", - responseFields( - fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), - fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") - ) - )); + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(new CommentUpdateRequest(user.getId(), "invalid", "updateContent")))) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.code").value(901)) + .andDo(document("api/v1/comments/patch/fail-guest-password-wrong", + responseFields( + fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), + fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") + ) + )); } @Test @@ -276,17 +285,17 @@ void deleteLoginUser() throws Exception { Long commentId = commentResponse.getId(); mockMvc.perform(delete("/api/v1/comments/{id}", commentId) - .header("Authorization", "Bearer " + token) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isNoContent()) - .andDo(document("api/v1/comments/delete/success-login-user", - requestHeaders( - headerWithName("Authorization").description("JWT - Bearer 토큰") - ), - pathParameters( - parameterWithName("id").description("삭제할 댓글 id") - ) - )); + .header("Authorization", "Bearer " + token) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()) + .andDo(document("api/v1/comments/delete/success-login-user", + requestHeaders( + headerWithName("Authorization").description("JWT - Bearer 토큰") + ), + pathParameters( + parameterWithName("id").description("삭제할 댓글 id") + ) + )); } @Test @@ -297,19 +306,19 @@ void deleteGuestUser() throws Exception { UserResponse user = commentResponse.getUser(); mockMvc.perform(delete("/api/v1/comments/{id}", commentId) - .contentType(MediaType.APPLICATION_JSON) - .param("guestUserId", user.getId().toString()) - .param("guestUserPassword", "password")) - .andExpect(status().isNoContent()) - .andDo(document("api/v1/comments/delete/success-guest-user", - pathParameters( - parameterWithName("id").description("삭제할 댓글 id") - ), - requestParameters( - parameterWithName("guestUserId").description("비로그인 작성자 id"), - parameterWithName("guestUserPassword").description("비로그인 작성자 비밀번호") - ) - )); + .contentType(MediaType.APPLICATION_JSON) + .param("guestUserId", user.getId().toString()) + .param("guestUserPassword", "password")) + .andExpect(status().isNoContent()) + .andDo(document("api/v1/comments/delete/success-guest-user", + pathParameters( + parameterWithName("id").description("삭제할 댓글 id") + ), + requestParameters( + parameterWithName("guestUserId").description("비로그인 작성자 id"), + parameterWithName("guestUserPassword").description("비로그인 작성자 비밀번호") + ) + )); } @Test @@ -319,14 +328,14 @@ void deleteAdminUser() throws Exception { Long commentId = commentResponse.getId(); mockMvc.perform(delete("/api/v1/comments/{id}", commentId) - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + token)) - .andExpect(status().isNoContent()) - .andDo(document("api/v1/comments/delete/success-admin-user", - requestHeaders( - headerWithName("Authorization").description("관리자의 JWT - Bearer 토큰") - ) - )); + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", "Bearer " + token)) + .andExpect(status().isNoContent()) + .andDo(document("api/v1/comments/delete/success-admin-user", + requestHeaders( + headerWithName("Authorization").description("관리자의 JWT - Bearer 토큰") + ) + )); } @Test @@ -338,27 +347,27 @@ void deleteUnauthorized() throws Exception { UserResponse unauthorizedUser = commentResponse2.getUser(); mockMvc.perform(delete("/api/v1/comments/{id}", commentId1) - .contentType(MediaType.APPLICATION_JSON) - .param("guestUserId", unauthorizedUser.getId().toString()) - .param("guestUserPassword", "password") + .contentType(MediaType.APPLICATION_JSON) + .param("guestUserId", unauthorizedUser.getId().toString()) + .param("guestUserPassword", "password") ) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.code").value(903)) - .andDo(document("api/v1/comments/delete/fail-not-mine", - responseFields( - fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), - fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") - ) - )); + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.code").value(903)) + .andDo(document("api/v1/comments/delete/fail-not-mine", + responseFields( + fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), + fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") + ) + )); } private ResultActions 소셜_로그인_댓글_등록됨(String content, String url) throws Exception { return mockMvc.perform(post("/api/v1/comments") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + token) - .content(asJsonString(new CommentCreateRequest(null, null, secretKey, content, url)))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.user..type").value("SocialLoginUser")); + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", "Bearer " + token) + .content(asJsonString(new CommentCreateRequest(null, null, secretKey, content, url)))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.user..type").value("SocialLoginUser")); } private CommentResponse 소셜_로그인_댓글_등록됨_Response_반환(String content, String url) throws Exception { @@ -368,10 +377,10 @@ void deleteUnauthorized() throws Exception { private ResultActions 비로그인_댓글_등록됨(String content, String url) throws Exception { return mockMvc.perform(post("/api/v1/comments") - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(new CommentCreateRequest("guest", "password", secretKey, content, url)))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.user..type").value("GuestUser")); + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(new CommentCreateRequest("guest", "password", secretKey, content, url)))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.user..type").value("GuestUser")); } private CommentResponse 비로그인_댓글_등록됨_Response_반환(String content, String url) throws Exception { diff --git a/backend/src/test/java/com/darass/darass/exception/controller/ControllerAdviceTest.java b/backend/src/test/java/com/darass/darass/exception/controller/ControllerAdviceTest.java index 720a7ec9c..e250f3e95 100644 --- a/backend/src/test/java/com/darass/darass/exception/controller/ControllerAdviceTest.java +++ b/backend/src/test/java/com/darass/darass/exception/controller/ControllerAdviceTest.java @@ -10,7 +10,7 @@ import com.darass.darass.auth.oauth.controller.OAuthController; import com.darass.darass.auth.oauth.service.OAuthService; import com.darass.darass.comment.controller.CommentController; -import com.darass.darass.comment.controller.dto.CommentCreateRequest; +import com.darass.darass.comment.dto.CommentCreateRequest; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/backend/src/test/java/com/darass/darass/project/acceptance/ProjectAcceptanceTest.java b/backend/src/test/java/com/darass/darass/project/acceptance/ProjectAcceptanceTest.java index 865b9664c..e4a3910cf 100644 --- a/backend/src/test/java/com/darass/darass/project/acceptance/ProjectAcceptanceTest.java +++ b/backend/src/test/java/com/darass/darass/project/acceptance/ProjectAcceptanceTest.java @@ -15,10 +15,10 @@ import com.darass.darass.AcceptanceTest; import com.darass.darass.auth.oauth.infrastructure.JwtTokenProvider; -import com.darass.darass.project.controller.dto.ProjectCreateRequest; -import com.darass.darass.project.controller.dto.ProjectResponse; import com.darass.darass.project.domain.CustomSecretKeyFactory; import com.darass.darass.project.domain.Project; +import com.darass.darass.project.dto.ProjectCreateRequest; +import com.darass.darass.project.dto.ProjectResponse; import com.darass.darass.project.repository.ProjectRepository; import com.darass.darass.user.domain.OAuthPlatform; import com.darass.darass.user.domain.SocialLoginUser; diff --git a/backend/src/test/java/com/darass/darass/project/service/ProjectServiceTest.java b/backend/src/test/java/com/darass/darass/project/service/ProjectServiceTest.java index 7d0df2c37..721c39c61 100644 --- a/backend/src/test/java/com/darass/darass/project/service/ProjectServiceTest.java +++ b/backend/src/test/java/com/darass/darass/project/service/ProjectServiceTest.java @@ -5,11 +5,11 @@ import com.darass.darass.SpringContainerTest; import com.darass.darass.exception.ExceptionWithMessageAndCode; -import com.darass.darass.project.controller.dto.ProjectCreateRequest; -import com.darass.darass.project.controller.dto.ProjectResponse; import com.darass.darass.project.domain.CustomSecretKeyFactory; import com.darass.darass.project.domain.Project; import com.darass.darass.project.domain.RandomSecretKeyFactory; +import com.darass.darass.project.dto.ProjectCreateRequest; +import com.darass.darass.project.dto.ProjectResponse; import com.darass.darass.project.repository.ProjectRepository; import com.darass.darass.user.domain.GuestUser; import com.darass.darass.user.domain.User; diff --git a/backend/src/test/java/com/darass/darass/user/controller/UserAcceptanceTest.java b/backend/src/test/java/com/darass/darass/user/controller/UserAcceptanceTest.java index 0285e907c..3bbc7aa2c 100644 --- a/backend/src/test/java/com/darass/darass/user/controller/UserAcceptanceTest.java +++ b/backend/src/test/java/com/darass/darass/user/controller/UserAcceptanceTest.java @@ -1,19 +1,35 @@ package com.darass.darass.user.controller; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; +import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.darass.darass.AcceptanceTest; import com.darass.darass.auth.oauth.infrastructure.JwtTokenProvider; -import com.darass.darass.comment.controller.dto.CommentCreateRequest; -import com.darass.darass.comment.controller.dto.CommentResponse; -import com.darass.darass.comment.controller.dto.UserResponse; +import com.darass.darass.comment.dto.CommentCreateRequest; +import com.darass.darass.comment.dto.CommentResponse; import com.darass.darass.exception.ExceptionWithMessageAndCode; import com.darass.darass.exception.dto.ExceptionResponse; import com.darass.darass.project.domain.Project; import com.darass.darass.project.domain.RandomSecretKeyFactory; import com.darass.darass.project.repository.ProjectRepository; -import com.darass.darass.user.controller.dto.PasswordCheckResponse; -import com.darass.darass.user.controller.dto.UserUpdateRequest; +import com.darass.darass.user.dto.PasswordCheckResponse; import com.darass.darass.user.domain.OAuthPlatform; import com.darass.darass.user.domain.SocialLoginUser; +import com.darass.darass.user.dto.UserResponse; +import com.darass.darass.user.dto.UserUpdateRequest; import com.darass.darass.user.repository.UserRepository; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; @@ -24,39 +40,34 @@ import org.springframework.restdocs.payload.JsonFieldType; import org.springframework.test.web.servlet.ResultActions; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; -import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; -import static org.springframework.restdocs.payload.PayloadDocumentation.*; -import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @DisplayName("User 인수테스트") public class UserAcceptanceTest extends AcceptanceTest { private final String apiUrl = "/api/v1/users"; + @Autowired private UserRepository userRepository; + @Autowired private ProjectRepository projectRepository; + @Autowired private JwtTokenProvider tokenProvider; + private SocialLoginUser socialLoginUser; + private String projectSecretKey; + @BeforeEach public void setUser() { // TODO: 이 부분 로그인 인수테스트로 바꾸기 socialLoginUser = SocialLoginUser - .builder() - .nickName("우기") - .oauthId("2312312312") - .oauthPlatform(OAuthPlatform.KAKAO) - .email("bbwwpark@naver.com") - .profileImageUrl("https://imageUrl") - .build(); + .builder() + .nickName("우기") + .oauthId("2312312312") + .oauthPlatform(OAuthPlatform.KAKAO) + .email("bbwwpark@naver.com") + .profileImageUrl("https://imageUrl") + .build(); userRepository.save(socialLoginUser); } @@ -170,62 +181,64 @@ void checkWrongGuestUserPassword() throws Exception { private void 비로그인_유저_비밀번호_틀림(ResultActions resultActions) throws Exception { String responseJson = resultActions.andReturn().getResponse().getContentAsString(); - PasswordCheckResponse passwordCheckResponse = new ObjectMapper().readValue(responseJson, PasswordCheckResponse.class); + PasswordCheckResponse passwordCheckResponse = new ObjectMapper() + .readValue(responseJson, PasswordCheckResponse.class); assertThat(passwordCheckResponse.getIsCorrectPassword()).isFalse(); 비밀번호_일치여부_조회_rest_doc_작성(resultActions, "api/v1/users/get/password-check-incorrect"); } private void 비로그인_유저_비밀번호_일치함(ResultActions resultActions) throws Exception { String responseJson = resultActions.andReturn().getResponse().getContentAsString(); - PasswordCheckResponse passwordCheckResponse = new ObjectMapper().readValue(responseJson, PasswordCheckResponse.class); + PasswordCheckResponse passwordCheckResponse = new ObjectMapper() + .readValue(responseJson, PasswordCheckResponse.class); assertThat(passwordCheckResponse.getIsCorrectPassword()).isTrue(); 비밀번호_일치여부_조회_rest_doc_작성(resultActions, "api/v1/users/get/password-check-correct"); } private ResultActions 비밀번호_일치여부_조회_rest_doc_작성(ResultActions resultActions, String path) throws Exception { return resultActions.andExpect(status().isOk()) - .andDo( - document(path, - requestParameters( - parameterWithName("guestUserId").description("검증하려는 비로그인 유저 id"), - parameterWithName("guestUserPassword").description("검증하려는 비밀번호") - ), - responseFields( - fieldWithPath("isCorrectPassword").type(JsonFieldType.BOOLEAN).description("비밀번호 일치 여부") - )) - ); + .andDo( + document(path, + requestParameters( + parameterWithName("guestUserId").description("검증하려는 비로그인 유저 id"), + parameterWithName("guestUserPassword").description("검증하려는 비밀번호") + ), + responseFields( + fieldWithPath("isCorrectPassword").type(JsonFieldType.BOOLEAN).description("비밀번호 일치 여부") + )) + ); } private ResultActions 비로그인_유저_비밀번호_일치여부_조회_요청(String expected, String actual) throws Exception { Project project = Project.builder() - .name("project") - .secretKeyFactory(new RandomSecretKeyFactory()) - .user(socialLoginUser) - .build(); + .name("project") + .secretKeyFactory(new RandomSecretKeyFactory()) + .user(socialLoginUser) + .build(); projectRepository.save(project); - secretKey = project.getSecretKey(); + projectSecretKey = project.getSecretKey(); String responseJson = 비로그인_댓글_등록됨(expected).andReturn().getResponse().getContentAsString(); UserResponse userResponse = new ObjectMapper().readValue(responseJson, CommentResponse.class).getUser(); return this.mockMvc.perform(get(apiUrl + "/check-password") - .contentType(MediaType.APPLICATION_JSON) - .param("guestUserId", userResponse.getId().toString()) - .param("guestUserPassword", actual) + .contentType(MediaType.APPLICATION_JSON) + .param("guestUserId", userResponse.getId().toString()) + .param("guestUserPassword", actual) ); } private ResultActions 비로그인_댓글_등록됨(String password) throws Exception { return this.mockMvc.perform(post("/api/v1/comments") - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(new CommentCreateRequest("guest", password, secretKey, "content", "url")))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.user..type").value("GuestUser")); + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(new CommentCreateRequest("guest", password, projectSecretKey, "content", "url")))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.user..type").value("GuestUser")); } private ResultActions 유저_조회_요청(String accessToken) throws Exception { return this.mockMvc.perform(get(apiUrl) - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + accessToken)); + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", "Bearer " + accessToken)); } private void 유저_조회됨(ResultActions resultActions) throws Exception { @@ -242,18 +255,18 @@ void checkWrongGuestUserPassword() throws Exception { private void 유저_조회_rest_doc_작성(ResultActions resultActions) throws Exception { resultActions.andDo( - document("api/v1/users/get/success", - requestHeaders( - headerWithName("Authorization").description("JWT - Bearer 토큰") - ), - responseFields( - fieldWithPath("id").type(JsonFieldType.NUMBER).description("유저 아이디"), - fieldWithPath("nickName").type(JsonFieldType.STRING).description("유저 닉네임"), - fieldWithPath("type").type(JsonFieldType.STRING).description("유저 타입"), - fieldWithPath("createdDate").type(JsonFieldType.STRING).description("유저 생성일"), - fieldWithPath("modifiedDate").type(JsonFieldType.STRING).description("유저 수정일"), - fieldWithPath("profileImageUrl").type(JsonFieldType.STRING).description("유저 프로필 이미지") - )) + document("api/v1/users/get/success", + requestHeaders( + headerWithName("Authorization").description("JWT - Bearer 토큰") + ), + responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("유저 아이디"), + fieldWithPath("nickName").type(JsonFieldType.STRING).description("유저 닉네임"), + fieldWithPath("type").type(JsonFieldType.STRING).description("유저 타입"), + fieldWithPath("createdDate").type(JsonFieldType.STRING).description("유저 생성일"), + fieldWithPath("modifiedDate").type(JsonFieldType.STRING).description("유저 수정일"), + fieldWithPath("profileImageUrl").type(JsonFieldType.STRING).description("유저 프로필 이미지") + )) ); } @@ -264,19 +277,19 @@ void checkWrongGuestUserPassword() throws Exception { private void 유저_조회_실패_rest_doc_작성(ResultActions resultActions) throws Exception { resultActions.andDo( - document("api/v1/users/get/fail", - responseFields( - fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), - fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") - )) + document("api/v1/users/get/fail", + responseFields( + fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), + fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") + )) ); } private ResultActions 유저_닉네임_수정_요청(UserUpdateRequest userUpdateRequest, String accessToken) throws Exception { return this.mockMvc.perform(patch(apiUrl) - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + accessToken) - .content(asJsonString(userUpdateRequest))); + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", "Bearer " + accessToken) + .content(asJsonString(userUpdateRequest))); } private void 유저_닉네임_수정됨(ResultActions resultActions, UserUpdateRequest userUpdateRequest) throws Exception { @@ -291,21 +304,21 @@ void checkWrongGuestUserPassword() throws Exception { private void 유저_닉네임_수정_rest_doc_작성(ResultActions resultActions) throws Exception { resultActions.andDo( - document("api/v1/users/patch/success", - requestHeaders( - headerWithName("Authorization").description("JWT - Bearer 토큰") - ), - requestFields( - fieldWithPath("nickName").type(JsonFieldType.STRING).description("새로운 유저 닉네임") - ), - responseFields( - fieldWithPath("id").type(JsonFieldType.NUMBER).description("유저 아이디"), - fieldWithPath("nickName").type(JsonFieldType.STRING).description("유저 닉네임"), - fieldWithPath("type").type(JsonFieldType.STRING).description("유저 타입"), - fieldWithPath("createdDate").type(JsonFieldType.STRING).description("유저 생성일"), - fieldWithPath("modifiedDate").type(JsonFieldType.STRING).description("유저 수정일"), - fieldWithPath("profileImageUrl").type(JsonFieldType.STRING).description("유저 프로필 이미지") - )) + document("api/v1/users/patch/success", + requestHeaders( + headerWithName("Authorization").description("JWT - Bearer 토큰") + ), + requestFields( + fieldWithPath("nickName").type(JsonFieldType.STRING).description("새로운 유저 닉네임") + ), + responseFields( + fieldWithPath("id").type(JsonFieldType.NUMBER).description("유저 아이디"), + fieldWithPath("nickName").type(JsonFieldType.STRING).description("유저 닉네임"), + fieldWithPath("type").type(JsonFieldType.STRING).description("유저 타입"), + fieldWithPath("createdDate").type(JsonFieldType.STRING).description("유저 생성일"), + fieldWithPath("modifiedDate").type(JsonFieldType.STRING).description("유저 수정일"), + fieldWithPath("profileImageUrl").type(JsonFieldType.STRING).description("유저 프로필 이미지") + )) ); } @@ -316,18 +329,18 @@ void checkWrongGuestUserPassword() throws Exception { private void 유저_닉네임_수정_실패_rest_doc_작성(ResultActions resultActions) throws Exception { resultActions.andDo( - document("api/v1/users/patch/fail", - responseFields( - fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), - fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") - )) + document("api/v1/users/patch/fail", + responseFields( + fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), + fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") + )) ); } private ResultActions 유저_삭제_요청(String accessToken) throws Exception { return this.mockMvc.perform(delete(apiUrl) - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", "Bearer " + accessToken)); + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", "Bearer " + accessToken)); } private void 유저_정보_삭제됨(ResultActions resultActions) throws Exception { @@ -337,11 +350,11 @@ void checkWrongGuestUserPassword() throws Exception { private void 유저_삭제_rest_doc_작성(ResultActions resultActions) throws Exception { resultActions.andDo( - document("api/v1/users/delete/success", - requestHeaders( - headerWithName("Authorization").description("JWT - Bearer 토큰") - ) - )); + document("api/v1/users/delete/success", + requestHeaders( + headerWithName("Authorization").description("JWT - Bearer 토큰") + ) + )); } private void 유저_삭제_실패됨(ResultActions resultActions) throws Exception { @@ -351,11 +364,11 @@ void checkWrongGuestUserPassword() throws Exception { private void 유저_삭제_실패_rest_doc_작성(ResultActions resultActions) throws Exception { resultActions.andDo( - document("api/v1/users/delete/fail", - responseFields( - fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), - fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") - )) + document("api/v1/users/delete/fail", + responseFields( + fieldWithPath("message").type(JsonFieldType.STRING).description("에러 메시지"), + fieldWithPath("code").type(JsonFieldType.NUMBER).description("에러 코드") + )) ); } diff --git a/backend/src/test/java/com/darass/darass/user/service/UserServiceTest.java b/backend/src/test/java/com/darass/darass/user/service/UserServiceTest.java index dd83bb82c..5c8328ba1 100644 --- a/backend/src/test/java/com/darass/darass/user/service/UserServiceTest.java +++ b/backend/src/test/java/com/darass/darass/user/service/UserServiceTest.java @@ -3,11 +3,11 @@ import static org.assertj.core.api.Assertions.assertThat; import com.darass.darass.SpringContainerTest; -import com.darass.darass.comment.controller.dto.UserResponse; import com.darass.darass.exception.ExceptionWithMessageAndCode; -import com.darass.darass.user.controller.dto.UserUpdateRequest; import com.darass.darass.user.domain.GuestUser; import com.darass.darass.user.domain.User; +import com.darass.darass.user.dto.UserResponse; +import com.darass.darass.user.dto.UserUpdateRequest; import com.darass.darass.user.repository.UserRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; diff --git a/backend/src/test/resources/application.properties b/backend/src/test/resources/application.properties index 407c34eaa..579bfb6d5 100644 --- a/backend/src/test/resources/application.properties +++ b/backend/src/test/resources/application.properties @@ -3,4 +3,4 @@ spring.jpa.show-sql=false spring.jpa.generate-ddl=false logging.level.root=error logging.level.org.springframework=error -logging.level.org.hibernate.SQL= error \ No newline at end of file +logging.level.org.hibernate.SQL=error \ No newline at end of file