Skip to content

Commit

Permalink
feat: Add memberLogin Reponse(#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
eastmeet committed Jan 19, 2023
1 parent ea3f8e8 commit a4c7fe0
Show file tree
Hide file tree
Showing 13 changed files with 71 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ public class MemberController {

private final MemberMapper mapper;

//멤버 회원가입
@PostMapping("/signup")
public ResponseEntity<DataResponseDto<?>> postMember(@Valid @RequestBody MemberDto.Post memberPostDto) {
log.info("email={}", memberPostDto.getEmail());
Expand Down Expand Up @@ -79,8 +78,7 @@ public ResponseEntity<DataResponseDto<?>> patchMember(@ClientId Long clientId,

return new ResponseEntity<>(
new DataResponseDto<>(mapper.memberToProfileHomeDto(member)),
HttpStatus.OK
);
HttpStatus.OK);
}

@GetMapping("/users/profile/{member-id}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -18,12 +19,15 @@ 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 = "")
@Mapping(target = "address", constant = "")
@Mapping(target = "memberTitle", constant = "")
Member oauthMemberDtoToMember(MemberDto.Oauth oauthMemberDto);

@Mapping(target = "password", constant = "")
LoginResponseDto memberToLoginResponseDto(Member member);

}
Original file line number Diff line number Diff line change
Expand Up @@ -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<DataResponseDto<?>> 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(
Expand All @@ -58,8 +59,8 @@ public ResponseEntity<DataResponseDto<?>> registerPost(@ClientId Long clientId,

@PatchMapping("/edit/{post-id}")
public ResponseEntity<DataResponseDto<?>> 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));
Expand All @@ -76,8 +77,8 @@ public ResponseEntity<DataResponseDto<?>> getPost(@PathVariable("post-id") @Posi

@GetMapping("/home")
public ResponseEntity<MultiResponseDto<?>> 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<Post> allPostsBySort = postService.findAllPostsBySort(page - 1, size, sort);
List<Post> content = allPostsBySort.getContent();
Expand All @@ -89,8 +90,8 @@ public ResponseEntity<MultiResponseDto<?>> getHomePosts(@RequestParam(defaultVal

@GetMapping()
public ResponseEntity<MultiResponseDto<?>> 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<Post> postsByNewestByPage = postService.findAllPostsBySort(page - 1, size, sort);
List<Post> postsByNewest = postsByNewestByPage.getContent();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ public Post findPostNoneSetView(Long postId) {
return optionalPost.orElseThrow(() -> new BusinessLogicException(ExceptionCode.POST_NOT_FOUND));
}


public Page<Post> findAllPostsBySort(int page, int size, String sort) {
Pageable pageable = PageRequest.of(page, size, Sort.by(sort).descending());

Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> roles;

}
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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) {
Expand All @@ -46,18 +60,14 @@ 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) {
String subject = member.getEmail();
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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@
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;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.net.Authenticator;


@Slf4j
Expand All @@ -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
Expand All @@ -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();
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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("*");
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class JwtTokenizerTest {

@BeforeAll
public void init() {
jwtTokenizer = new JwtTokenizer();
jwtTokenizer = new JwtTokenizer(null);
secretKey = "kevin1234123412341234123412341234";

base64EncodedSecretKey = jwtTokenizer.encodeBase64SecretKey(secretKey);
Expand Down

0 comments on commit a4c7fe0

Please sign in to comment.