Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/docs/asciidoc/auth.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,8 @@ operation::auth-controller-test/kakao-o-auth-sign-in[snippets='http-request,curl
=== `POST` ํ† ํฐ ์žฌ๋ฐœ๊ธ‰

operation::auth-controller-test/reissue[snippets='http-request,curl-request,request-cookies,http-response,response-cookies,response-fields']

[[๊ฒŒ์ŠคํŠธ-ํ† ํฐ-๋ฐœ๊ธ‰]]
=== `POST` ๊ฒŒ์ŠคํŠธ ํ† ํฐ ๋ฐœ๊ธ‰

operation::auth-controller-test/guest-token[snippets='http-request,curl-request,http-response,response-fields']
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;

@Service
@RequiredArgsConstructor
public class AuthService {
Expand All @@ -40,11 +38,13 @@ private SocialAccount createUser(OAuthUserInfo oAuthUserInfo) {
return socialAccountRepository.save(SocialAccount.create(userId, oAuthUserInfo));
}

@Transactional
public TokenPair reissue(String refreshToken) {
return jwtService.reissue(refreshToken);
}

public String guestLogin() {
@Transactional
public String createGuestToken() {
Long guestId = userService.createGuest();
return cryptoService.encrypt(String.valueOf(guestId));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.swyp8team2.auth.application.oauth.dto.KakaoAuthResponse;
import com.swyp8team2.auth.application.oauth.dto.OAuthUserInfo;
import com.swyp8team2.common.config.KakaoOAuthConfig;
import com.swyp8team2.common.exception.BadRequestException;
import com.swyp8team2.common.exception.ErrorCode;
import com.swyp8team2.common.exception.InternalServerException;
import lombok.RequiredArgsConstructor;
Expand All @@ -29,8 +30,8 @@ public OAuthUserInfo getUserInfo(String code, String redirectUri) {
.fetchUserInfo(BEARER + kakaoAuthResponse.accessToken())
.toOAuthUserInfo();
} catch (Exception e) {
log.error("์†Œ์…œ ๋กœ๊ทธ์ธ ์‹คํŒจ", e);
throw new InternalServerException(ErrorCode.SOCIAL_AUTHENTICATION_FAILED);
log.debug("์†Œ์…œ ๋กœ๊ทธ์ธ ์‹คํŒจ {}", e.getMessage());
throw new BadRequestException(ErrorCode.SOCIAL_AUTHENTICATION_FAILED);
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/swyp8team2/auth/domain/SocialAccount.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.swyp8team2.auth.application.oauth.dto.OAuthUserInfo;
import com.swyp8team2.common.domain.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
Expand All @@ -25,6 +26,7 @@ public class SocialAccount extends BaseEntity {

private Long userId;

@Column(nullable = false, unique = true)
private String socialId;

@Enumerated(EnumType.STRING)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ public ResponseEntity<TokenResponse> reissue(
}

@PostMapping("/guest/token")
public ResponseEntity<GuestTokenResponse> guestLogin() {
String guestToken = authService.guestLogin();
public ResponseEntity<GuestTokenResponse> guestToken() {
String guestToken = authService.createGuestToken();
return ResponseEntity.ok(new GuestTokenResponse(guestToken));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import com.swyp8team2.common.exception.ErrorCode;
import com.swyp8team2.user.domain.User;
import com.swyp8team2.user.domain.UserRepository;
import com.swyp8team2.vote.domain.Vote;
import com.swyp8team2.vote.domain.VoteRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
Expand All @@ -25,21 +27,27 @@ public class CommentService {

private final UserRepository userRepository;
private final CommentRepository commentRepository;
private final VoteRepository voteRepository;

@Transactional
public void createComment(Long postId, CreateCommentRequest request, UserInfo userInfo) {
Comment comment = new Comment(postId, userInfo.userId(), request.content());
commentRepository.save(comment);
}

public CursorBasePaginatedResponse<CommentResponse> findComments(Long postId, Long cursor, int size) {
Slice<Comment> commentSlice = commentRepository.findByPostId(postId, cursor, PageRequest.of(0, size));
return CursorBasePaginatedResponse.of(commentSlice.map(this::createCommentResponse));
public CursorBasePaginatedResponse<CommentResponse> findComments(Long userId, Long postId, Long cursor, int size) {
Slice<Comment> commentSlice = commentRepository.findByPostId(postId, cursor, PageRequest.ofSize(size));
return CursorBasePaginatedResponse.of(
commentSlice.map(comment -> createCommentResponse(comment, userId))
);
}

private CommentResponse createCommentResponse(Comment comment) {
User user = userRepository.findById(comment.getUserNo())
private CommentResponse createCommentResponse(Comment comment, Long userId) {
User author = userRepository.findById(comment.getUserNo())
.orElseThrow(() -> new BadRequestException(ErrorCode.USER_NOT_FOUND));
return CommentResponse.of(comment, user);
Long voteImageId = voteRepository.findByUserIdAndPostId(userId, comment.getPostId())
.map(Vote::getPostImageId)
.orElse(null);
return CommentResponse.of(comment, author, author.getId().equals(userId), voteImageId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequiredArgsConstructor
Expand All @@ -47,8 +48,8 @@ public ResponseEntity<CursorBasePaginatedResponse<CommentResponse>> selectCommen
@RequestParam(value = "size", required = false, defaultValue = "10") @Min(1) int size,
@AuthenticationPrincipal UserInfo userInfo
) {
CursorBasePaginatedResponse<CommentResponse> response = commentService.findComments(postId, cursor, size);
return ResponseEntity.ok(response);
Long userId = Optional.ofNullable(userInfo).map(UserInfo::userId).orElse(null);
return ResponseEntity.ok(commentService.findComments(userId, postId, cursor, size));
}

@DeleteMapping("/{commentId}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ public record CommentResponse(
String content,
AuthorDto author,
Long voteImageId,
LocalDateTime createdAt
LocalDateTime createdAt,
boolean isAuthor
) implements CursorDto {

@Override
Expand All @@ -21,12 +22,13 @@ public long getId() {
return commentId;
}

public static CommentResponse of(Comment comment, User user) {
public static CommentResponse of(Comment comment, User user, boolean isAuthor, Long voteImageId) {
return new CommentResponse(comment.getId(),
comment.getContent(),
new AuthorDto(user.getId(), user.getNickname(), user.getProfileUrl()),
null,
comment.getCreatedAt()
);
comment.getContent(),
new AuthorDto(user.getId(), user.getNickname(), user.getProfileUrl()),
voteImageId,
comment.getCreatedAt(),
isAuthor
);
}
}
3 changes: 3 additions & 0 deletions src/main/java/com/swyp8team2/common/dev/DataInitializer.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ public class DataInitializer {

@Transactional
public void init() {
if (userRepository.count() > 0) {
return;
}
List<NicknameAdjective> adjectives = nicknameAdjectiveRepository.findAll();
User testUser = userRepository.save(User.create("nickname", "https://t1.kakaocdn.net/account_images/default_profile.jpeg"));
TokenPair tokenPair = jwtService.createToken(testUser.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,10 @@ void reissue_refreshTokenMismatched() throws Exception {

@Test
@DisplayName("๊ฒŒ์ŠคํŠธ ํ† ํฐ ๋ฐœ๊ธ‰")
void guestLogin() throws Exception {
void guestToken() throws Exception {
//given
String guestToken = "guestToken";
given(authService.guestLogin())
given(authService.createGuestToken())
.willReturn(guestToken);

//when then
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.swyp8team2.user.domain.Role;
import com.swyp8team2.user.domain.User;
import com.swyp8team2.user.domain.UserRepository;
import com.swyp8team2.vote.domain.VoteRepository;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand Down Expand Up @@ -43,6 +44,9 @@ class CommentServiceTest {
@InjectMocks
private CommentService commentService;

@Mock
private VoteRepository voteRepository;

@Test
@DisplayName("๋Œ“๊ธ€ ์ƒ์„ฑ")
void createComment() {
Expand Down Expand Up @@ -74,11 +78,12 @@ void findComments() {

// Mock ์„ค์ •
given(commentRepository.findByPostId(eq(postId), eq(cursor), any(PageRequest.class))).willReturn(commentSlice);
given(voteRepository.findByUserIdAndPostId(eq(user.getId()), eq(postId))).willReturn(Optional.empty());
// ๊ฐ ๋Œ“๊ธ€๋งˆ๋‹ค user_no=100L ์ด๋ฏ€๋กœ, findById(100L)๋งŒ ํ˜ธ์ถœ๋จ
given(userRepository.findById(100L)).willReturn(Optional.of(user));

// when
CursorBasePaginatedResponse<CommentResponse> response = commentService.findComments(postId, cursor, size);
CursorBasePaginatedResponse<CommentResponse> response = commentService.findComments(user.getId(), postId, cursor, size);

// then
assertThat(response.data()).hasSize(2);
Expand Down Expand Up @@ -113,7 +118,7 @@ void findComments_userNotFound() {
given(userRepository.findById(100L)).willReturn(Optional.empty());

// when & then
assertThatThrownBy(() -> commentService.findComments(postId, cursor, size))
assertThatThrownBy(() -> commentService.findComments(1L, postId, cursor, size))
.isInstanceOf(BadRequestException.class)
.hasMessage((ErrorCode.USER_NOT_FOUND.getMessage()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,15 @@ void findComments() throws Exception {
"๋Œ“๊ธ€ ๋‚ด์šฉ",
new AuthorDto(100L, "๋‹‰๋„ค์ž„", "http://example.com/profile.png"),
null,
LocalDateTime.now()
LocalDateTime.now(),
false
);
List<CommentResponse> commentList = Collections.singletonList(commentResponse);

CursorBasePaginatedResponse<CommentResponse> response =
new CursorBasePaginatedResponse<>(null, false, commentList);

when(commentService.findComments(eq(postId), eq(cursor), eq(size))).thenReturn(response);
when(commentService.findComments(eq(null), eq(postId), eq(cursor), eq(size))).thenReturn(response);

//when
mockMvc.perform(get("/posts/{postId}/comments", "1"))
Expand Down Expand Up @@ -125,11 +126,14 @@ void findComments() throws Exception {
.description("์ž‘์„ฑ์ž๊ฐ€ ํˆฌํ‘œํ•œ ์ด๋ฏธ์ง€ Id (ํˆฌํ‘œ ์—†์„ ์‹œ null)"),
fieldWithPath("data[].createdAt")
.type(JsonFieldType.STRING)
.description("๋Œ“๊ธ€ ์ž‘์„ฑ์ผ")
.description("๋Œ“๊ธ€ ์ž‘์„ฑ์ผ"),
fieldWithPath("data[].isAuthor")
.type(JsonFieldType.BOOLEAN)
.description("์ž‘์„ฑ์ž ์—ฌ๋ถ€")
)
));

verify(commentService, times(1)).findComments(eq(postId), eq(cursor), eq(size));
verify(commentService, times(1)).findComments(eq(null), eq(postId), eq(cursor), eq(size));
}

@Test
Expand Down