Skip to content

Commit

Permalink
Merge pull request #172 from woowacourse-teams/refactor/164-login-user
Browse files Browse the repository at this point in the history
#164 컨트롤러에서 인증된 유저를 구하는 코드 리팩토링하기
  • Loading branch information
chomily authored Sep 14, 2020
2 parents 47e0137 + 4385809 commit af42763
Show file tree
Hide file tree
Showing 10 changed files with 190 additions and 108 deletions.
19 changes: 15 additions & 4 deletions src/main/java/com/saebyeok/saebyeok/config/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
package com.saebyeok.saebyeok.config;

import com.saebyeok.saebyeok.controller.resolver.LoginMemberArgumentResolver;
import com.saebyeok.saebyeok.interceptor.LogInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final LogInterceptor logInterceptor;
private final LoginMemberArgumentResolver loginMemberArgumentResolver;

public WebMvcConfig(LogInterceptor logInterceptor) {
public WebMvcConfig(LogInterceptor logInterceptor, LoginMemberArgumentResolver loginMemberArgumentResolver) {
this.logInterceptor = logInterceptor;
this.loginMemberArgumentResolver = loginMemberArgumentResolver;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logInterceptor).addPathPatterns("/**")
.excludePathPatterns("/css/**")
.excludePathPatterns("/js/**")
.excludePathPatterns("/index.html");
.excludePathPatterns("/css/**")
.excludePathPatterns("/js/**")
.excludePathPatterns("/index.html");
}

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(loginMemberArgumentResolver);
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package com.saebyeok.saebyeok.controller;

import com.saebyeok.saebyeok.controller.resolver.LoginMember;
import com.saebyeok.saebyeok.domain.Member;
import com.saebyeok.saebyeok.domain.MemberRepository;
import com.saebyeok.saebyeok.dto.ArticlesAnalysisResponse;
import com.saebyeok.saebyeok.dto.CommentsAnalysisResponse;
import com.saebyeok.saebyeok.exception.MemberNotFoundException;
import com.saebyeok.saebyeok.security.User;
import com.saebyeok.saebyeok.service.AnalysisService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
Expand All @@ -20,37 +17,26 @@
@RequiredArgsConstructor
@RestController
public class AnalysisController {
private final MemberRepository memberRepository;
private final AnalysisService analysisService;

@GetMapping("/analysis/articles")
public ResponseEntity<ArticlesAnalysisResponse> getArticlesAnalysis(Authentication authentication) {
// TODO: 2020/08/16 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));

public ResponseEntity<ArticlesAnalysisResponse> getArticlesAnalysis(@LoginMember Member member) {
List<Integer> articleEmotionsCount = analysisService.findArticleEmotionsCount(member);
Long mostEmotionId = analysisService.findMostEmotionId(member);

ArticlesAnalysisResponse articlesAnalysisResponse = new ArticlesAnalysisResponse(articleEmotionsCount,
mostEmotionId);
mostEmotionId);

return ResponseEntity.ok(articlesAnalysisResponse);
}

@GetMapping("/analysis/comments")
public ResponseEntity<CommentsAnalysisResponse> getCommentsAnalysis(Authentication authentication) {
// TODO: 2020/08/16 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));

public ResponseEntity<CommentsAnalysisResponse> getCommentsAnalysis(@LoginMember Member member) {
Long totalCommentsCount = analysisService.countTotalCommentsBy(member);
Long totalCommentLikesCount = analysisService.countTotalCommentLikesBy(member);

CommentsAnalysisResponse commentsAnalysisResponse = new CommentsAnalysisResponse(totalCommentsCount,
totalCommentLikesCount);
totalCommentLikesCount);

return ResponseEntity.ok(commentsAnalysisResponse);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package com.saebyeok.saebyeok.controller;

import com.saebyeok.saebyeok.controller.resolver.LoginMember;
import com.saebyeok.saebyeok.domain.Article;
import com.saebyeok.saebyeok.domain.Member;
import com.saebyeok.saebyeok.domain.MemberRepository;
import com.saebyeok.saebyeok.dto.ArticleCreateRequest;
import com.saebyeok.saebyeok.dto.ArticleResponse;
import com.saebyeok.saebyeok.exception.MemberNotFoundException;
import com.saebyeok.saebyeok.security.User;
import com.saebyeok.saebyeok.service.ArticleService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
Expand All @@ -21,72 +18,46 @@
@RequiredArgsConstructor
@RestController
public class ArticleController {

private final ArticleService articleService;
private final MemberRepository memberRepository;

@GetMapping("/articles")
public ResponseEntity<List<ArticleResponse>> getArticles(Authentication authentication,
public ResponseEntity<List<ArticleResponse>> getArticles(@LoginMember Member member,
@RequestParam int page, @RequestParam int size,
@RequestParam(required = false) List<Long> emotionIds) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));
List<ArticleResponse> articles = articleService.getArticles(member, page, size, emotionIds);
return ResponseEntity.ok(articles);
}

@PostMapping("/articles")
public ResponseEntity<Void> createArticle(Authentication authentication, @Valid @RequestBody ArticleCreateRequest request) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));
public ResponseEntity<Void> createArticle(@LoginMember Member member, @Valid @RequestBody ArticleCreateRequest request) {
Article article = articleService.createArticle(member, request);
return ResponseEntity
.created(URI.create("/articles/" + article.getId()))
.build();
}

