Skip to content

Commit

Permalink
Merge pull request #126 from swm-nodriversomabus/FIX-DEV-SECURITY-114
Browse files Browse the repository at this point in the history
Fix dev security 114
  • Loading branch information
namhyo01 authored Oct 19, 2023
2 parents 5a3d765 + 6aaccaf commit 2667b15
Show file tree
Hide file tree
Showing 38 changed files with 237 additions and 202 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,18 @@
import com.example.api.auth.type.TokenResponseStatus;
import com.example.api.auth.utils.CookieUtils;
import com.example.api.common.dto.StatusResponseDto;
import com.example.api.common.utils.AuthenticationUtils;
import com.example.api.user.domain.User;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Optional;
import java.util.UUID;

@Slf4j
@RestController
@Slf4j
@RequiredArgsConstructor
@RefreshScope
public class AuthController {
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/com/example/api/auth/domain/SecurityUser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.api.auth.domain;
import lombok.Builder;
import lombok.Getter;

import java.util.UUID;

@Builder
@Getter
public class SecurityUser {
private UUID userId;

private String naverId;

private String kakaoId;

private String googleId;

private String instaId;

private String appleId;

private String role;
}
7 changes: 4 additions & 3 deletions src/main/java/com/example/api/auth/filter/JwtAuthFilter.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.api.auth.filter;


import com.example.api.auth.domain.SecurityUser;
import com.example.api.auth.dto.SecurityUserDto;
import com.example.api.auth.service.JwtUtilService;
import com.example.api.chat.exception.JwtException;
Expand Down Expand Up @@ -83,7 +84,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
// UserEntity user = userService.findSocialUser(jwtUtilService.getId(atc), jwtUtilService.getProvider(atc))
// .orElseThrow(IllegalStateException::new);
// Security Context에 등록할 user 객체 생성
User userinfo = userService.findSocialUser(jwtUtilService.getId(atc), jwtUtilService.getProvider(atc));
SecurityUser userinfo = userService.findSocialUser(jwtUtilService.getId(atc), jwtUtilService.getProvider(atc));

// Security Context에 인증 객체 등록
Authentication authentication = getAuthentication(userinfo);
Expand All @@ -94,10 +95,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
filterChain.doFilter(request, response);
}

