Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Refactor/83-스프링 시큐리티를 전체 API에 적용하기 #84

Merged
merged 3 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package org.example.tree.domain.branch.controller;

import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.example.tree.domain.branch.dto.BranchResponseDTO;
import org.example.tree.domain.branch.service.BranchService;
import org.example.tree.domain.member.entity.Member;
import org.example.tree.global.common.ApiResponse;
import org.example.tree.global.security.handler.annotation.AuthMember;
import org.springframework.web.bind.annotation.*;

@RestController
Expand All @@ -16,10 +19,9 @@ public class BranchController {
public ApiResponse<BranchResponseDTO.branchView> getBranchView(
@PathVariable Long treeId,
@RequestParam("memberId") Long profileId,
@RequestHeader("Authorization") final String header
@AuthMember @Parameter(hidden = true) Member member
) {
String token = header.replace("Bearer ", "");
return ApiResponse.onSuccess(branchService.getBranchView(treeId, token, profileId));
return ApiResponse.onSuccess(branchService.getBranchView(treeId, member, profileId));
}

@GetMapping("/trees/{treeId}/branchView/all")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ public void createBranch(Tree tree,Profile inviter, Profile invitee) {
// return branch.getBranchDegree();
// }

/**
* 특정 멤버 사이의 Branch Degree를 계산합니다.
* @param treeId
* @param rootId
* @param leafId
* @return branchDegree(int)
*/
public int calculateBranchDegree(Long treeId, Long rootId, Long leafId) {
// 두 멤버 사이의 모든 Branch 엔티티를 찾습니다.
List<Branch> branches = branchQueryService.findAllBranchesInTree(treeId);
Expand All @@ -48,6 +55,14 @@ public int calculateBranchDegree(Long treeId, Long rootId, Long leafId) {
return shortestDistance;
}

/**
* 특정 멤버까지의 브랜치 최단 거리를 계산합니다.
* @param branches
* @param startMemberId
* @param endMemberId
* @return ShortestPathResult(최단 거리 결과 DTO)
*/

public BranchResponseDTO.ShortestPathResult findShortestDistance(List<Branch> branches, Long startMemberId, Long endMemberId) {
Map<Long, List<Long>> adjacencyList = new HashMap<>();
Map<Long, Long> prev = new HashMap<>();
Expand Down Expand Up @@ -91,13 +106,19 @@ public BranchResponseDTO.ShortestPathResult findShortestDistance(List<Branch> br
return branchConverter.toShortestPathResult(distance, path);
}

/**
* 트리하우스 내의 두 멤버 사이의 최단 거리를 계산하고, 그에 따른 BranchView를 반환합니다.
* @param treeId
* @param member
* @param leafId
* @return branchView(DTO)
*/
@Transactional
public BranchResponseDTO.branchView getBranchView(Long treeId, String token, Long leafId) {
Member member = memberQueryService.findByToken(token);
public BranchResponseDTO.branchView getBranchView(Long treeId, Member member, Long leafId) {
Tree tree = treeQueryService.findById(treeId);
List<Branch> branches = branchQueryService.findAllBranchesInTree(treeId);
Long rootId = profileQueryService.getTreeProfile(member, tree).getId();
BranchResponseDTO.ShortestPathResult result = findShortestDistance(branches, rootId, leafId);
List<Branch> branches = branchQueryService.findAllBranchesInTree(treeId); // 해당 트리의 모든 Branch 조회
Long rootId = profileQueryService.getTreeProfile(member, tree).getId(); // 시작 노드 ID는 현재 사용자의 ID
BranchResponseDTO.ShortestPathResult result = findShortestDistance(branches, rootId, leafId); // 최단 거리 계산

// Node 정보 생성
List<BranchResponseDTO.NodeDTO> nodes = result.getPath().stream()
Expand All @@ -115,6 +136,12 @@ public BranchResponseDTO.branchView getBranchView(Long treeId, String token, Lon
return branchConverter.toBranchView(nodes, links, rootId, leafId);
}

/**
* 트리하우스 내의 모든 Branch를 조회하고, 그에 따른 전체 BranchView를 반환합니다.
* @param treeId
* @return branchView(DTO)
*/

@Transactional
public BranchResponseDTO.branchView getCompleteBranchView(Long treeId) {
List<Branch> branches = branchQueryService.findAllBranchesInTree(treeId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package org.example.tree.domain.invitation.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.example.tree.domain.invitation.dto.InvitationRequestDTO;
import org.example.tree.domain.invitation.dto.InvitationResponseDTO;
import org.example.tree.domain.invitation.service.InvitationService;
import org.example.tree.domain.member.entity.Member;
import org.example.tree.global.common.ApiResponse;
import org.example.tree.global.security.handler.annotation.AuthMember;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand Down Expand Up @@ -51,18 +54,16 @@ public ApiResponse<InvitationResponseDTO.rejectInvitation> rejectInvitation(
@GetMapping("/users/invitation")
@Operation(summary = "초대장 조회", description = "내가 받은 초대장을 조회합니다.")
public ApiResponse<List<InvitationResponseDTO.getInvitation>> getInvitation(
@RequestHeader("Authorization") final String header
@AuthMember @Parameter(hidden = true) Member member
) {
String token = header.replace("Bearer ", "");
return ApiResponse.onSuccess(invitationService.getInvitation(token));
return ApiResponse.onSuccess(invitationService.getInvitation(member));
}

@GetMapping("/users/availableInvitation")
@Operation(summary = "가용 초대장 조회", description = "내가 보낼 수 있는 초대장 개수를 조회합니다.")
public ApiResponse<InvitationResponseDTO.getAvailableInvitation> getAvailableInvitation(
@RequestHeader("Authorization") final String header
@AuthMember @Parameter(hidden = true) Member member
) {
String token = header.replace("Bearer ", "");
return ApiResponse.onSuccess(invitationService.getAvailableInvitation(token));
return ApiResponse.onSuccess(invitationService.getAvailableInvitation(member));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.example.tree.domain.invitation.dto.InvitationResponseDTO;
import org.example.tree.domain.invitation.entity.Invitation;
import org.example.tree.domain.invitation.entity.InvitationStatus;
import org.example.tree.domain.member.entity.Member;
import org.example.tree.domain.profile.entity.Profile;
import org.example.tree.domain.tree.entity.Tree;
Expand All @@ -17,6 +18,7 @@ public Invitation toInvitation (Profile sender, Tree tree, String phone) {
.sender(sender)
.tree(tree)
.phone(phone)
.status(InvitationStatus.PENDING)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,12 @@ public InvitationResponseDTO.rejectInvitation rejectInvitation(InvitationRequest
}

@Transactional
public InvitationResponseDTO.getAvailableInvitation getAvailableInvitation(String token) {
Member member = memberQueryService.findByToken(token);
public InvitationResponseDTO.getAvailableInvitation getAvailableInvitation(Member member) {
return invitationConverter.toGetAvailableInvitation(member);
}

@Transactional
public List<InvitationResponseDTO.getInvitation> getInvitation(String token) {
Member member = memberQueryService.findByToken(token);
public List<InvitationResponseDTO.getInvitation> getInvitation(Member member) {
List<Invitation> invitations= invitationQueryService.findAllByPhone(member.getPhone());
return invitations.stream()
.map(invitation -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package org.example.tree.domain.notification.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.example.tree.domain.member.entity.Member;
import org.example.tree.domain.notification.dto.NotificationRequestDTO;
import org.example.tree.domain.notification.dto.NotificationResponseDTO;
import org.example.tree.domain.notification.service.NotificationService;
import org.example.tree.global.common.ApiResponse;
import org.example.tree.global.security.handler.annotation.AuthMember;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand All @@ -29,10 +32,9 @@ public ApiResponse sendNotification(
@Operation(summary = "전체 알림 조회", description = "유저가 받은 알림들을 조회합니다.")
@GetMapping
public ApiResponse<List<NotificationResponseDTO.getNotification>> getNotifications(
@RequestHeader("Authorization") final String header)
{
String token = header.replace("Bearer ", "");
return ApiResponse.onSuccess(notificationService.getUserNotifications(token));
@AuthMember @Parameter(hidden = true) Member member
) {
return ApiResponse.onSuccess(notificationService.getUserNotifications(member));
}

@Operation(summary = "특정 알림 조회", description = "유저가 받은 알림 중 하나를 조회합니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ public void invitationNotification(Profile sender, Invitation invitation, String
notificationCommandService.createNotification(notification);
}

public List<NotificationResponseDTO.getNotification> getUserNotifications(String token) {
Member member = memberQueryService.findByToken(token);
public List<NotificationResponseDTO.getNotification> getUserNotifications(Member member) {
List<Notification> notifications = notificationQueryService.getNotifications(member);
return notifications.stream()
.map(notificationConverter::toGetNotification)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public class PostController {
private final PostService postService;

@PostMapping("/trees/{treeId}/feed/posts")
@Operation(summary = "게시글 작성", description = "게시글을 작성합니다.")
public ApiResponse<PostResponseDTO.createPost> createPost(
@PathVariable final Long treeId,
@RequestBody final PostRequestDTO.createPost request,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package org.example.tree.domain.profile.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.example.tree.domain.member.entity.Member;
import org.example.tree.domain.profile.dto.ProfileRequestDTO;
import org.example.tree.domain.profile.service.ProfileService;
import org.example.tree.domain.tree.dto.TreeRequestDTO;
import org.example.tree.global.common.ApiResponse;
import org.example.tree.global.security.handler.annotation.AuthMember;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
Expand Down Expand Up @@ -34,20 +37,18 @@ public ApiResponse registerTreeMember(
@GetMapping("/trees/{treeId}/members/{profileId}") //프로필 조회
@Operation(summary = "멤버 프로필 조회", description = "트리하우스 속 특정 멤버의 프로필을 조회합니다.")
public ApiResponse getProfileDetails(
@RequestHeader("Authorization") final String header,
@AuthMember @Parameter(hidden = true) Member member,
@PathVariable Long treeId,
@PathVariable Long profileId) {
String token = header.replace("Bearer ", "");
return ApiResponse.onSuccess(profileService.getProfileDetails(token, profileId));
return ApiResponse.onSuccess(profileService.getProfileDetails(member, profileId));
}

@GetMapping("/trees/{treeId}/myProfile") //내 프로필 조회
@Operation(summary = "내 프로필 조회", description = "트리하우스 속 내 프로필을 조회합니다.")
public ApiResponse getMyProfile(
@RequestHeader("Authorization") final String header,
@AuthMember @Parameter(hidden = true) Member member,
@PathVariable Long treeId
) {
String token = header.replace("Bearer ", "");
return ApiResponse.onSuccess(profileService.getMyProfile(token, treeId));
return ApiResponse.onSuccess(profileService.getMyProfile(member, treeId));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,14 @@ public Profile getTreeProfile(Member member, Long treeId) {
return profileQueryService.getTreeProfile(member,tree);
}

/**
* 트리하우스 내 다른 멤버의 프로필 조회
* @param member //본인
* @param profileId //조회할 프로필의 id
* @return ProfileResponseDTO.getProfileDetails //프로필 조회 결과
*/
@Transactional
public ProfileResponseDTO.getProfileDetails getProfileDetails(String token, Long profileId) {
Member member = memberQueryService.findByToken(token);
public ProfileResponseDTO.getProfileDetails getProfileDetails(Member member, Long profileId) {
Profile profile = profileQueryService.findById(profileId);
Tree tree = profile.getTree();
Profile myProfile = profileQueryService.getTreeProfile(member,tree);
Expand All @@ -86,9 +91,14 @@ public ProfileResponseDTO.getProfileDetails getProfileDetails(String token, Long
return profileConverter.toGetProfileDetails(profile, treeIds, branchDegree);
}

/**
* 내 프로필 조회
* @param member //본인
* @param treeId //조회할 트리하우스의 id
* @return ProfileResponseDTO.getProfileDetails //프로필 조회 결과
*/
@Transactional
public ProfileResponseDTO.getProfileDetails getMyProfile(String token, Long treeId) {
Member member = memberQueryService.findByToken(token);
public ProfileResponseDTO.getProfileDetails getMyProfile(Member member, Long treeId) {
Tree tree = treeQueryService.findById(treeId);
Profile profile = profileQueryService.getTreeProfile(member,tree);
List<Long> treeIds = profileQueryService.findJoinedTree(profile);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package org.example.tree.domain.tree.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.example.tree.domain.member.entity.Member;
import org.example.tree.domain.tree.dto.TreeRequestDTO;
import org.example.tree.domain.tree.dto.TreeResponseDTO;
import org.example.tree.domain.tree.service.TreeService;
import org.example.tree.global.common.ApiResponse;
import org.example.tree.global.security.handler.annotation.AuthMember;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand All @@ -28,21 +31,18 @@ public ApiResponse createTree(
@Operation(summary = "트리하우스 조회")
@GetMapping
public ApiResponse<List<TreeResponseDTO.getTree>> getTrees(
@RequestHeader("Authorization") final String header
)
{
String token = header.replace("Bearer ", "");
return ApiResponse.onSuccess(treeService.getTrees(token));
@AuthMember @Parameter(hidden = true) Member member
) {
return ApiResponse.onSuccess(treeService.getTrees(member));
}

@Operation(summary = "트리하우스 위치 변경")
@PostMapping("/{treeId}")
public ApiResponse<TreeResponseDTO.shiftTree> shiftTree(
@RequestHeader("Authorization") final String header,
@AuthMember @Parameter(hidden = true) Member member,
@PathVariable final Long treeId
) {
String token = header.replace("Bearer ", "");
return ApiResponse.onSuccess(treeService.shiftTree(treeId, token));
return ApiResponse.onSuccess(treeService.shiftTree(treeId, member));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ public void createTree(TreeRequestDTO.createTree request) {
}

@Transactional
public List<TreeResponseDTO.getTree> getTrees(String token) {
Member member = memberQueryService.findByToken(token);
public List<TreeResponseDTO.getTree> getTrees(Member member) {
Profile currentProfile = profileQueryService.getCurrentProfile(member);
List<Long> treeIds = profileQueryService.findJoinedTree(currentProfile);
List<Tree> trees = treeIds.stream()
Expand All @@ -51,8 +50,7 @@ public List<TreeResponseDTO.getTree> getTrees(String token) {
}

@Transactional
public TreeResponseDTO.shiftTree shiftTree(Long treeId, String token) {
Member member = memberQueryService.findByToken(token);
public TreeResponseDTO.shiftTree shiftTree(Long treeId, Member member) {
Tree tree = treeQueryService.findById(treeId);
Profile currentProfile = profileQueryService.getCurrentProfile(member);
currentProfile.inactivate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public class GlobalWebConfig implements WebMvcConfigurer {

private final AuthMemberArgumentResolver authMemberArgumentResolver;

/**
* 컨트롤러 메서드의 특정 파라미터를 지원하는 커스텀한 ArgumentResolver를 추가
* @param resolverList
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolverList) {
resolverList.add(authMemberArgumentResolver);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ public class SecurityConfig {
private final JwtAuthenticationExceptionHandler jwtAuthenticationExceptionHandler =
new JwtAuthenticationExceptionHandler();

/**
* 특정 경로에 대한 보안 설정을 무시하도록 설정
* @return WebSecurityCustomizer
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) ->
Expand Down Expand Up @@ -83,10 +87,10 @@ public CorsConfigurationSource corsConfiguration() {
return request -> {
org.springframework.web.cors.CorsConfiguration config =
new org.springframework.web.cors.CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowedOriginPatterns(Collections.singletonList("*"));
config.setAllowCredentials(true);
config.setAllowedHeaders(Collections.singletonList("*")); // 모든 헤더 허용
config.setAllowedMethods(Collections.singletonList("*")); // 모든 메소드 허용
config.setAllowedOriginPatterns(Collections.singletonList("*")); // 모든 Origin 허용
config.setAllowCredentials(true); // 인증정보 허용
return config;
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
if(StringUtils.hasText(accessToken) && tokenProvider.validateToken(accessToken)) {

Authentication authentication = tokenProvider.getAuthentication(accessToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
SecurityContextHolder.getContext().setAuthentication(authentication); // 인증 정보를 SecurityContext에 설정

}
else{
Expand Down
Loading
Loading