@GetMapping("/articles/{articleId}")
public ResponseEntity<ArticleResponse> readArticle(Authentication authentication, @PathVariable Long articleId) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));
public ResponseEntity<ArticleResponse> readArticle(@LoginMember Member member, @PathVariable Long articleId) {
ArticleResponse articleResponse = articleService.readArticle(member, articleId);
return ResponseEntity.ok(articleResponse);
}

@DeleteMapping("/articles/{articleId}")
public ResponseEntity<Void> deleteArticle(Authentication authentication, @PathVariable Long articleId) throws IllegalAccessException {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));
public ResponseEntity<Void> deleteArticle(@LoginMember Member member, @PathVariable Long articleId) throws IllegalAccessException {
articleService.deleteArticle(member, articleId);
return ResponseEntity.noContent().build();
}

@GetMapping("/member/articles")
public ResponseEntity<List<ArticleResponse>> getMemberArticles(Authentication authentication,
public ResponseEntity<List<ArticleResponse>> getMemberArticles(@LoginMember Member member,
@RequestParam int page, @RequestParam int size,
@RequestParam(required = false) List<Long> emotionIds) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));
List<ArticleResponse> articles = articleService.getMemberArticles(member, page, size, emotionIds);
return ResponseEntity.ok(articles);
}

@GetMapping("/member/articles/{articleId}")
public ResponseEntity<ArticleResponse> readMemberArticle(Authentication authentication, @PathVariable Long articleId) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));
public ResponseEntity<ArticleResponse> readMemberArticle(@LoginMember Member member, @PathVariable Long articleId) {
ArticleResponse articleResponse = articleService.readMemberArticle(member, articleId);
return ResponseEntity.ok(articleResponse);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package com.saebyeok.saebyeok.controller;

import com.saebyeok.saebyeok.controller.resolver.LoginMember;
import com.saebyeok.saebyeok.domain.Comment;
import com.saebyeok.saebyeok.domain.Member;
import com.saebyeok.saebyeok.domain.MemberRepository;
import com.saebyeok.saebyeok.dto.CommentCreateRequest;
import com.saebyeok.saebyeok.exception.MemberNotFoundException;
import com.saebyeok.saebyeok.security.User;
import com.saebyeok.saebyeok.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
Expand All @@ -20,27 +17,18 @@
@RestController
public class CommentController {
private final CommentService commentService;
private final MemberRepository memberRepository;

@PostMapping("/articles/{articleId}/comments")
public ResponseEntity<Void> createComment(Authentication authentication, @PathVariable Long articleId,
public ResponseEntity<Void> createComment(@LoginMember Member member, @PathVariable Long articleId,
@Valid @RequestBody CommentCreateRequest commentCreateRequest) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));
Comment comment = commentService.createComment(member, commentCreateRequest);
return ResponseEntity.
created(URI.create("/articles/" + articleId + "/comments/" + comment.getId())).
build();
}

