From a4c7fe0f65fbc6979a03d6fe151b65e34f74dd8a Mon Sep 17 00:00:00 2001 From: eastmeet Date: Thu, 19 Jan 2023 21:08:07 +0900 Subject: [PATCH] feat: Add memberLogin Reponse(#60) --- .../comment/controller/CommentController.java | 4 ---- .../comment/service/CommentService.java | 3 ++- .../member/controller/MemberController.java | 4 +--- .../domain/member/mapper/MemberMapper.java | 8 +++++-- .../post/controller/PostController.java | 17 ++++++------- .../domain/post/service/PostService.java | 1 - .../authorization/dto/LoginResponseDto.java | 17 +++++++++++++ .../MemberAuthenticationFailureHandler.java | 4 ++-- .../MemberAuthenticationSuccessHandler.java | 24 +++++++++++++------ .../resolver/UserArgumentResolver.java | 16 ++++--------- .../global/config/SecurityConfiguration.java | 14 +++++++---- .../picha/global/exception/ExceptionCode.java | 2 +- .../main36/picha/auth/JwtTokenizerTest.java | 2 +- 13 files changed, 71 insertions(+), 45 deletions(-) create mode 100644 server/src/main/java/com/main36/picha/global/authorization/dto/LoginResponseDto.java diff --git a/server/src/main/java/com/main36/picha/domain/comment/controller/CommentController.java b/server/src/main/java/com/main36/picha/domain/comment/controller/CommentController.java index a72f4ed5..8f651fae 100644 --- a/server/src/main/java/com/main36/picha/domain/comment/controller/CommentController.java +++ b/server/src/main/java/com/main36/picha/domain/comment/controller/CommentController.java @@ -30,13 +30,9 @@ @Validated public class CommentController { private final JwtTokenizer jwtTokenizer; - private final MemberService memberService; - private final CommentService commentService; - private final PostService postService; - private final CommentMapper mapper; @PostMapping("/upload/{post-id}") diff --git a/server/src/main/java/com/main36/picha/domain/comment/service/CommentService.java b/server/src/main/java/com/main36/picha/domain/comment/service/CommentService.java index c0abd0b7..c01f844e 100644 --- a/server/src/main/java/com/main36/picha/domain/comment/service/CommentService.java +++ b/server/src/main/java/com/main36/picha/domain/comment/service/CommentService.java @@ -43,8 +43,9 @@ public Comment findVerifiedComment(long commentId){ public Comment verifyClientId(long clientId, long commentId) { Comment comment = findComment(commentId); + if (!comment.getMember().getMemberId().equals(clientId)) { - throw new BusinessLogicException(ExceptionCode.NOT_AUTHOR); + throw new BusinessLogicException(ExceptionCode.CLIENT_IS_NOT_EQUAL); } return comment; diff --git a/server/src/main/java/com/main36/picha/domain/member/controller/MemberController.java b/server/src/main/java/com/main36/picha/domain/member/controller/MemberController.java index 9350d93d..cc5fa624 100644 --- a/server/src/main/java/com/main36/picha/domain/member/controller/MemberController.java +++ b/server/src/main/java/com/main36/picha/domain/member/controller/MemberController.java @@ -30,7 +30,6 @@ public class MemberController { private final MemberMapper mapper; - //멤버 회원가입 @PostMapping("/signup") public ResponseEntity> postMember(@Valid @RequestBody MemberDto.Post memberPostDto) { log.info("email={}", memberPostDto.getEmail()); @@ -79,8 +78,7 @@ public ResponseEntity> patchMember(@ClientId Long clientId, return new ResponseEntity<>( new DataResponseDto<>(mapper.memberToProfileHomeDto(member)), - HttpStatus.OK - ); + HttpStatus.OK); } @GetMapping("/users/profile/{member-id}") diff --git a/server/src/main/java/com/main36/picha/domain/member/mapper/MemberMapper.java b/server/src/main/java/com/main36/picha/domain/member/mapper/MemberMapper.java index 0751a4ca..2abe731c 100644 --- a/server/src/main/java/com/main36/picha/domain/member/mapper/MemberMapper.java +++ b/server/src/main/java/com/main36/picha/domain/member/mapper/MemberMapper.java @@ -2,13 +2,14 @@ import com.main36.picha.domain.member.dto.*; import com.main36.picha.domain.member.entity.Member; +import com.main36.picha.global.authorization.dto.LoginResponseDto; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingConstants; @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) -public interface MemberMapper { +public interface MemberMapper { Member memberPostDtoToMember(MemberDto.Post memberPostDto); @@ -18,7 +19,7 @@ public interface MemberMapper { @Mapping(target = "totalMyPosts", expression = "java(member.getPosts().size())") @Mapping(target = "totalMySaves", expression = "java(member.getSaves().size())") - MemberResponseDto.Profile memberToProfileHomeDto(Member member); + MemberResponseDto.Profile memberToProfileHomeDto(Member member); @Mapping(target = "password", constant = "") @Mapping(target = "phoneNumber", constant = "") @@ -26,4 +27,7 @@ public interface MemberMapper { @Mapping(target = "memberTitle", constant = "") Member oauthMemberDtoToMember(MemberDto.Oauth oauthMemberDto); + @Mapping(target = "password", constant = "") + LoginResponseDto memberToLoginResponseDto(Member member); + } diff --git a/server/src/main/java/com/main36/picha/domain/post/controller/PostController.java b/server/src/main/java/com/main36/picha/domain/post/controller/PostController.java index 3788ccc7..b38373a5 100644 --- a/server/src/main/java/com/main36/picha/domain/post/controller/PostController.java +++ b/server/src/main/java/com/main36/picha/domain/post/controller/PostController.java @@ -36,10 +36,11 @@ public class PostController { private final PostMapper mapper; private final MemberService memberService; private final AttractionService attractionService; + @PostMapping("/register/{attraction-id}") public ResponseEntity> registerPost(@ClientId Long clientId, - @PathVariable("attraction-id") @Positive long attractionId, - @Valid @RequestBody PostDto.Post postRegisterDto) { + @PathVariable("attraction-id") @Positive long attractionId, + @Valid @RequestBody PostDto.Post postRegisterDto) { Post.PostBuilder postBuilder = Post.builder(); Post post = postService.createPost( @@ -58,8 +59,8 @@ public ResponseEntity> registerPost(@ClientId Long clientId, @PatchMapping("/edit/{post-id}") public ResponseEntity> editPost(@ClientId Long clientId, - @PathVariable("post-id") @Positive long postId, - @Valid @RequestBody PostDto.Patch postPatchDto) { + @PathVariable("post-id") @Positive long postId, + @Valid @RequestBody PostDto.Patch postPatchDto) { postService.verifyClientId(clientId, postId); postPatchDto.setPostId(postId); Post updatePost = postService.updatePost(mapper.postPatchDtoToPost(postPatchDto)); @@ -76,8 +77,8 @@ public ResponseEntity> getPost(@PathVariable("post-id") @Posi @GetMapping("/home") public ResponseEntity> getHomePosts(@RequestParam(defaultValue = "newest", required = false) String sort, - @RequestParam(defaultValue = "1", required = false) @Positive int page, - @RequestParam(defaultValue = "8", required = false) @Positive int size) { + @RequestParam(defaultValue = "1", required = false) @Positive int page, + @RequestParam(defaultValue = "8", required = false) @Positive int size) { sort = getString(sort); Page allPostsBySort = postService.findAllPostsBySort(page - 1, size, sort); List content = allPostsBySort.getContent(); @@ -89,8 +90,8 @@ public ResponseEntity> getHomePosts(@RequestParam(defaultVal @GetMapping() public ResponseEntity> getAllPosts(@RequestParam(defaultValue = "newest", required = false) String sort, - @RequestParam(defaultValue = "1", required = false) @Positive int page, - @RequestParam(defaultValue = "9", required = false) @Positive int size) { + @RequestParam(defaultValue = "1", required = false) @Positive int page, + @RequestParam(defaultValue = "9", required = false) @Positive int size) { sort = getString(sort); Page postsByNewestByPage = postService.findAllPostsBySort(page - 1, size, sort); List postsByNewest = postsByNewestByPage.getContent(); diff --git a/server/src/main/java/com/main36/picha/domain/post/service/PostService.java b/server/src/main/java/com/main36/picha/domain/post/service/PostService.java index e34aff3b..4a8629ab 100644 --- a/server/src/main/java/com/main36/picha/domain/post/service/PostService.java +++ b/server/src/main/java/com/main36/picha/domain/post/service/PostService.java @@ -64,7 +64,6 @@ public Post findPostNoneSetView(Long postId) { return optionalPost.orElseThrow(() -> new BusinessLogicException(ExceptionCode.POST_NOT_FOUND)); } - public Page findAllPostsBySort(int page, int size, String sort) { Pageable pageable = PageRequest.of(page, size, Sort.by(sort).descending()); diff --git a/server/src/main/java/com/main36/picha/global/authorization/dto/LoginResponseDto.java b/server/src/main/java/com/main36/picha/global/authorization/dto/LoginResponseDto.java new file mode 100644 index 00000000..1886915b --- /dev/null +++ b/server/src/main/java/com/main36/picha/global/authorization/dto/LoginResponseDto.java @@ -0,0 +1,17 @@ +package com.main36.picha.global.authorization.dto; + +import lombok.Builder; +import lombok.Data; + +import java.util.List; + +@Data +@Builder +public class LoginResponseDto { + + private Long memberId; + private String email; + private String password; + private List roles; + +} diff --git a/server/src/main/java/com/main36/picha/global/authorization/handler/MemberAuthenticationFailureHandler.java b/server/src/main/java/com/main36/picha/global/authorization/handler/MemberAuthenticationFailureHandler.java index 638b5f59..81515c6d 100644 --- a/server/src/main/java/com/main36/picha/global/authorization/handler/MemberAuthenticationFailureHandler.java +++ b/server/src/main/java/com/main36/picha/global/authorization/handler/MemberAuthenticationFailureHandler.java @@ -27,9 +27,9 @@ public void onAuthenticationFailure(HttpServletRequest request, private void sendErrorResponse(HttpServletResponse response) throws IOException{ Gson gson = new Gson(); - ErrorResponse errorResponse = ErrorResponse.of(HttpStatus.UNAUTHORIZED); + ErrorResponse errorResponse = ErrorResponse.of(HttpStatus.FORBIDDEN); response.setContentType(MediaType.APPLICATION_JSON_VALUE); - response.setStatus(HttpStatus.UNAUTHORIZED.value()); + response.setStatus(HttpStatus.FORBIDDEN.value()); response.getWriter().write(gson.toJson(errorResponse, ErrorResponse.class)); } } diff --git a/server/src/main/java/com/main36/picha/global/authorization/handler/MemberAuthenticationSuccessHandler.java b/server/src/main/java/com/main36/picha/global/authorization/handler/MemberAuthenticationSuccessHandler.java index 7d3da06c..4cbf38b0 100644 --- a/server/src/main/java/com/main36/picha/global/authorization/handler/MemberAuthenticationSuccessHandler.java +++ b/server/src/main/java/com/main36/picha/global/authorization/handler/MemberAuthenticationSuccessHandler.java @@ -1,11 +1,17 @@ package com.main36.picha.global.authorization.handler; +import com.google.gson.Gson; import com.main36.picha.domain.member.entity.Member; +import com.main36.picha.domain.member.mapper.MemberMapper; +import com.main36.picha.global.authorization.dto.LoginDto; +import com.main36.picha.global.authorization.dto.LoginResponseDto; import com.main36.picha.global.authorization.jwt.JwtTokenizer; +import com.main36.picha.global.authorization.resolver.ClientId; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -21,19 +27,27 @@ public class MemberAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private final JwtTokenizer jwtTokenizer; + private final MemberMapper mapper; + + private final Gson gson; + @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { Member member = (Member) authResult.getPrincipal(); - + LoginResponseDto loginResponseDto = mapper.memberToLoginResponseDto(member); String accessToken = delegateAccessToken(member); String refreshToken = delegateRefreshToken(member); response.setHeader("Authorization", "Bearer " + accessToken); response.setHeader("RefreshToken", refreshToken); + response.setContentType("application/json"); + response.setCharacterEncoding("utf-8"); + response.getWriter().write(gson.toJson(loginResponseDto)); log.info("# Authenticated successfully!"); + } private String delegateAccessToken(Member member) { @@ -46,9 +60,7 @@ private String delegateAccessToken(Member member) { String base64EncodedSecretKey = jwtTokenizer.encodeBase64SecretKey(jwtTokenizer.getSecretKey()); - String accessToken = jwtTokenizer.generatedAccessToken(claims, subject, expiration, base64EncodedSecretKey); - - return accessToken; + return jwtTokenizer.generatedAccessToken(claims, subject, expiration, base64EncodedSecretKey); } private String delegateRefreshToken(Member member) { @@ -56,8 +68,6 @@ private String delegateRefreshToken(Member member) { Date expiration = jwtTokenizer.getTokenExpiration(jwtTokenizer.getRefreshTokenExpirationMinutes()); String base64EncodedSecretKey = jwtTokenizer.encodeBase64SecretKey(jwtTokenizer.getSecretKey()); - String refreshToken = jwtTokenizer.generateRefreshToken(subject, expiration, base64EncodedSecretKey); - - return refreshToken; + return jwtTokenizer.generateRefreshToken(subject, expiration, base64EncodedSecretKey); } } diff --git a/server/src/main/java/com/main36/picha/global/authorization/resolver/UserArgumentResolver.java b/server/src/main/java/com/main36/picha/global/authorization/resolver/UserArgumentResolver.java index 5dd296b8..de52d9fe 100644 --- a/server/src/main/java/com/main36/picha/global/authorization/resolver/UserArgumentResolver.java +++ b/server/src/main/java/com/main36/picha/global/authorization/resolver/UserArgumentResolver.java @@ -3,9 +3,13 @@ import com.main36.picha.domain.member.entity.Member; import com.main36.picha.domain.member.service.MemberService; import com.main36.picha.global.authorization.jwt.JwtTokenizer; +import com.nimbusds.jose.proc.SecurityContext; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.Authentication; +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; @@ -13,6 +17,7 @@ import org.springframework.web.method.support.ModelAndViewContainer; import javax.servlet.http.HttpServletRequest; +import java.net.Authenticator; @Slf4j @@ -26,9 +31,6 @@ public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterAnnotation(ClientId.class) != null && parameter.getParameterType().equals(Long.class); - -// return isLoginUserAnnotation && isUserClass; -// return parameter.getParameterType().equals(LoginDto.class); } @Override @@ -40,13 +42,5 @@ public Long resolveArgument(MethodParameter parameter, HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); return jwtTokenizer.getUserId(request); - - //Object getPrincipal(); // 주로 ID - //Object getDetails(); // 사용자 상세정보 - -// -// TokenPrincipalDto castedPrincipal = (TokenPrincipalDto) principal; -// usernamePasswordAuthenticationToken.getPrincipal(); -// return castedPrincipal.getId(); } } diff --git a/server/src/main/java/com/main36/picha/global/config/SecurityConfiguration.java b/server/src/main/java/com/main36/picha/global/config/SecurityConfiguration.java index 696b2591..558c0c16 100644 --- a/server/src/main/java/com/main36/picha/global/config/SecurityConfiguration.java +++ b/server/src/main/java/com/main36/picha/global/config/SecurityConfiguration.java @@ -1,6 +1,8 @@ package com.main36.picha.global.config; +import com.google.gson.Gson; +import com.main36.picha.domain.member.entity.Member; import com.main36.picha.domain.member.mapper.MemberMapper; import com.main36.picha.domain.member.repository.MemberRepository; import com.main36.picha.domain.member.service.MemberService; @@ -39,7 +41,7 @@ public class SecurityConfiguration { private final MemberService memberService; private final MemberMapper mapper; private final MemberRepository memberRepository; - + private final Gson gson; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { @@ -84,8 +86,12 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); - configuration.setAllowedOrigins(List.of("http://localhost:3000", "https://pikcha36.o-r.kr/" - , "http://pikcha36.o-r.kr/")); + configuration.setAllowedOrigins( + List.of( + "http://localhost:3000", + "https://pikcha36.o-r.kr/", + "http://pikcha36.o-r.kr/") + ); configuration.setAllowCredentials(true); configuration.addExposedHeader("Authorization"); configuration.addAllowedHeader("*"); @@ -103,7 +109,7 @@ public void configure(HttpSecurity builder) throws Exception { JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager); jwtAuthenticationFilter.setFilterProcessesUrl("/login"); - jwtAuthenticationFilter.setAuthenticationSuccessHandler(new MemberAuthenticationSuccessHandler(jwtTokenizer)); + jwtAuthenticationFilter.setAuthenticationSuccessHandler(new MemberAuthenticationSuccessHandler(jwtTokenizer, mapper, gson)); jwtAuthenticationFilter.setAuthenticationFailureHandler(new MemberAuthenticationFailureHandler()); JwtVerificationFilter jwtVerificationFilter = new JwtVerificationFilter(jwtTokenizer, authorityUtils); diff --git a/server/src/main/java/com/main36/picha/global/exception/ExceptionCode.java b/server/src/main/java/com/main36/picha/global/exception/ExceptionCode.java index 47606c69..39e82074 100644 --- a/server/src/main/java/com/main36/picha/global/exception/ExceptionCode.java +++ b/server/src/main/java/com/main36/picha/global/exception/ExceptionCode.java @@ -7,7 +7,7 @@ public enum ExceptionCode { MEMBER_NOT_ALLOW(405, "That Member doesn't have authority"), MEMBER_EXISTS(409, "Member exists"), - CLIENT_IS_NOT_EQUAL(400, "Client is not equal member, post, comment"), + CLIENT_IS_NOT_EQUAL(400, "Client is not equal memberId"), ATTRACTION_NOT_FOUND(404, "Attraction not found"), ATTRACTION_EXISTS(409, "Attraction exists"), diff --git a/server/src/test/java/com/main36/picha/auth/JwtTokenizerTest.java b/server/src/test/java/com/main36/picha/auth/JwtTokenizerTest.java index dab19877..9ff7543e 100644 --- a/server/src/test/java/com/main36/picha/auth/JwtTokenizerTest.java +++ b/server/src/test/java/com/main36/picha/auth/JwtTokenizerTest.java @@ -28,7 +28,7 @@ public class JwtTokenizerTest { @BeforeAll public void init() { - jwtTokenizer = new JwtTokenizer(); + jwtTokenizer = new JwtTokenizer(null); secretKey = "kevin1234123412341234123412341234"; base64EncodedSecretKey = jwtTokenizer.encodeBase64SecretKey(secretKey);