diff --git a/server/src/main/java/com/main36/picha/domain/attraction/controller/AttractionController.java b/server/src/main/java/com/main36/picha/domain/attraction/controller/AttractionController.java index 76a2a185..2d7daec1 100644 --- a/server/src/main/java/com/main36/picha/domain/attraction/controller/AttractionController.java +++ b/server/src/main/java/com/main36/picha/domain/attraction/controller/AttractionController.java @@ -40,7 +40,7 @@ public class AttractionController { // 1. 명소 등록 핸들러 @PostMapping("/upload") - public ResponseEntity postAttraction(AttractionPostDto attractionPostDto) throws IOException { + public ResponseEntity> postAttraction(AttractionPostDto attractionPostDto) throws IOException { Attraction attraction = mapper.attractionPostDtoToAttraction(attractionPostDto); @@ -64,7 +64,7 @@ public ResponseEntity postAttraction(AttractionPostDto attractionPostDto) throws // 2. 명소 수정 핸들러 @PatchMapping("/{attraction-id}") - public ResponseEntity patchAttraction(@PathVariable("attraction-id") @Positive long attractionId, + public ResponseEntity> patchAttraction(@PathVariable("attraction-id") @Positive long attractionId, AttractionPatchDto attractionPatchDto) throws IOException { attractionPatchDto.setAttractionId(attractionId); @@ -91,9 +91,9 @@ public ResponseEntity patchAttraction(@PathVariable("attraction-id") @Positive l // 3. 명소 1개 정보 요청을 처리하는 핸들러 // 반환하는 정보 : 명소 정보(Id,이름, 설명, 주소, 이미지 주소), 좋아요 수, 좋아요 눌렀는지, 즐겨찾기 수, 즐겨찾기 눌렀는지 @GetMapping("/{attraction-id}") - public ResponseEntity getAttraction(HttpServletRequest request, + public ResponseEntity> getAttraction(HttpServletRequest request, @PathVariable("attraction-id") @Positive long attractionId){ - Member member = memberService.findMember(extractedUsername(request)); + Member member = memberService.findMemberByMemberEmail(extractedUsername(request)); Attraction attraction = attractionService.findAttraction(attractionId); AttractionDetailResponseDto response = mapper.attractionToAttractionDetailResponseDto(attraction); @@ -105,7 +105,7 @@ public ResponseEntity getAttraction(HttpServletRequest request, // 4. 찾는 '구' 리스트를 받아 명소 Id 기준으로 명소 여러개의 정보 요청을 처리하는 핸들러 // 반환하는 정보 : 명소 정보(id, 이름, 이미지 주소), 좋아요 수, 즐겨찾기 수(아직 구현안됨) @GetMapping("/filter") - public ResponseEntity getFilteredAttractions(@Positive @RequestParam(required = false, defaultValue = "1") int page, + public ResponseEntity> getFilteredAttractions(@Positive @RequestParam(required = false, defaultValue = "1") int page, @Positive @RequestParam(required = false, defaultValue = "9") int size, @RequestParam(required = false, defaultValue = "latest") String sort, @RequestBody AttractionFilterDto filterDto){ @@ -126,18 +126,18 @@ public ResponseEntity getFilteredAttractions(@Positive @RequestParam(required = // 5. 명소 Id를 기준으로 명소 여러개의 정보 요청을 처리하는 핸들러 // 반환하는 정보 : 명소 정보(id, 이름, 이미지 주소), 좋아요 수, 즐겨찾기 수 @GetMapping - public ResponseEntity getAttractions(@Positive @RequestParam(required = false, defaultValue = "1") int page, + public ResponseEntity> getAttractions(@Positive @RequestParam(required = false, defaultValue = "1") int page, @Positive @RequestParam(required = false, defaultValue = "9") int size){ Page attractionPage = attractionService.findAttractions(page-1, size); List attractions = attractionPage.getContent(); - return new ResponseEntity(new MultiResponseDto<>( + return new ResponseEntity<>(new MultiResponseDto<>( mapper.attractionsToAttractionResponseDtos(attractions),attractionPage), HttpStatus.OK); } // 6. 명소를 아예 삭제하는 요청을 처리하는 핸들러 @DeleteMapping("/{attraction-id}") - public ResponseEntity deleteAttraction(@PathVariable("attraction-id") @Positive long attractionId){ + public ResponseEntity deleteAttraction(@PathVariable("attraction-id") @Positive long attractionId){ attractionService.deleteAttraction(attractionId); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -145,11 +145,11 @@ public ResponseEntity deleteAttraction(@PathVariable("attraction-id") @Positive // 7. 명소 좋아요! @PostMapping("/likes/{attraction-id}") - public ResponseEntity voteAttraction(HttpServletRequest request, + public ResponseEntity> voteAttraction(HttpServletRequest request, @PathVariable("attraction-id") @Positive long attractionId){ // 회원 정보를 받아온다 String userEmail = extractedUsername(request); - Member member = memberService.findMember(userEmail); + Member member = memberService.findMemberByMemberEmail(userEmail); // 명소 정보를 찾는다 Attraction attraction = attractionService.findAttraction(attractionId); @@ -160,15 +160,15 @@ public ResponseEntity voteAttraction(HttpServletRequest request, // responseDto 생성 AttractionLikesResponseDto response = new AttractionLikesResponseDto(); response.setIsVoted(status); - return new ResponseEntity(new DataResponseDto<>(response), HttpStatus.OK); + return new ResponseEntity<>(new DataResponseDto<>(response), HttpStatus.OK); } // 8. 명소 즐겨찾기 @PostMapping("/saves/{attraction-id}") - public ResponseEntity saveAttraction(HttpServletRequest request, + public ResponseEntity> saveAttraction(HttpServletRequest request, @PathVariable("attraction-id") @Positive long attractionId){ String userEmail = extractedUsername(request); - Member member = memberService.findMember(userEmail); + Member member = memberService.findMemberByMemberEmail(userEmail); // 명소 정보를 찾는다 Attraction attraction = attractionService.findAttraction(attractionId); @@ -177,7 +177,7 @@ public ResponseEntity saveAttraction(HttpServletRequest request, AttractionSaveResponseDto response = new AttractionSaveResponseDto(); response.setIsSaved(status); - return new ResponseEntity(new DataResponseDto<>(response), HttpStatus.OK); + return new ResponseEntity<>(new DataResponseDto<>(response), HttpStatus.OK); } private String extractedUsername(HttpServletRequest request) { 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 954c7d5a..a72f4ed5 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 @@ -1,16 +1,14 @@ package com.main36.picha.domain.comment.controller; -import com.main36.picha.domain.comment.dto.CommentPostDto; +import com.main36.picha.domain.comment.dto.CommentDto; import com.main36.picha.domain.comment.dto.CommentResponseDto; import com.main36.picha.domain.comment.entity.Comment; import com.main36.picha.domain.comment.mapper.CommentMapper; import com.main36.picha.domain.comment.service.CommentService; -import com.main36.picha.domain.member.entity.Member; import com.main36.picha.domain.member.service.MemberService; import com.main36.picha.domain.post.service.PostService; import com.main36.picha.global.authorization.jwt.JwtTokenizer; -import com.main36.picha.global.exception.BusinessLogicException; -import com.main36.picha.global.exception.ExceptionCode; +import com.main36.picha.global.authorization.resolver.ClientId; import com.main36.picha.global.response.DataResponseDto; import com.main36.picha.global.response.MultiResponseDto; import lombok.RequiredArgsConstructor; @@ -41,18 +39,17 @@ public class CommentController { private final CommentMapper mapper; - @PostMapping("/upload/{member-id}/{post-id}") - public ResponseEntity> postComment(@PathVariable("member-id") @Positive long memberId, + @PostMapping("/upload/{post-id}") + public ResponseEntity> postComment(@ClientId Long clientId, @PathVariable("post-id") @Positive long postId, - @RequestBody @Valid CommentPostDto commentPostDto) { - + @RequestBody @Valid CommentDto.Post commentPostDto) { Comment.CommentBuilder commentBuilder = Comment.builder(); Comment comment = commentService.createComment( commentBuilder .commentContent(commentPostDto.getCommentContent()) - .member(memberService.findVerifiedMemberById(memberId)) + .member(memberService.findMemberByMemberId(clientId)) .post(postService.findPost(postId)) .build() ); @@ -62,12 +59,12 @@ public ResponseEntity> postComment(@PathVariable("member-id") return new ResponseEntity<>(new DataResponseDto<>(commentResponseDto), HttpStatus.CREATED); } - @PatchMapping("/edit/{member-id}/{comment-id}") - public ResponseEntity> patchComment(@PathVariable("member-id") @Positive long memberId, + @PatchMapping("/edit/{comment-id}") + public ResponseEntity> patchComment(@ClientId Long clientId, @PathVariable("comment-id") @Positive long commentId, - @RequestBody @Valid CommentPostDto commentPostDto) { - Comment comment = verifiedById(memberId, commentId); - comment.setCommentContent(commentPostDto.getCommentContent()); + @RequestBody @Valid CommentDto.Patch commentPatchDto) { + Comment comment = commentService.verifyClientId(clientId, commentId); + comment.setCommentContent(commentPatchDto.getCommentContent()); CommentResponseDto commentResponseDto = mapper.commentToCommentResponseDto(comment); @@ -92,23 +89,13 @@ public ResponseEntity> getComment(@Positive @RequestParam(re return ResponseEntity.ok(new MultiResponseDto<>(commentResponseDtos, commentPage)); } - @DeleteMapping("/delete/{member-id}/{comment-id}") - public ResponseEntity deleteComment(@PathVariable("member-id") @Positive long memberId, + @DeleteMapping("/delete/{comment-id}") + public ResponseEntity deleteComment(@ClientId Long clientId, @PathVariable("comment-id") @Positive long commentId) { - verifiedById(memberId, commentId); - commentService.deleteComment(commentId); + Comment comment = commentService.verifyClientId(clientId, commentId); + commentService.deleteComment(comment); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } - private Comment verifiedById(long memberId, long commentId) { - Member member = memberService.findVerifiedMemberById(memberId); - Comment comment = commentService.findComment(commentId); - - if (!comment.getMember().getMemberId().equals(memberId)) { - throw new BusinessLogicException(ExceptionCode.NOT_AUTHOR); - } - - return comment; - } } diff --git a/server/src/main/java/com/main36/picha/domain/comment/dto/CommentDto.java b/server/src/main/java/com/main36/picha/domain/comment/dto/CommentDto.java new file mode 100644 index 00000000..afe87912 --- /dev/null +++ b/server/src/main/java/com/main36/picha/domain/comment/dto/CommentDto.java @@ -0,0 +1,24 @@ +package com.main36.picha.domain.comment.dto; + +import lombok.Data; +import lombok.Getter; + +import javax.validation.constraints.NotBlank; + + +@Data +public class CommentDto { + + @Getter + public static class Post { + @NotBlank(message = "댓글 내용을 입력해주세요.") + private String commentContent; + } + + @Getter + public static class Patch { + @NotBlank(message = "댓글 내용을 입력해주세요.") + private String commentContent; + } + +} diff --git a/server/src/main/java/com/main36/picha/domain/comment/dto/CommentPostDto.java b/server/src/main/java/com/main36/picha/domain/comment/dto/CommentPostDto.java deleted file mode 100644 index 036d05f1..00000000 --- a/server/src/main/java/com/main36/picha/domain/comment/dto/CommentPostDto.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.main36.picha.domain.comment.dto; - -import lombok.Data; - -import javax.validation.constraints.NotBlank; - - -@Data -public class CommentPostDto { - - @NotBlank(message = "댓글 내용을 입력해주세요.") - private String commentContent; -} diff --git a/server/src/main/java/com/main36/picha/domain/comment/mapper/CommentMapper.java b/server/src/main/java/com/main36/picha/domain/comment/mapper/CommentMapper.java index 85f756dd..55f2e45a 100644 --- a/server/src/main/java/com/main36/picha/domain/comment/mapper/CommentMapper.java +++ b/server/src/main/java/com/main36/picha/domain/comment/mapper/CommentMapper.java @@ -1,6 +1,6 @@ package com.main36.picha.domain.comment.mapper; -import com.main36.picha.domain.comment.dto.CommentPostDto; +import com.main36.picha.domain.comment.dto.CommentDto; import com.main36.picha.domain.comment.dto.CommentResponseDto; import com.main36.picha.domain.comment.entity.Comment; import org.mapstruct.Mapper; @@ -11,7 +11,7 @@ @Mapper(componentModel = "spring") public interface CommentMapper { - Comment CommentDtoToComment(CommentPostDto commentPostDto); + Comment CommentDtoToComment(CommentDto commentDto); @Mapping(target = "username", source = "member.username") @Mapping(target = "memberId", source = "member.memberId") 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 9bb6c68a..c0abd0b7 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 @@ -11,8 +11,6 @@ import org.springframework.stereotype.Service; import javax.transaction.Transactional; -import java.util.Optional; - @Service @Transactional @RequiredArgsConstructor @@ -34,15 +32,23 @@ public Page findComments(int page, int size) { )); } - public void deleteComment(long commentId){ - Comment findComment = findVerifiedComment(commentId); - commentRepository.delete(findComment); + public void deleteComment(Comment comment){ + commentRepository.delete(comment); } - private Comment findVerifiedComment(long commentId){ + public Comment findVerifiedComment(long commentId){ return commentRepository.findById(commentId) .orElseThrow(()-> new BusinessLogicException(ExceptionCode.COMMENT_NOT_FOUND)); } + public Comment verifyClientId(long clientId, long commentId) { + Comment comment = findComment(commentId); + if (!comment.getMember().getMemberId().equals(clientId)) { + throw new BusinessLogicException(ExceptionCode.NOT_AUTHOR); + } + + 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 4f65d71a..9350d93d 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 @@ -1,11 +1,11 @@ package com.main36.picha.domain.member.controller; -import com.main36.picha.domain.member.dto.MemberPatchDto; -import com.main36.picha.domain.member.dto.MemberPostDto; +import com.main36.picha.domain.member.dto.MemberDto; import com.main36.picha.domain.member.entity.Member; import com.main36.picha.domain.member.mapper.MemberMapper; import com.main36.picha.domain.member.service.MemberService; +import com.main36.picha.global.authorization.resolver.ClientId; import com.main36.picha.global.response.DataResponseDto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -24,7 +24,6 @@ @RestController @Validated @RequiredArgsConstructor -@RequestMapping("/users") public class MemberController { private final MemberService memberService; @@ -33,7 +32,10 @@ public class MemberController { //멤버 회원가입 @PostMapping("/signup") - public ResponseEntity> postMember(@Valid @RequestBody MemberPostDto memberPostDto) { + public ResponseEntity> postMember(@Valid @RequestBody MemberDto.Post memberPostDto) { + log.info("email={}", memberPostDto.getEmail()); + log.info("username={}", memberPostDto.getUsername()); + Member member = mapper.memberPostDtoToMember(memberPostDto); member.setPicture("https://drive.google.com/file/d/1OmsgU1GLU9iUBYe9ruw_Uy1AcrN57n4g/view?usp=sharing"); Member createMember = memberService.createMember(member); @@ -48,6 +50,7 @@ public ResponseEntity getToken(@RequestParam String access_token, @RequestParam String refresh_token) { log.info("at={}", access_token); log.info("rt={}", refresh_token); + String at = "Bearer " + access_token; // 1. 헤더에 담아서 보내기 @@ -65,9 +68,12 @@ public ResponseEntity getToken(@RequestParam String access_token, // return ResponseEntity.ok(tokenBuilder); } - @PatchMapping("/edit/{member-id}") - public ResponseEntity> patchMember(@PathVariable("member-id") @Positive long memberId, - @Valid @RequestBody MemberPatchDto memberPatchDto) { + @PatchMapping("/users/edit/{member-id}") + public ResponseEntity> patchMember(@ClientId Long clientId, + @PathVariable("member-id") @Positive Long memberId, + @Valid @RequestBody MemberDto.Patch memberPatchDto) { + memberService.isEqualToClientIdAndMemberId(clientId, memberId); + memberPatchDto.setMemberId(memberId); Member member = memberService.updateMember(mapper.memberPatchDtoToMember(memberPatchDto)); @@ -77,27 +83,22 @@ public ResponseEntity> patchMember(@PathVariable("member-id") ); } - @GetMapping("/{member-id}/{email}") - public ResponseEntity> getMemberProfile(@Positive @PathVariable("member-id") long memberId, - @PathVariable("email") String email) { - //TODO: verifyLoginMember - Member member = memberService.findMember(memberId, email); + @GetMapping("/users/profile/{member-id}") + public ResponseEntity> getMemberProfile(@ClientId Long clientId, + @PathVariable("member-id") @Positive Long memberId) { + Member member = memberService.isEqualToClientIdAndMemberId(clientId, memberId); + return new ResponseEntity<>(new DataResponseDto<>(mapper.memberToProfileHomeDto(member)), HttpStatus.OK); } - @GetMapping() - public ResponseEntity getMembers(@RequestParam(defaultValue = "1", required = false) int page, - @RequestParam(defaultValue = "9", required = false) int size) { -// Page pageMember = - return new ResponseEntity<>(HttpStatus.OK); - } + @DeleteMapping("/users/delete/{member-id}") + public ResponseEntity deleteMember(@ClientId Long clientId, + @PathVariable("member-id") @Positive Long memberId) { + Member member = memberService.isEqualToClientIdAndMemberId(clientId, memberId); + memberService.deleteMember(member); - @DeleteMapping("/delete/{member-id}/confirm") - public ResponseEntity deleteMember(@PathVariable("member-id") @Positive long memberId) { - //TODO: verifyLoginMember - memberService.deleteMember(memberId); - return new ResponseEntity(HttpStatus.NO_CONTENT); + return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } diff --git a/server/src/main/java/com/main36/picha/domain/member/dto/MemberDto.java b/server/src/main/java/com/main36/picha/domain/member/dto/MemberDto.java new file mode 100644 index 00000000..9f502aa0 --- /dev/null +++ b/server/src/main/java/com/main36/picha/domain/member/dto/MemberDto.java @@ -0,0 +1,77 @@ +package com.main36.picha.domain.member.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import javax.persistence.Column; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +public class MemberDto { + @Data + @Builder + public static class Post { + + @NotBlank(message = "not allowed null values and spaces.") + @Email(message = "please match the email format.") + private String email; + + @NotBlank(message = "not allowed null values and spaces.") +// @Pattern(message = "'숫자', '문자' 무조건 1개 이상, '최소 8자에서 최대 20자' 허용, !@#$%^&* 특수문자만 허용", +// regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d~!@#$%^&*()+|=]{8,20}$") + private String password; + + @Pattern(regexp = "^010-\\d{3,4}-\\d{4}$", + message = "휴대폰 번호는 010으로 시작하는 11자리 숫자와 '-'로 구성되어야 합니다.") + private String phoneNumber; + + private String address; + + @NotBlank(message = "not allowed null values and spaces.") + private String username; + + + } + + @Data + @Builder + public static class Patch { + + private long memberId; + + @NotBlank(message = "not allowed null values and spaces.") + private String username; + + private String phoneNumber; + + private String address; + +// @NotBlank(message = "not allowed null values and spaces.") +// @Email(message = "please match the email format.") +// private String email; + +// @NotBlank(message = "not allowed null values and spaces.") +//// @Pattern(message = "'숫자', '문자' 무조건 1개 이상, '최소 8자에서 최대 20자' 허용, !@#$%^&* 특수문자만 허용", +//// regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d~!@#$%^&*()+|=]{8,20}$") +// private String password; + } + + + @Data + @Builder + @AllArgsConstructor + public static class Oauth { + + @Column(nullable = false) + private String username; + + @Column(nullable = false, updatable = false, unique = true) + private String email; + + @Column(name = "picture") + private String picture; + + } +} diff --git a/server/src/main/java/com/main36/picha/domain/member/dto/MemberPatchDto.java b/server/src/main/java/com/main36/picha/domain/member/dto/MemberPatchDto.java deleted file mode 100644 index a4957fbf..00000000 --- a/server/src/main/java/com/main36/picha/domain/member/dto/MemberPatchDto.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.main36.picha.domain.member.dto; - -import lombok.Builder; -import lombok.Data; -import net.bytebuddy.asm.Advice; - -import javax.persistence.Column; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Positive; -import java.time.LocalDateTime; - -@Data -@Builder -public class MemberPatchDto { - - private long memberId; - - @NotBlank(message = "not allowed null values and spaces.") - private String username; - - private String phoneNumber; - - private String address; - -// @NotBlank(message = "not allowed null values and spaces.") -// @Email(message = "please match the email format.") -// private String email; - -// @NotBlank(message = "not allowed null values and spaces.") -//// @Pattern(message = "'숫자', '문자' 무조건 1개 이상, '최소 8자에서 최대 20자' 허용, !@#$%^&* 특수문자만 허용", -//// regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d~!@#$%^&*()+|=]{8,20}$") -// private String password; -} diff --git a/server/src/main/java/com/main36/picha/domain/member/dto/MemberPostDto.java b/server/src/main/java/com/main36/picha/domain/member/dto/MemberPostDto.java deleted file mode 100644 index 28366825..00000000 --- a/server/src/main/java/com/main36/picha/domain/member/dto/MemberPostDto.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.main36.picha.domain.member.dto; - - -import lombok.Builder; -import lombok.Data; - -import javax.validation.constraints.Email; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Pattern; -import java.time.LocalDateTime; - -@Data -@Builder -public class MemberPostDto { - - @NotBlank(message = "not allowed null values and spaces.") - @Email(message = "please match the email format.") - private String email; - - @NotBlank(message = "not allowed null values and spaces.") -// @Pattern(message = "'숫자', '문자' 무조건 1개 이상, '최소 8자에서 최대 20자' 허용, !@#$%^&* 특수문자만 허용", -// regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d~!@#$%^&*()+|=]{8,20}$") - private String password; - - @Pattern(regexp = "^010-\\d{3,4}-\\d{4}$", - message = "휴대폰 번호는 010으로 시작하는 11자리 숫자와 '-'로 구성되어야 합니다.") - private String phoneNumber; - - private String address; - - @NotBlank(message = "not allowed null values and spaces.") - private String username; - - -} diff --git a/server/src/main/java/com/main36/picha/domain/member/dto/MemberResponseDto.java b/server/src/main/java/com/main36/picha/domain/member/dto/MemberResponseDto.java new file mode 100644 index 00000000..7cf69526 --- /dev/null +++ b/server/src/main/java/com/main36/picha/domain/member/dto/MemberResponseDto.java @@ -0,0 +1,41 @@ +package com.main36.picha.domain.member.dto; + +import lombok.Builder; +import lombok.Data; + +import java.time.LocalDateTime; + +public class MemberResponseDto { + + @Data + @Builder + public static class SignUp { + private Long memberId; + private String email; + private String phoneNumber; + private String address; + private String username; + private String picture; + private LocalDateTime createdAt; + } + + @Data + @Builder + public static class Profile { + private long memberId; + private String username; + private String memberTitle; + private String phoneNumber; + private String address; + private String picture; + private String email; + private int totalMyPosts; + private int totalMySaves; + private LocalDateTime createdAt; + private LocalDateTime modifiedAt; + + //TODO: 프로필화면 내 지도색칠을 위해 post address 정보 주기 +// private List postList; + } + +} diff --git a/server/src/main/java/com/main36/picha/domain/member/dto/OauthMemberDto.java b/server/src/main/java/com/main36/picha/domain/member/dto/OauthMemberDto.java deleted file mode 100644 index d447b865..00000000 --- a/server/src/main/java/com/main36/picha/domain/member/dto/OauthMemberDto.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.main36.picha.domain.member.dto; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; - -import javax.persistence.*; - -@Data -@Builder -@AllArgsConstructor -public class OauthMemberDto { - - @Column(nullable = false) - private String username; - - @Column(nullable = false, updatable = false, unique = true) - private String email; - - @Column(name = "picture") - private String picture; - -} diff --git a/server/src/main/java/com/main36/picha/domain/member/dto/ProfileHomeDto.java b/server/src/main/java/com/main36/picha/domain/member/dto/ProfileHomeDto.java deleted file mode 100644 index c1862222..00000000 --- a/server/src/main/java/com/main36/picha/domain/member/dto/ProfileHomeDto.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.main36.picha.domain.member.dto; - -import lombok.Builder; -import lombok.Data; -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.LastModifiedBy; - -import javax.persistence.Column; -import java.time.LocalDateTime; - -@Data -@Builder -public class ProfileHomeDto { - - private long memberId; - - private String username; - - private String memberTitle; - - private String phoneNumber; - - private String address; - - private String picture; - - private String email; - - private int totalMyPosts; - - private int totalMySaves; - - private LocalDateTime createdAt; - - private LocalDateTime modifiedAt; - - //TODO: 프로필화면 내 지도색칠을 위해 post address 정보 주기 -// private List postList; -} diff --git a/server/src/main/java/com/main36/picha/domain/member/dto/SignUpResponseDto.java b/server/src/main/java/com/main36/picha/domain/member/dto/SignUpResponseDto.java deleted file mode 100644 index a4fd8abd..00000000 --- a/server/src/main/java/com/main36/picha/domain/member/dto/SignUpResponseDto.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.main36.picha.domain.member.dto; - -import lombok.Builder; -import lombok.Data; - -import javax.persistence.Column; -import java.time.LocalDateTime; - -@Data -@Builder -public class SignUpResponseDto { - - private Long memberId; - - private String email; - - private String phoneNumber; - - private String address; - - private String username; - - private String picture; - - private LocalDateTime createdAt; - -} 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 38d451fc..526e1d5b 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,26 +2,23 @@ import com.main36.picha.domain.member.dto.*; import com.main36.picha.domain.member.entity.Member; -import com.main36.picha.domain.post.entity.Post; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingConstants; -import java.util.List; - @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public interface MemberMapper { - Member memberPostDtoToMember(MemberPostDto memberPostDto); + Member memberPostDtoToMember(MemberDto.Post memberPostDto); - Member memberPatchDtoToMember(MemberPatchDto memberPatchDto); + Member memberPatchDtoToMember(MemberDto.Patch memberPatchDto); SignUpResponseDto memberToSignUpResponseDto(Member member); @Mapping(target = "totalMyPosts", expression = "java(member.getPosts().size())") @Mapping(target = "totalMySaves", expression = "java(member.getSaves().size())") - ProfileHomeDto memberToProfileHomeDto(Member member); + ProfileHomeResponseDto memberToProfileHomeDto(Member member); @Mapping(target = "password", constant = "") @Mapping(target = "phoneNumber", constant = "") diff --git a/server/src/main/java/com/main36/picha/domain/member/repository/MemberRepository.java b/server/src/main/java/com/main36/picha/domain/member/repository/MemberRepository.java index 920dbfbc..8e2b1ba3 100644 --- a/server/src/main/java/com/main36/picha/domain/member/repository/MemberRepository.java +++ b/server/src/main/java/com/main36/picha/domain/member/repository/MemberRepository.java @@ -8,5 +8,5 @@ public interface MemberRepository extends JpaRepository { Optional findByEmail(String email); - Optional findByMemberIdAndEmail(Long memberId, String email); + Optional findByMemberId(Long memberId); } diff --git a/server/src/main/java/com/main36/picha/domain/member/service/MemberService.java b/server/src/main/java/com/main36/picha/domain/member/service/MemberService.java index 4d0e4e48..26eb869c 100644 --- a/server/src/main/java/com/main36/picha/domain/member/service/MemberService.java +++ b/server/src/main/java/com/main36/picha/domain/member/service/MemberService.java @@ -1,14 +1,11 @@ package com.main36.picha.domain.member.service; -import com.main36.picha.domain.member.dto.MemberPatchDto; import com.main36.picha.domain.member.entity.Member; import com.main36.picha.domain.member.repository.MemberRepository; import com.main36.picha.global.exception.BusinessLogicException; import com.main36.picha.global.exception.ExceptionCode; import com.main36.picha.global.utils.CustomAuthorityUtils; import lombok.RequiredArgsConstructor; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @@ -25,8 +22,6 @@ public class MemberService { private final PasswordEncoder passwordEncoder; private final CustomAuthorityUtils authorityUtils; - - // 멤버 생성 public Member createMember(Member member) { verifyExistsEmail(member.getEmail()); String encryptedPassword = passwordEncoder.encode(member.getPassword()); @@ -34,7 +29,6 @@ public Member createMember(Member member) { List roles = authorityUtils.createRoles(member.getEmail()); member.setRoles(roles); return memberRepository.save(member); - } public Member createOauth2Member(Member member) { @@ -60,9 +54,8 @@ private void verifyExistsEmail(String email) { throw new BusinessLogicException(ExceptionCode.MEMBER_EXISTS); } - // 멤버 업데이트 public Member updateMember(Member member) { - Member findMember = findVerifiedMemberById(member.getMemberId()); + Member findMember = findMemberByMemberId(member.getMemberId()); Optional.ofNullable(member.getUsername()) .ifPresent(name -> findMember.setUsername(name)); Optional.ofNullable(member.getPhoneNumber()) @@ -74,37 +67,30 @@ public Member updateMember(Member member) { return memberRepository.save(findMember); } - // 멤버 조회(프로필) - public Member findMember(Long memberId, String email) { - Optional byMemberIdAndEmail = memberRepository.findByMemberIdAndEmail(memberId, email); - return byMemberIdAndEmail.orElseThrow(() -> + public Member findMemberByMemberId(long memberId) { + Optional findMember = memberRepository.findById(memberId); + return findMember.orElseThrow(() -> new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND)); } - public Member findMember(String email) { - Optional byMemberIdAndEmail = memberRepository.findByEmail(email); - return byMemberIdAndEmail.orElseThrow(() -> + public Member findMemberByMemberEmail(String email) { + Optional findMember = memberRepository.findByEmail(email); + return findMember.orElseThrow(() -> new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND)); } - // 멤버 삭제 - public void deleteMember(long memberId) { - Member verifiedMemberById = findVerifiedMemberById(memberId); - memberRepository.delete(verifiedMemberById); + public void deleteMember(Member member) { + memberRepository.delete(member); } + public Member isEqualToClientIdAndMemberId(Long clientId, Long memberId) { + Member member = findMemberByMemberId(memberId); - public Member findVerifiedMemberByEmail(String email) { - Optional findMember = memberRepository.findByEmail(email); - return findMember.orElseThrow(() -> - new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND)); - } + if (!member.getMemberId().equals(clientId)) { + throw new BusinessLogicException(ExceptionCode.CLIENT_IS_NOT_EQUAL); + } - public Member findVerifiedMemberById(long memberId) { - Optional findMember = memberRepository.findById(memberId); - return findMember.orElseThrow(() -> - new BusinessLogicException(ExceptionCode.MEMBER_NOT_FOUND)); + return 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 9abb6150..409b70a1 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 @@ -8,8 +8,7 @@ import com.main36.picha.domain.post.entity.Post; import com.main36.picha.domain.post.mapper.PostMapper; import com.main36.picha.domain.post.service.PostService; -import com.main36.picha.global.exception.BusinessLogicException; -import com.main36.picha.global.exception.ExceptionCode; +import com.main36.picha.global.authorization.resolver.ClientId; import com.main36.picha.global.response.DataResponseDto; import com.main36.picha.global.response.MultiResponseDto; import lombok.RequiredArgsConstructor; @@ -37,10 +36,10 @@ public class PostController { private final PostMapper mapper; private final MemberService memberService; private final AttractionService attractionService; - @PostMapping("/register/{member-id}/{attraction-id}") - public ResponseEntity> registerPost(@PathVariable("member-id") @Positive long memberId, - @PathVariable("attraction-id") @Positive long attractionId, - @Valid @RequestBody PostRegisterDto postRegisterDto) { + @PostMapping("/register/{attraction-id}") + public ResponseEntity> registerPost(@ClientId Long clientId, + @PathVariable("attraction-id") @Positive long attractionId, + @Valid @RequestBody PostDto.Post postRegisterDto) { Post.PostBuilder postBuilder = Post.builder(); Post post = postService.createPost( @@ -48,7 +47,7 @@ public ResponseEntity> registerPost(@Path .postTitle(postRegisterDto.getPostTitle()) .postContent(postRegisterDto.getPostContent()) .hashTagContent(postRegisterDto.getHashTagContent()) - .member(memberService.findVerifiedMemberById(memberId)) + .member(memberService.findMemberByMemberId(clientId)) .attraction(attractionService.findAttraction(attractionId)) .comments(new ArrayList<>()) .build() @@ -57,12 +56,11 @@ public ResponseEntity> registerPost(@Path return new ResponseEntity<>(new DataResponseDto<>(mapper.postToSingleResponseDto(post)), HttpStatus.CREATED); } - @PatchMapping("/edit/{member-id}/{post-id}") - public ResponseEntity> editPost(@PathVariable("member-id") @Positive long memberId, - @PathVariable("post-id") @Positive long postId, - @Valid @RequestBody PostPatchDto postPatchDto) { - verifiedById(memberId, postId); - + @PatchMapping("/edit/{post-id}") + public ResponseEntity> editPost(@ClientId Long clientId, + @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)); @@ -89,7 +87,6 @@ public ResponseEntity> getHomePosts(@RequestParam(defaultVal } - @GetMapping() public ResponseEntity> getAllPosts(@RequestParam(defaultValue = "newest", required = false) String sort, @RequestParam(defaultValue = "1", required = false) @Positive int page, @@ -102,6 +99,15 @@ public ResponseEntity> getAllPosts(@RequestParam(defaultValu mapper.postListToPostPageResponseDtoList(postsByNewest), postsByNewestByPage), HttpStatus.OK); } + @DeleteMapping("/delete/{post-id}") + public ResponseEntity deletePost(@ClientId Long clientId, + @PathVariable("post-id") long postId) { + Post post = postService.verifyClientId(clientId, postId); + postService.erasePost(post); + + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + private static String getString(String sort) { switch (sort) { case "newest": @@ -117,24 +123,4 @@ private static String getString(String sort) { return sort; } - @DeleteMapping("/delete/{member-id}/{post-id}") - public ResponseEntity deletePost(@PathVariable("member-id") long memberId, - @PathVariable("post-id") long postId) { - - Post post = verifiedById(memberId, postId); - postService.erasePost(post); - - return new ResponseEntity<>(HttpStatus.NO_CONTENT); - } - - private Post verifiedById(long memberId, long postId) { - Post post = postService.findPostNoneSetView(postId); - - if (!post.getMember().getMemberId().equals(memberId)) { - throw new BusinessLogicException(ExceptionCode.NOT_AUTHOR); - } - - return post; - } - } diff --git a/server/src/main/java/com/main36/picha/domain/post/dto/PostDto.java b/server/src/main/java/com/main36/picha/domain/post/dto/PostDto.java new file mode 100644 index 00000000..5d407360 --- /dev/null +++ b/server/src/main/java/com/main36/picha/domain/post/dto/PostDto.java @@ -0,0 +1,29 @@ +package com.main36.picha.domain.post.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +public class PostDto { + @Data + public static class Post { + @NotBlank(message = "제목을 입력해주세요.") + private String postTitle; + private String postContent; + private String hashTagContent; + } + + @Data + public static class Patch { + + private Long postId; + @NotBlank(message = "제목을 입력해주세요.") + private String postTitle; + private String postContent; + + //TODO: 정규표현식 적용 -> [] + private String hashTagContent; + + } + +} diff --git a/server/src/main/java/com/main36/picha/domain/post/dto/PostHomeDto.java b/server/src/main/java/com/main36/picha/domain/post/dto/PostHomeDto.java deleted file mode 100644 index 40e9bac3..00000000 --- a/server/src/main/java/com/main36/picha/domain/post/dto/PostHomeDto.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.main36.picha.domain.post.dto; - -import com.main36.picha.domain.member.entity.Member; -import lombok.Builder; -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -@Builder -public class PostHomeDto { - private Long postId; - private Long memberId; - private String username; - private String picture; - private int views; - private int likes; - private String postTitle; - private LocalDateTime createdAt; - private LocalDateTime modifiedAt; -} diff --git a/server/src/main/java/com/main36/picha/domain/post/dto/PostPatchDto.java b/server/src/main/java/com/main36/picha/domain/post/dto/PostPatchDto.java deleted file mode 100644 index 8c0b0430..00000000 --- a/server/src/main/java/com/main36/picha/domain/post/dto/PostPatchDto.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.main36.picha.domain.post.dto; - -import lombok.Builder; -import lombok.Data; - -import javax.validation.constraints.NotBlank; - -@Data -public class PostPatchDto { - - private Long postId; - @NotBlank(message = "제목을 입력해주세요.") - private String postTitle; - private String postContent; - - //TODO: 정규표현식 적용 -> [] - private String hashTagContent; - -} diff --git a/server/src/main/java/com/main36/picha/domain/post/dto/PostRegisterDto.java b/server/src/main/java/com/main36/picha/domain/post/dto/PostRegisterDto.java deleted file mode 100644 index f6e79516..00000000 --- a/server/src/main/java/com/main36/picha/domain/post/dto/PostRegisterDto.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.main36.picha.domain.post.dto; - -import lombok.*; - -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Null; - - -@Data -public class PostRegisterDto { - @NotBlank(message = "제목을 입력해주세요.") - private String postTitle; - private String postContent; - private String hashTagContent; -} diff --git a/server/src/main/java/com/main36/picha/domain/post/dto/SinglePostResponseDto.java b/server/src/main/java/com/main36/picha/domain/post/dto/PostResponseDto.java similarity index 65% rename from server/src/main/java/com/main36/picha/domain/post/dto/SinglePostResponseDto.java rename to server/src/main/java/com/main36/picha/domain/post/dto/PostResponseDto.java index eca2f5c9..bd302687 100644 --- a/server/src/main/java/com/main36/picha/domain/post/dto/SinglePostResponseDto.java +++ b/server/src/main/java/com/main36/picha/domain/post/dto/PostResponseDto.java @@ -12,7 +12,8 @@ @Data @Setter(AccessLevel.NONE) @Builder -public class SinglePostResponseDto { +public class PostResponseDto { + private long postId; private String postTitle; private String postContent; @@ -28,4 +29,19 @@ public class SinglePostResponseDto { private LocalDateTime createdAt; private LocalDateTime modifiedAt; + + @Data + @Builder + public static class Home { + private Long postId; + private Long memberId; + private String username; + private String picture; + private int views; + private int likes; + private String postTitle; + private LocalDateTime createdAt; + private LocalDateTime modifiedAt; + } + } diff --git a/server/src/main/java/com/main36/picha/domain/post/mapper/PostMapper.java b/server/src/main/java/com/main36/picha/domain/post/mapper/PostMapper.java index 7a0590f7..21be6fe8 100644 --- a/server/src/main/java/com/main36/picha/domain/post/mapper/PostMapper.java +++ b/server/src/main/java/com/main36/picha/domain/post/mapper/PostMapper.java @@ -1,11 +1,7 @@ package com.main36.picha.domain.post.mapper; -import com.main36.picha.domain.attraction.entity.Attraction; import com.main36.picha.domain.comment.dto.CommentResponseDto; -import com.main36.picha.domain.comment.entity.Comment; -import com.main36.picha.domain.member.entity.Member; -import com.main36.picha.domain.member.service.MemberService; import com.main36.picha.domain.post.dto.*; import com.main36.picha.domain.post.entity.Post; import org.mapstruct.Mapper; @@ -18,15 +14,15 @@ @Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public interface PostMapper { - Post postPatchDtoToPost(PostPatchDto postPatchDto); + Post postPatchDtoToPost(PostDto.Patch postPatchDto); - default SinglePostResponseDto postToSingleResponseDto(Post post) { + default PostResponseDto postToSingleResponseDto(Post post) { if (post == null) { return null; } - return SinglePostResponseDto.builder() + return PostResponseDto.builder() .postId(post.getPostId()) .postTitle(post.getPostTitle()) .postContent(post.getPostContent()) @@ -58,16 +54,16 @@ default SinglePostResponseDto postToSingleResponseDto(Post post) { @Mapping(target = "memberId", expression = "java(post.getMember().getMemberId())") @Mapping(target = "username", expression = "java(post.getMember().getUsername())") @Mapping(target = "picture", expression = "java(post.getMember().getPicture())") - PostHomeDto postToPostHomeDto(Post post); + PostResponseDto.Home postToPostHomeDto(Post post); - default List postListToPostHomeResponseDtoList(List postList) { + default List postListToPostHomeResponseDtoList(List postList) { if (postList == null) { return null; } return postList.stream() .map(post -> { - return PostHomeDto.builder() + return PostResponseDto.Home.builder() .postId(post.getPostId()) .memberId(post.getMember().getMemberId()) .username(post.getMember().getUsername()) @@ -82,7 +78,7 @@ default List postListToPostHomeResponseDtoList(List postList) } - default List postListToPostPageResponseDtoList(List postList) { + default List postListToPostPageResponseDtoList(List postList) { if (postList == null) { return null; @@ -90,7 +86,7 @@ default List postListToPostPageResponseDtoList(List return postList.stream() .map(post -> { - return SinglePostResponseDto.builder() + return PostResponseDto.builder() .postId(post.getPostId()) .postTitle(post.getPostTitle()) .postContent(post.getPostContent()) 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 6eae5a12..e34aff3b 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 @@ -72,8 +72,17 @@ public Page findAllPostsBySort(int page, int size, String sort) { } public void erasePost(Post post) { - postRepository.delete(post); + postRepository.delete( post); } + public Post verifyClientId(Long clientId, Long postId) { + Post post = findPost(postId); + + if (!post.getMember().getMemberId().equals(clientId)) { + throw new BusinessLogicException(ExceptionCode.CLIENT_IS_NOT_EQUAL); + } + + return post; + } } diff --git a/server/src/main/java/com/main36/picha/global/authorization/handler/OAuth2MemberSuccessHandler.java b/server/src/main/java/com/main36/picha/global/authorization/handler/OAuth2MemberSuccessHandler.java index 570eee5a..a83606d2 100644 --- a/server/src/main/java/com/main36/picha/global/authorization/handler/OAuth2MemberSuccessHandler.java +++ b/server/src/main/java/com/main36/picha/global/authorization/handler/OAuth2MemberSuccessHandler.java @@ -72,7 +72,8 @@ private String delegateAccessToken(String username, List authorities) { claims.put("username", username); claims.put("roles", authorities); - String subject = username; + var subject = username; + Date expiration = jwtTokenizer.getTokenExpiration(jwtTokenizer.getAccessTokenExpirationMinutes()); String base64EncodedSecretKey = jwtTokenizer.encodeBase64SecretKey(jwtTokenizer.getSecretKey()); diff --git a/server/src/main/java/com/main36/picha/global/authorization/jwt/JwtTokenizer.java b/server/src/main/java/com/main36/picha/global/authorization/jwt/JwtTokenizer.java index 0a8cb24c..e580e157 100644 --- a/server/src/main/java/com/main36/picha/global/authorization/jwt/JwtTokenizer.java +++ b/server/src/main/java/com/main36/picha/global/authorization/jwt/JwtTokenizer.java @@ -1,5 +1,7 @@ package com.main36.picha.global.authorization.jwt; +import com.main36.picha.domain.member.entity.Member; +import com.main36.picha.domain.member.service.MemberService; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; @@ -7,6 +9,7 @@ import io.jsonwebtoken.io.Encoders; import io.jsonwebtoken.security.Keys; import lombok.Getter; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -20,8 +23,11 @@ @Slf4j @Component +@RequiredArgsConstructor public class JwtTokenizer { + private final MemberService memberService; + @Getter @Value("${jwt.secret-key}") private String secretKey; @@ -110,4 +116,9 @@ public String getUsername(HttpServletRequest request) { return String.valueOf(claims.getBody().get("username")); } + public Long getUserId(HttpServletRequest request) { + Member member = memberService.findMemberByMemberEmail( getUsername(request)); + + return member.getMemberId(); + } } diff --git a/server/src/main/java/com/main36/picha/global/authorization/resolver/LoginUser.java b/server/src/main/java/com/main36/picha/global/authorization/resolver/ClientId.java similarity index 90% rename from server/src/main/java/com/main36/picha/global/authorization/resolver/LoginUser.java rename to server/src/main/java/com/main36/picha/global/authorization/resolver/ClientId.java index 33bd2807..52619579 100644 --- a/server/src/main/java/com/main36/picha/global/authorization/resolver/LoginUser.java +++ b/server/src/main/java/com/main36/picha/global/authorization/resolver/ClientId.java @@ -7,5 +7,5 @@ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) -public @interface LoginUser { +public @interface ClientId { } 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 6fa5a62c..5dd296b8 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 @@ -1,7 +1,10 @@ package com.main36.picha.global.authorization.resolver; -import com.main36.picha.global.authorization.dto.LoginDto; +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 lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; import org.springframework.web.bind.support.WebDataBinderFactory; @@ -11,13 +14,17 @@ import javax.servlet.http.HttpServletRequest; + +@Slf4j +@RequiredArgsConstructor @Component public class UserArgumentResolver implements HandlerMethodArgumentResolver { - + private final JwtTokenizer jwtTokenizer; + private final MemberService memberService; @Override public boolean supportsParameter(MethodParameter parameter) { - return parameter.getParameterAnnotation(LoginUser.class) != null + return parameter.getParameterAnnotation(ClientId.class) != null && parameter.getParameterType().equals(Long.class); // return isLoginUserAnnotation && isUserClass; @@ -25,19 +32,21 @@ public boolean supportsParameter(MethodParameter parameter) { } @Override - public Object resolveArgument(MethodParameter parameter, + public Long resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { - HttpServletRequest httpServletRequest = (HttpServletRequest) webRequest.getNativeRequest(); - return httpServletRequest.getHeader("User-Agent"); -// String token = JwtTokenizer.getUsername(httpServletRequest); -// JwtUtil.validateToken(token); -// -// String userId = JwtUtil.getPayload(token); -// String ipAddress = httpServletRequest.getRemoteAddr(); + HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); + + return jwtTokenizer.getUserId(request); + + //Object getPrincipal(); // 주로 ID + //Object getDetails(); // 사용자 상세정보 + // -// return new UserDto(userId, ipAddress); +// 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 22853a72..696b2591 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 @@ -20,6 +20,7 @@ import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.util.AntPathMatcher; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @@ -39,6 +40,7 @@ public class SecurityConfiguration { private final MemberMapper mapper; private final MemberRepository memberRepository; + @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http @@ -57,8 +59,14 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .apply(new CustomFilterConfigure()) .and() .authorizeHttpRequests(authorize -> authorize - .antMatchers("/", "/users/signup", "/users/login", "/users/token/**", - "/main", "/attractions", "/attractions/**", "/posts", "/posts/*", "/comments", "comments/*").permitAll() + .antMatchers( + "/", + "/signup", + "/login", + "/token", + "/attractions", "/attractions/**", + "/posts", "/posts/*", + "/comments", "comments/*").permitAll() .antMatchers("admin").hasRole("ADMIN") .requestMatchers(toH2Console()).permitAll() .anyRequest().authenticated() @@ -94,7 +102,7 @@ public void configure(HttpSecurity builder) throws Exception { AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class); JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager); - jwtAuthenticationFilter.setFilterProcessesUrl("/users/login"); + jwtAuthenticationFilter.setFilterProcessesUrl("/login"); jwtAuthenticationFilter.setAuthenticationSuccessHandler(new MemberAuthenticationSuccessHandler(jwtTokenizer)); jwtAuthenticationFilter.setAuthenticationFailureHandler(new MemberAuthenticationFailureHandler()); diff --git a/server/src/main/java/com/main36/picha/global/config/WebMvcConfig.java b/server/src/main/java/com/main36/picha/global/config/WebMvcConfig.java index 0a4df19a..35982954 100644 --- a/server/src/main/java/com/main36/picha/global/config/WebMvcConfig.java +++ b/server/src/main/java/com/main36/picha/global/config/WebMvcConfig.java @@ -1,9 +1,7 @@ package com.main36.picha.global.config; -import com.main36.picha.global.authorization.resolver.LoginUser; import com.main36.picha.global.authorization.resolver.UserArgumentResolver; import lombok.RequiredArgsConstructor; -import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.Configuration; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.CorsRegistry; @@ -28,7 +26,4 @@ public void addArgumentResolvers(List resolvers) resolvers.add(userArgumentResolver); } -// public static void main(String[] args) { -// SpringApplication.run(WebMvcConfig.class, args); -// } } \ No newline at end of file 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 0404605e..47606c69 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,6 +7,8 @@ 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"), + ATTRACTION_NOT_FOUND(404, "Attraction not found"), ATTRACTION_EXISTS(409, "Attraction exists"),