public Authentication getAuthentication(User user){
public Authentication getAuthentication(SecurityUser user){

return new UsernamePasswordAuthenticationToken(user, "",
List.of(new SimpleGrantedAuthority(user.getRole().toString()))
List.of(new SimpleGrantedAuthority(user.getRole()))
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@Slf4j
@RequiredArgsConstructor
@Tag(name = "Chat", description = "Chat API")
public class ChatController {
Expand All @@ -35,17 +35,17 @@ public class ChatController {

/**
* 추후에 jwt 인증을 통해 유저 데이터를 불러와 message에 추가할 예정
* @param roomNumber (ID)
* @param roomId (ID)
* @param message (데이터)
*/
@Operation(summary = "Send message", description = "채팅방에 메시지를 보낸다.")
@MessageMapping("/chat/{roomNumber}")
public void sendMessage(@DestinationVariable String roomNumber, AddChatDto message, String contentType, @RequestParam("file") MultipartFile file) {
log.info("roomNumber : {}", roomNumber);
@MessageMapping("/chat/{roomId}")
public void sendMessage(@DestinationVariable String roomId, AddChatDto message, String contentType, @RequestParam("file") MultipartFile file) {
log.info("roomId : {}", roomId);
if (contentType.equals("image")) {
message.setContent(uploadFileUsecase.uploadFile(file));
}
sendChatUsecase.send(roomNumber, message);
sendChatUsecase.send(roomId, message);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,21 @@

import java.util.List;
import java.util.UUID;
@Slf4j

@RestController
@RequestMapping("/chatroom")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "ChatRoom", description = "ChatRoom API")
public class ChatRoomController {
private final CreateChatRoomUsecase createChatRoomUsecase;
private final FindChatRomListUsecase findChatRomListUsecase;
/**
* 채팅방 생성
* @param createChatRoomDto (Data)
* @return 채팅 방 ID 값
* @param createChatRoomDto (데이터)
* @return UUID
*/
@Operation(summary = "Create chatroom", description = "새로운 채팅방을 생성한다.")
@PostMapping
@PostMapping("/chatroom")
public UUID createChatroom(@RequestBody @Valid CreateChatRoomDto createChatRoomDto){
ChatRoom chatRoom = createChatRoomUsecase.createRoom(createChatRoomDto);
return chatRoom.getChatroomId();
Expand All @@ -42,13 +42,13 @@ public UUID createChatroom(@RequestBody @Valid CreateChatRoomDto createChatRoomD
* @return List<ChatRoom>
*/
@Operation(summary = "Get chatroom list", description = "사용자의 채팅방 목록을 불러온다.")
@GetMapping
@GetMapping("/chatroom")
public List<ChatRoom> chatRoomList(@RequestParam Long userid, @PageableDefault(sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) { //추후 바꾸자함
return findChatRomListUsecase.chatRoomList(pageable, userid);
}

@Operation(summary = "Delete chatroom", description = "채팅방을 삭제한다.")
@DeleteMapping(value = "/{chatRoomId}")
@DeleteMapping("/chatroom/{chatRoomId}")
public void outChatRoom(@PathVariable UUID chatRoomId){
log.info("chatroom = {}", chatRoomId);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.api.common.utils;

import com.example.api.auth.domain.SecurityUser;
import com.example.api.user.domain.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -9,10 +10,10 @@
* 이걸로 유저 정보를 가져오자
*/
public class AuthenticationUtils {
public static User getCurrentUserAuthentication(){
public static SecurityUser getCurrentUserAuthentication(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof User){
return (User) authentication.getPrincipal();
if (authentication != null && authentication.getPrincipal() instanceof SecurityUser){
return (SecurityUser) authentication.getPrincipal();
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ public FriendDto addFriend(@RequestBody FriendDto friendDto) {

/**
* 친구 목록 조회
* @param userId (ID)
* @return List<UserDto>
*/
@Operation(summary = "Get friend list", description = "사용자의 친구 목록을 조회한다.")
@GetMapping("/user/{userId}/friend")
public List<FindUserDto> getFriendList(@PathVariable String userId) {
return findFriendUsecase.getFriendList(userId);
@GetMapping("/user/friend")
public List<FindUserDto> getFriendList() {
return findFriendUsecase.getFriendList();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
import java.util.List;

public interface FindFriendUsecase {
List<FindUserDto> getFriendList(String userId);
List<FindUserDto> getFriendList();
}
20 changes: 11 additions & 9 deletions src/main/java/com/example/api/friend/service/FriendService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.example.api.friend.service;

import com.example.api.auth.domain.SecurityUser;
import com.example.api.common.utils.AuthenticationUtils;
import com.example.api.friend.adapter.out.persistence.FriendEntity;
import com.example.api.friend.adapter.out.persistence.FriendMapperInterface;
import com.example.api.friend.application.port.in.AddFriendUsecase;
Expand All @@ -20,7 +22,6 @@

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
Expand All @@ -42,15 +43,16 @@ public FriendDto addFriend(FriendDto friendDto) {
}

@Override
public List<FindUserDto> getFriendList(String userId) {
public List<FindUserDto> getFriendList() {
SecurityUser securityUser = AuthenticationUtils.getCurrentUserAuthentication();
if (securityUser == null) {
log.error("FriendService::getFriendList: Authentication is needed.");
return new ArrayList<>();
}
List<FindUserDto> friendList = new ArrayList<>();
try {
List<FriendEntity> friendPairList = findFriendPort.getFriendList(UUID.fromString(userId));
for (FriendEntity friendPair: friendPairList) {
friendList.add(userMapper.toDto(findUserPort.getByUserId(friendPair.getUserId()).orElseThrow()));
}
} catch (IllegalArgumentException e) {
log.warn("Invalid userId: UUID transform failed.");
List<FriendEntity> friendPairList = findFriendPort.getFriendList(securityUser.getUserId());
for (FriendEntity friendPair: friendPairList) {
friendList.add(userMapper.toDto(findUserPort.getByUserId(friendPair.getUserId()).orElseThrow()));
}
return friendList;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
public interface FindMatchingUsecase {
List<FindMatchingDto> getAll();
Optional<FindMatchingDto> getMatchingById(Long matchingId);
List<FindMatchingDto> getMatchingByWriterId(String userId);
List<FindMatchingDto> getMatchingByWriterId();
List<FindMatchingDto> getMatchingByIsActive(Boolean isActive);
List<FindMatchingDto> getRecommendedMatchingList(String userId);
List<FindMatchingDto> getRecommendedMatchingList();
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

public interface MatchingApplicationUsecase {
ChatRoom createMatchingApplication(MatchingApplicationDto matchingApplicationDto);
List<FindMatchingDto> getByUserIdIsAndStateEquals(String userId, ApplicationStateEnum state);
List<FindMatchingDto> getByUserIdIsAndStateEquals(ApplicationStateEnum state);
List<FindUserDto> getByMatchingIdIsAndStateEquals(Long matchingId, ApplicationStateEnum state);
MatchingApplicationDto updateMatchingApplication(MatchingApplicationDto matchingApplicationDto);
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.example.api.matching.service;

import com.example.api.auth.domain.SecurityUser;
import com.example.api.chatroom.domain.ChatRoom;
import com.example.api.chatroom.dto.CreateChatRoomDto;
import com.example.api.chatroom.service.ChatRoomService;
import com.example.api.chatroom.type.ChatRoomEnum;
import com.example.api.common.type.ApplicationStateEnum;
import com.example.api.common.utils.AuthenticationUtils;
import com.example.api.fcm.dto.FcmDto;
import com.example.api.fcm.service.FcmService;
import com.example.api.matching.adapter.out.persistence.MatchingApplicationEntity;
Expand Down Expand Up @@ -75,18 +77,18 @@ public ChatRoom createMatchingApplication(MatchingApplicationDto matchingApplica
}

@Override
public List<FindMatchingDto> getByUserIdIsAndStateEquals(String userId, ApplicationStateEnum state) {
try {
List<MatchingApplicationEntity> matchingPairList = matchingApplicationPort.getByUserIdIsAndStateEquals(UUID.fromString(userId), state);
List<FindMatchingDto> matchingData = new ArrayList<>();
for (MatchingApplicationEntity matchingPair: matchingPairList) {
matchingData.add(matchingMapper.toDto(findMatchingPort.getByMatchingId(matchingPair.getMatchingId()).orElseThrow()));
}
return matchingData;
} catch (IllegalArgumentException e) {
log.warn("Invalid userId: UUID transform failed.");
public List<FindMatchingDto> getByUserIdIsAndStateEquals(ApplicationStateEnum state) {
SecurityUser securityUser = AuthenticationUtils.getCurrentUserAuthentication();
if (securityUser == null) {
log.error("MatchingApplicationService::getByUserIdAndStateEquals: Authentication is needed.");
return new ArrayList<>();
}
List<MatchingApplicationEntity> matchingPairList = matchingApplicationPort.getByUserIdIsAndStateEquals(securityUser.getUserId(), state);
List<FindMatchingDto> matchingData = new ArrayList<>();
for (MatchingApplicationEntity matchingPair: matchingPairList) {
matchingData.add(matchingMapper.toDto(findMatchingPort.getByMatchingId(matchingPair.getMatchingId()).orElseThrow()));
}
return matchingData;
}

@Override
Expand Down
29 changes: 17 additions & 12 deletions src/main/java/com/example/api/matching/service/MatchingService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.example.api.matching.service;

import com.example.api.auth.domain.SecurityUser;
import com.example.api.common.type.Pair;
import com.example.api.common.utils.AuthenticationUtils;
import com.example.api.matching.adapter.out.persistence.MatchingMapperInterface;
import com.example.api.matching.application.port.in.DeleteMatchingUsecase;
import com.example.api.matching.application.port.in.FindMatchingUsecase;
Expand All @@ -15,7 +17,6 @@
import com.example.api.matching.dto.LikeDto;
import com.example.api.matching.dto.SaveMatchingDto;
import com.example.api.preference.service.PreferenceService;
import com.example.api.user.application.port.in.RecommendedMatchingUsecase;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
Expand All @@ -28,8 +29,7 @@
@Slf4j
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class MatchingService implements
SaveMatchingUsecase, FindMatchingUsecase, DeleteMatchingUsecase, LikeUsecase, RecommendedMatchingUsecase {
public class MatchingService implements SaveMatchingUsecase, FindMatchingUsecase, DeleteMatchingUsecase, LikeUsecase {
private final PreferenceService preferenceService;
private final MatchingMapperInterface matchingMapper;
private final SaveMatchingPort saveMatchingPort;
Expand Down Expand Up @@ -58,15 +58,16 @@ public Optional<FindMatchingDto> getMatchingById(Long matchingId) {
}

@Override
public List<FindMatchingDto> getMatchingByWriterId(String userId) {
try {
return findMatchingPort.getByWriterId(UUID.fromString(userId)).stream()
.map(matchingMapper::toDto)
.collect(Collectors.toList());
} catch (IllegalArgumentException e) {
log.warn("Invalid userId: UUID transform failed.");
public List<FindMatchingDto> getMatchingByWriterId() {
SecurityUser securityUser = AuthenticationUtils.getCurrentUserAuthentication();
if (securityUser == null) {
log.error("MatchingService::getMatchingByWriterId: Authentication is needed.");
return new ArrayList<>();
}
UUID userId = securityUser.getUserId();
return findMatchingPort.getByWriterId(userId).stream()
.map(matchingMapper::toDto)
.collect(Collectors.toList());
}

@Override
Expand All @@ -77,12 +78,16 @@ public List<FindMatchingDto> getMatchingByIsActive(Boolean isActive) {
}

@Override
public List<FindMatchingDto> getRecommendedMatchingList(String userId) {
public List<FindMatchingDto> getRecommendedMatchingList() {
SecurityUser securityUser = AuthenticationUtils.getCurrentUserAuthentication();
if (securityUser == null) {
return new ArrayList<>();
}
List<FindMatchingDto> activeMatchingList = this.getMatchingByIsActive(true); // 유효한 매칭만 뽑아옴
List<Pair<Long, Integer>> matchingScoreList = new ArrayList<>();
for (FindMatchingDto matchingData: activeMatchingList) { // 매칭별로 유사도 점수를 계산함
Long matchingId = matchingData.getMatchingId();
Integer matchingScore = preferenceService.getMatchingScore(userId, matchingId);
Integer matchingScore = preferenceService.getMatchingScore(matchingId);
matchingScoreList.add(new Pair<>(matchingId, matchingScore));
}
matchingScoreList.sort(Comparator.comparing(Pair::getSecond));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class MemberController {

/**
* 방 생성 후, 유저들을 초대해 들어오는 경우
* @param addMemberDto
* @param addMemberDto (데이터)
*/
@Operation(summary = "Add member", description = "채팅방에 사용자를 초대한다.")
@PostMapping(value="/members")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class MemberService implements AddMemberChatRoomUsecase {

/**
* 채팅방에 멤버 추가
* @param addMemberDto (Data)
* @param addMemberDto (데이터)
*/
@Override
@Transactional
Expand Down
Loading

0 comments on commit 2667b15

Please sign in to comment.