Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#66] Jwt & OAuth 리팩터링 및 테스트 추가 #74

Merged
merged 9 commits into from
Jan 25, 2023
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ jacocoTestCoverageVerification {

excludes = [
'*.global*',
'*.service*',
'*.series*',
'*.comment*',
'*.dto*'
]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ public ResponseEntity<Void> save(
@Valid @RequestBody CreateCommentRequest request,
@AuthenticationPrincipal JwtAuthentication user
) {
String userEmail = user.userEmail();
commentService.save(request, userEmail, postId);
commentService.save(request, user.id(), postId);
return ResponseEntity.status(CREATED).build();
}

Expand All @@ -44,8 +43,7 @@ public ResponseEntity<Void> update(
@Valid @RequestBody UpdateCommentRequest request,
@AuthenticationPrincipal JwtAuthentication user
) {
String userEmail = user.userEmail();
commentService.update(request, userEmail, commentId);
commentService.update(request, user.id(), commentId);
return ResponseEntity.ok().build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
import static com.prgrms.prolog.domain.comment.dto.CommentDto.*;

public interface CommentService {
Long save(CreateCommentRequest request, String email, Long postId);
Long update(UpdateCommentRequest request, String email, Long commentId);
Long save(CreateCommentRequest request, Long userId, Long postId);
Long update(UpdateCommentRequest request, Long userId, Long commentId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,18 @@ public class CommentServiceImpl implements CommentService {

@Override
@Transactional
public Long save(CreateCommentRequest request, String email, Long postId) {
public Long save(CreateCommentRequest request, Long userId, Long postId) {
Post findPost = getFindPostBy(postId);
User findUser = getFindUserBy(email);
User findUser = getFindUserBy(userId);
Comment comment = buildComment(request, findPost, findUser);
return commentRepository.save(comment).getId();
}

@Override
@Transactional
public Long update(UpdateCommentRequest request, String email, Long commentId) {
public Long update(UpdateCommentRequest request, Long userId, Long commentId) {
Comment findComment = commentRepository.joinUserByCommentId(commentId);
validateCommentNotNull(findComment);
validateCommentOwnerNotSameEmail(email, findComment);
findComment.changeContent(request.content());
return findComment.getId();
}
Expand All @@ -51,8 +50,8 @@ private Comment buildComment(CreateCommentRequest request, Post findPost, User f
.build();
}

private User getFindUserBy(String email) {
return userRepository.findByEmail(email)
private User getFindUserBy(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("exception.user.notExists"));
}

Expand All @@ -61,12 +60,6 @@ private Post getFindPostBy(Long postId) {
.orElseThrow(() -> new IllegalArgumentException("exception.post.notExists"));
}

private void validateCommentOwnerNotSameEmail(String email, Comment comment) {
if (! comment.checkUserEmail(email)) {
throw new IllegalArgumentException("exception.user.email.notSame");
}
}

private void validateCommentNotNull(Comment comment) {
Assert.notNull(comment, "exception.comment.notExists");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,15 @@ public PostController(PostService postService) {
@PostMapping()
public ResponseEntity<Void> save(
@Valid @RequestBody CreateRequest create,
@AuthenticationPrincipal JwtAuthentication jwt
@AuthenticationPrincipal JwtAuthentication user
) {
String userEmail = jwt.userEmail();
Long savePostId = postService.save(create, userEmail);
Long savePostId = postService.save(create, user.id());
URI location = UriComponentsBuilder.fromUriString("/api/v1/posts/" + savePostId).build().toUri();
return ResponseEntity.created(location).build();
}

@GetMapping("/{id}")
public ResponseEntity<PostResponse> findById(@PathVariable Long id) {
public ResponseEntity<PostResponse> findById(@PathVariable Long id) { // 비공개 처리는?
PostResponse findPost = postService.findById(id);
return ResponseEntity.ok(findPost);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
package com.prgrms.prolog.domain.post.dto;

import static com.prgrms.prolog.domain.user.dto.UserDto.UserProfile.*;

import java.util.List;

import com.prgrms.prolog.domain.comment.model.Comment;
import com.prgrms.prolog.domain.post.model.Post;
import com.prgrms.prolog.domain.user.dto.UserResponse;
import com.prgrms.prolog.domain.user.dto.UserDto.UserProfile;

public record PostResponse(String title,
String content,
boolean openStatus,
UserResponse.findResponse user,
UserProfile user,
List<Comment> comment,
int commentCount) {

public static PostResponse toPostResponse(Post post) {
return new PostResponse(post.getTitle(), post.getContent(), post.isOpenStatus(),
UserResponse.findResponse.toUserResponse(post.getUser()), post.getComments(), post.getComments().size());
toUserProfile(post.getUser()), post.getComments(), post.getComments().size());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public PostService(PostRepository postRepository, UserRepository userRepository)
this.userRepository = userRepository;
}

public Long save(CreateRequest create, String userEmail) {
User user = userRepository.findByEmail(userEmail)
public Long save(CreateRequest create, Long userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException(USER_NOT_EXIST_MESSAGE));
Post post = postRepository.save(CreateRequest.toEntity(create, user));
return post.getId();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ public class UserController {
private final UserService userService;

@GetMapping("/me")
ResponseEntity<UserInfo> myPage(
ResponseEntity<UserProfile> getMyProfile(
@AuthenticationPrincipal JwtAuthentication user
) {
return ResponseEntity.ok(userService.findByEmail(user.userEmail()));
return ResponseEntity.ok(
userService.findUserProfileByUserId(user.id())
);
}

}
21 changes: 14 additions & 7 deletions src/main/java/com/prgrms/prolog/domain/user/dto/UserDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,37 @@
public class UserDto {

@Builder
public record UserInfo(
public record UserProfile(
Long id,
String email,
String nickName,
String introduce,
String prologName
String prologName,
String profileImgUrl
) {
public UserInfo(User user) {
this(
public static UserProfile toUserProfile(User user) {
return new UserProfile(
user.getId(),
user.getEmail(),
user.getNickName(),
user.getIntroduce(),
user.getPrologName()
user.getPrologName(),
user.getProfileImgUrl()
);
}
}

@Builder
public record UserProfile(
public record UserInfo(
String email,
String nickName,
String provider,
String oauthId
String oauthId,
String profileImgUrl
) {

}

public record IdResponse(Long id) {
}
}
5 changes: 4 additions & 1 deletion src/main/java/com/prgrms/prolog/domain/user/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ public class User extends BaseEntity {
private Long id;
@Size(max = 100)
private String email;
@Size(max = 255)
private String profileImgUrl;
@Size(max = 100)
private String nickName;
@Size(max = 100)
Expand All @@ -67,13 +69,14 @@ public class User extends BaseEntity {

@Builder
public User(String email, String nickName, String introduce,
String prologName, String provider, String oauthId) {
String prologName, String provider, String oauthId, String profileImgUrl) {
this.email = validateEmail(email);
this.nickName = validateNickName(nickName);
this.introduce = validateIntroduce(introduce);
this.prologName = validatePrologName(prologName);
this.provider = Objects.requireNonNull(provider, "provider" + NULL_VALUE_MESSAGE);
this.oauthId = Objects.requireNonNull(oauthId, "oauthId" + NULL_VALUE_MESSAGE);
this.profileImgUrl = profileImgUrl;
}

private String validatePrologName(String prologName) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.prgrms.prolog.domain.user.model.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

Optional<User> findByEmail(String email);
@Query("""
SELECT u
FROM User u
WHERE u.provider = :provider
and u.oauthId = :oauthId
""")
Optional<User> findByProviderAndOauthId(String provider, String oauthId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

public interface UserService {

/* 사용자 로그인 */
UserInfo login(UserProfile userProfile);
/* 사용자 회원 가입 */
IdResponse signUp(UserInfo userInfo);

/* 이메일로 사용자 조회 */
UserInfo findByEmail(String email);
/* 사용자 조회 */
UserProfile findUserProfileByUserId(Long userId);

}

Original file line number Diff line number Diff line change
Expand Up @@ -19,35 +19,37 @@ public class UserServiceImpl implements UserService {

private final UserRepository userRepository;

/* [사용자 조회] 이메일 값으로 등록된 유저 정보 찾아서 제공 */
/* [사용자 조회] 사용자 ID를 통해 등록된 유저 정보 찾아서 제공 */
@Override
public UserInfo findByEmail(String email) {
return userRepository.findByEmail(email)
.map(UserInfo::new)
.orElseThrow(IllegalArgumentException::new);
public UserProfile findUserProfileByUserId(Long userId) {
return userRepository.findById(userId)
.map(UserProfile::toUserProfile)
.orElseThrow(() -> new IllegalArgumentException("유저를 찾을 수 없습니다."));
}

/* [로그인] 등록된 사용자인지 확인해서 맞는 경우 정보 제공, 아닌 경우 등록 진행 */
/* [회원 가입] 등록된 사용자 인지 확인해서 맞는 경우 유저ID 제공, 아닌 경우 사용자 등록 */
@Transactional
public UserInfo login(UserProfile userProfile) {
return userRepository.findByEmail(userProfile.email())
.map(UserInfo::new)
.orElseGet(() -> register(userProfile));
public IdResponse signUp(UserInfo userInfo) {
return new IdResponse(
userRepository
.findByProviderAndOauthId(userInfo.provider(), userInfo.oauthId())
.map(User::getId)
.orElseGet(() -> register(userInfo).getId())
);
}

/* [사용자 등록] 디폴트 설정 값으로 회원가입 진행 */
private UserInfo register(UserProfile userProfile) {
return new UserInfo(
userRepository.save(
private User register(UserInfo userInfo) {
return userRepository.save(
User.builder()
.email(userProfile.email())
.nickName(userProfile.nickName())
.email(userInfo.email())
.nickName(userInfo.nickName())
.introduce(DEFAULT_INTRODUCE)
.prologName(userProfile.nickName() + "의 prolog")
.provider(userProfile.provider())
.oauthId(userProfile.oauthId())
.prologName(userInfo.nickName() + "의 prolog")
.provider(userInfo.provider())
.oauthId(userInfo.oauthId())
.profileImgUrl(userInfo.profileImgUrl())
.build()
)
);
);
}
}
6 changes: 3 additions & 3 deletions src/main/java/com/prgrms/prolog/global/config/JpaConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ public class JpaConfig {
public AuditorAware<String> auditorAwareProvider() {
return () -> Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.map(this::getUser);
.map(this::getCreatorInfo);
}

private String getUser(Authentication authentication) { //TODO: 메소드명 바꾸기
private String getCreatorInfo(Authentication authentication) {
if (isValidAuthentication(authentication)) {
JwtAuthentication user = (JwtAuthentication)authentication.getPrincipal();
return user.userEmail();
return user.id().toString();
}
return null;
}
Expand Down
20 changes: 10 additions & 10 deletions src/main/java/com/prgrms/prolog/global/jwt/JwtAuthentication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,31 @@

import java.util.Objects;

public record JwtAuthentication(String token, String userEmail) {
public record JwtAuthentication(String token, Long id) {

public JwtAuthentication {
validateToken(token);
validateUserEmail(userEmail);

validateId(id);
}


private void validateToken(String token) {
if (Objects.isNull(token) || token.isBlank()) {
throw new IllegalArgumentException("토큰이 없습니다.");
}
}

private void validateUserEmail(String userEmail) {
if (Objects.isNull(userEmail) || userEmail.isBlank()) {
throw new IllegalArgumentException("유저 이메일이 없습니다.");
private void validateId(Long userId) {
if (Objects.isNull(userId) || userId <= 0L) {
throw new IllegalArgumentException("유저의 ID가 없습니다.");
}
}

@Override
public String toString() {
return "JwtAuthentication{"
+ "token='" + token + '\''
+ ", userEmail='" + userEmail + '\''
+ '}';
return "JwtAuthentication{" +
"token='" + token + '\'' +
", id='" + id + '\'' +
'}';
}
}
Loading