@DeleteMapping("/articles/{articleId}/comments/{commentId}")
public ResponseEntity<Void> deleteComment(Authentication authentication, @PathVariable Long articleId, @PathVariable Long commentId) throws IllegalAccessException {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));
public ResponseEntity<Void> deleteComment(@LoginMember Member member, @PathVariable Long articleId, @PathVariable Long commentId) throws IllegalAccessException {
commentService.deleteComment(member, commentId);

return ResponseEntity.
Expand Down
39 changes: 5 additions & 34 deletions src/main/java/com/saebyeok/saebyeok/controller/LikeController.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
package com.saebyeok.saebyeok.controller;

import com.saebyeok.saebyeok.controller.resolver.LoginMember;
import com.saebyeok.saebyeok.domain.ArticleLike;
import com.saebyeok.saebyeok.domain.CommentLike;
import com.saebyeok.saebyeok.domain.Member;
import com.saebyeok.saebyeok.domain.MemberRepository;
import com.saebyeok.saebyeok.exception.MemberNotFoundException;
import com.saebyeok.saebyeok.security.User;
import com.saebyeok.saebyeok.service.LikeService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
Expand All @@ -18,59 +15,33 @@
@RequiredArgsConstructor
@RestController
public class LikeController {

private final MemberRepository memberRepository;
private final LikeService likeService;

@PostMapping("/likes/article/{articleId}")
public ResponseEntity<Void> likeArticle(Authentication authentication, @PathVariable Long articleId) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));

public ResponseEntity<Void> likeArticle(@LoginMember Member member, @PathVariable Long articleId) {
ArticleLike articleLike = likeService.likeArticle(member, articleId);

return ResponseEntity
.created(URI.create("/likes/article/" + articleId + "/article_like/" + articleLike.getId()))
.build();
}

@DeleteMapping("/likes/article/{articleId}")
public ResponseEntity<Void> unlikeArticle(Authentication authentication, @PathVariable Long articleId) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));

public ResponseEntity<Void> unlikeArticle(@LoginMember Member member, @PathVariable Long articleId) {
likeService.unlikeArticle(member, articleId);

return ResponseEntity.noContent().build();
}

@PostMapping("/likes/comment/{commentId}")
public ResponseEntity<Void> likeComment(Authentication authentication, @PathVariable Long commentId) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));

public ResponseEntity<Void> likeComment(@LoginMember Member member, @PathVariable Long commentId) {
CommentLike commentLike = likeService.likeComment(member, commentId);

return ResponseEntity
.created(URI.create("/likes/comment/" + commentId + "/comment_like" + commentLike.getId()))
.build();
}

@DeleteMapping("/likes/comment/{commentId}")
public ResponseEntity<Void> unlikeComment(Authentication authentication, @PathVariable Long commentId) {
// TODO: 20. 8. 11. 커스텀 어노테이션으로 리팩토링
User user = (User) authentication.getPrincipal();
Member member = memberRepository.findById(user.getId())
.orElseThrow(() -> new MemberNotFoundException(user.getId()));

public ResponseEntity<Void> unlikeComment(@LoginMember Member member, @PathVariable Long commentId) {
likeService.unlikeComment(member, commentId);

return ResponseEntity.noContent().build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.saebyeok.saebyeok.controller.resolver;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginMember {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.saebyeok.saebyeok.controller.resolver;

import com.saebyeok.saebyeok.security.User;
import com.saebyeok.saebyeok.service.MemberService;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class LoginMemberArgumentResolver implements HandlerMethodArgumentResolver {
private final MemberService memberService;

public LoginMemberArgumentResolver(MemberService memberService) {
this.memberService = memberService;
}

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(LoginMember.class);
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = (User) principal;

return memberService.findById(user.getId());
}
}
18 changes: 18 additions & 0 deletions src/main/java/com/saebyeok/saebyeok/service/MemberService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.saebyeok.saebyeok.service;

import com.saebyeok.saebyeok.domain.Member;
import com.saebyeok.saebyeok.domain.MemberRepository;
import com.saebyeok.saebyeok.exception.MemberNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class MemberService {
private final MemberRepository memberRepository;

public Member findById(Long id) {
return memberRepository.findById(id)
.orElseThrow(() -> new MemberNotFoundException(id));
}
}
Loading

0 comments on commit af42763

Please sign in to comment.