Skip to content

Commit

Permalink
Merge pull request #122 from IT-Cotato/feature/121-feature-another-ro…
Browse files Browse the repository at this point in the history
…om-access-error

Feature: 다른 방으로 접근했을 때 에러 추가(# 121)
  • Loading branch information
yooooonshine authored Aug 7, 2024
2 parents 8ab8667 + c26a53d commit 4204c1a
Show file tree
Hide file tree
Showing 21 changed files with 216 additions and 77 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public enum UserErrorCode implements ErrorCode {
ROOM_NOT_FOUND(HttpStatus.NOT_FOUND, "존재하지 않는 방입니다."),
PLACE_NOT_FOUND(HttpStatus.NOT_FOUND, "방에 입력된 장소가 없습니다."),
PLACE_CONFLICT(HttpStatus.CONFLICT, "이미 장소를 저장하였습니다."),
ROOM_TYPE_UNPROCESSABLE(HttpStatus.UNPROCESSABLE_ENTITY, "방의 타입이 일치하지 않습니다."),

VOTE_NOT_FOUND(HttpStatus.NOT_FOUND, "투표를 한 적이 없습니다."),
VOTE_ROOM_NOT_FOUND(HttpStatus.NOT_FOUND, "생성된 투표방이 없습니다."),
Expand All @@ -27,9 +28,7 @@ public enum UserErrorCode implements ErrorCode {
DUPLICATE_VOTE_ROOM(HttpStatus.CONFLICT, "이미 투표방이 존재합니다."),

//5xx
API_INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "API 서버에 문제가 발생하였습니다.")

;
API_INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "API 서버에 문제가 발생하였습니다.");

private final HttpStatus httpStatus;
private final String message;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class JwtProperties {
private Access access;
private Refresh refresh;
private RoomId roomId;
private RoomType roomType;

private String ACCESS_TOKEN_SUBJECT = "AccessToken";
private String REFRESH_TOKEN_SUBJECT = "RefreshToken";
Expand All @@ -41,4 +42,10 @@ public static class Refresh {
public static class RoomId {
private String header;
}

@Getter
@Setter
public static class RoomType {
private String header;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import middle_point_search.backend.common.security.login.handler.LoginSuccessHandler;
import middle_point_search.backend.common.security.login.provider.CustomAuthenticationProvider;
import middle_point_search.backend.domains.member.repository.MemberRepository;
import middle_point_search.backend.domains.room.repository.RoomRepository;

@Configuration
@EnableWebSecurity
Expand All @@ -38,6 +39,7 @@ public class SecurityConfig {
private final CustomAuthenticationProvider authenticationProvider;
private final JwtTokenProvider jwtTokenProvider;
private final MemberRepository memberRepository;
private final RoomRepository roomRepository;

private final SecurityProperties securityProperties;
private final UrlBasedCorsConfigurationSource ConfigurationSource;
Expand Down Expand Up @@ -107,7 +109,7 @@ public JsonNamePwAuthenticationFilter jsonUsernamePasswordLoginFilter() throws E
//JWT 필터 등록
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter(jwtTokenProvider, memberRepository, securityProperties, pathMatcher);
return new JwtAuthenticationFilter(jwtTokenProvider, memberRepository, securityProperties, pathMatcher, roomRepository);
}

//예외 핸들링 필터 등록
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
import middle_point_search.backend.common.properties.SecurityProperties;
import middle_point_search.backend.common.security.jwt.provider.JwtTokenProvider;
import middle_point_search.backend.domains.member.repository.MemberRepository;
import middle_point_search.backend.domains.room.domain.Room;
import middle_point_search.backend.domains.room.domain.RoomType;
import middle_point_search.backend.domains.room.repository.RoomRepository;

@Slf4j
@RequiredArgsConstructor
Expand All @@ -32,6 +35,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final MemberRepository memberRepository;
private final SecurityProperties securityProperties;
private final AntPathMatcher pathMatcher;
private final RoomRepository roomRepository;

@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
Expand All @@ -51,8 +55,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

final String refreshToken = jwtTokenProvider.extractRefreshToken(request).orElse(null);
final String accessToken = jwtTokenProvider.extractAccessToken(request).orElse(null);
final String tokenRoomId = jwtTokenProvider.extractRoomId(accessToken).orElse(null);

final String nowRoomId = jwtTokenProvider.extractRoomId(request).orElse(null);
final String tokenRoomId = jwtTokenProvider.extractRoomId(accessToken).orElse(null);
final RoomType nowRoomType = jwtTokenProvider.extractRoomType(request).orElse(null);
final Room room = roomRepository.findByIdentityNumber(nowRoomId)
.orElseThrow(() -> new CustomException(ROOM_NOT_FOUND));

//1. access토큰이 존재하며, accessToken이 유효하면 인증
//2. access토큰이 존재하며, accesToken이 유효하지 않으면 에러 리턴
Expand All @@ -72,6 +80,11 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
throw new CustomException(UNAUTHORIZED);
}

//토큰의 있는 방의 Type과 헤더릐 RoomType이 같은지 검사
if (nowRoomType != room.getRoomType()) {
throw new CustomException(ROOM_TYPE_UNPROCESSABLE);
}

log.info("access토큰 인증 성공");
Authentication authentication = jwtTokenProvider.getAuthentication(accessToken);
saveAuthentication(authentication);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import middle_point_search.backend.domains.room.domain.RoomType;

public interface JwtTokenProvider {

Expand All @@ -30,6 +31,8 @@ public interface JwtTokenProvider {

Optional<String> extractRoomId(HttpServletRequest request);

Optional<RoomType> extractRoomType(HttpServletRequest request);

Claims parseClaims(String accessToken);

Optional<String> extractName(String accessToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import middle_point_search.backend.common.util.ResponseWriter;
import middle_point_search.backend.domains.member.domain.Member;
import middle_point_search.backend.domains.member.repository.MemberRepository;
import middle_point_search.backend.domains.room.domain.RoomType;

@Transactional(readOnly = true)
@Service
Expand Down Expand Up @@ -161,6 +162,12 @@ public Optional<String> extractRoomId(HttpServletRequest request) {
return Optional.ofNullable(request.getHeader(jwtProperties.getRoomId().getHeader()));
}

@Override
public Optional<RoomType> extractRoomType(HttpServletRequest request) {
String roomType = request.getHeader(jwtProperties.getRoomType().getHeader());
return Optional.ofNullable(RoomType.getRoomTypeByName(roomType));
}

@Override
public Claims parseClaims(String accessToken) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class CustomUserDetailsServiceImpl implements CustomUserDetailsService {
@Transactional
public UserDetails loadUserByUsernameAndRoomId(String roomId, String name, String pw) throws UsernameNotFoundException, RoomNotFoundException {

roomRepository.findRoomByIdentityNumber(roomId);
roomRepository.findByIdentityNumber(roomId);
if (!roomRepository.existsByIdentityNumber(roomId)) {
throw new RoomNotFoundException("해당하는 방이 존재하지 않습니다");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public Member getMember() {
public Room getRoom() {
String roomId = getRoomId();

return roomRepository.findRoomByIdentityNumber(roomId)
return roomRepository.findByIdentityNumber(roomId)
.orElseThrow(() -> new CustomException(ROOM_NOT_FOUND));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class MemberService {
public Member createMember(String roomId, String name, String pw) throws RoomNotFoundException {

pw = encodePassword(pw);
Room room = roomRepository.findRoomByIdentityNumber(roomId)
Room room = roomRepository.findByIdentityNumber(roomId)
.orElseThrow(() -> new RoomNotFoundException("해당하는 방이 존재하지 않습니다"));

//회원 권한 정하기
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public class MidPointController {
AccessToken 필요.""",
parameters = {
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER)
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER),
@Parameter(name = "RoomType", description = "roomType 필요. [TOGETHER, SELF] 중 하나", in = ParameterIn.HEADER)
},
responses = {
@ApiResponse(
Expand All @@ -64,6 +65,10 @@ public class MidPointController {
responseCode = "404",
description = "방에 입력된 장소가 없습니다.",
content = @Content(schema = @Schema(implementation = ErrorResponse.class))
),
@ApiResponse(
responseCode = "422",
description = "방의 타입이 일치하지 않습니다"
)
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,20 +48,21 @@ public class PlaceController {
AccessToken 필요.""",
parameters = {
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER)
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER),
@Parameter(name = "RoomType", description = "roomType 필요. [TOGETHER, SELF] 중 하나", in = ParameterIn.HEADER)
},
responses = {
@ApiResponse(
responseCode = "200",
description = "성공"
),
@ApiResponse(
responseCode = "400",
description = "방 타입이 일치하지 않습니다."
),
@ApiResponse(
responseCode = "401",
description = "인증에 실패하였습니다."
),
@ApiResponse(
responseCode = "422",
description = "방의 타입이 일치하지 않습니다"
)
}
)
Expand All @@ -87,24 +88,25 @@ public ResponseEntity<BaseResponse> placeSaveOrUpdate(@RequestBody @Valid PlaceS
AccessToken 필요.""",
parameters = {
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER)
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER),
@Parameter(name = "RoomType", description = "roomType 필요. [TOGETHER, SELF] 중 하나", in = ParameterIn.HEADER)
},
responses = {
@ApiResponse(
responseCode = "200",
description = "성공"
),
@ApiResponse(
responseCode = "400",
description = "방 타입이 일치하지 않습니다."
),
@ApiResponse(
responseCode = "401",
description = "인증에 실패하였습니다."
),
@ApiResponse(
responseCode = "422",
description = "방의 타입이 일치하지 않습니다"
)
}
)
public ResponseEntity<BaseResponse> placesSaveOrUpdateBySelf(@RequestBody PlacesSaveOrUpdateBySelfRequest request) {
public ResponseEntity<BaseResponse> placesSaveOrUpdateBySelf(@RequestBody @Valid PlacesSaveOrUpdateBySelfRequest request) {

Room room = memberLoader.getRoom();

Expand All @@ -123,7 +125,8 @@ public ResponseEntity<BaseResponse> placesSaveOrUpdateBySelf(@RequestBody Places
AccessToken 필요.""",
parameters = {
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER)
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER),
@Parameter(name = "RoomType", description = "roomType 필요. [TOGETHER, SELF] 중 하나", in = ParameterIn.HEADER)
},
responses = {
@ApiResponse(
Expand All @@ -137,6 +140,10 @@ public ResponseEntity<BaseResponse> placesSaveOrUpdateBySelf(@RequestBody Places
@ApiResponse(
responseCode = "401",
description = "인증에 실패하였습니다."
),
@ApiResponse(
responseCode = "422",
description = "방의 타입이 일치하지 않습니다"
)
}
)
Expand All @@ -157,7 +164,8 @@ public ResponseEntity<DataResponse<PlaceFindResponse>> placeFind() {
AccessToken 필요.""",
parameters = {
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER)
@Parameter(name = "RoomId", description = "roomId 필요", in = ParameterIn.HEADER),
@Parameter(name = "RoomType", description = "roomType 필요. [TOGETHER, SELF] 중 하나", in = ParameterIn.HEADER)
},
responses = {
@ApiResponse(
Expand All @@ -171,6 +179,10 @@ public ResponseEntity<DataResponse<PlaceFindResponse>> placeFind() {
@ApiResponse(
responseCode = "401",
description = "인증에 실패하였습니다."
),
@ApiResponse(
responseCode = "422",
description = "방의 타입이 일치하지 않습니다"
)
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
import middle_point_search.backend.domains.place.dto.PlaceDTO.PlacesSaveOrUpdateBySelfRequest;
import middle_point_search.backend.domains.place.repository.PlaceRepository;
import middle_point_search.backend.domains.room.domain.Room;
import middle_point_search.backend.domains.room.domain.RoomType;
import middle_point_search.backend.domains.room.service.RoomService;

@Slf4j
@Service
Expand All @@ -33,14 +31,12 @@
public class PlaceService {

private final PlaceRepository placeRepository;
private final RoomService roomService;
private final MemberService memberService;

//장소 저장 및 업데이트 하고, Member 및 Room 역할 변경
@Transactional(rollbackFor = {CustomException.class})
public void saveOrUpdatePlaceAndRoleUpdate(Room room, Member member, PlaceSaveOrUpdateRequest request) {

roomService.updateRoomType(room, RoomType.TOGETHER);
saveOrUpdatePlace(room, member, request);
memberService.updateMemberRole(member, Role.USER);
}
Expand Down Expand Up @@ -69,7 +65,6 @@ private void saveOrUpdatePlace(Room room, Member member, PlaceSaveOrUpdateReques
public void saveOrUpdatePlacesBySelfAndRoleUpdate(Room room, PlacesSaveOrUpdateBySelfRequest request) {

String roomId = room.getIdentityNumber();
roomService.updateRoomType(room, RoomType.SELF);
saveOrUpdatePlacesBySelf(room, request);
memberService.updateRomeMembersRole(roomId, Role.USER);
}
Expand Down Expand Up @@ -100,7 +95,7 @@ public PlaceFindResponse findPlace(String roomId, String memberName) {

//내 장소 조회
PlaceVO myPlace = placeRepository.findByRoom_IdentityNumberAndMember_Name(roomId, memberName)
.map(Place:: toVO)
.map(Place::toVO)
.orElse(null);

//내 장소 존재 유무
Expand Down
Loading

0 comments on commit 4204c1a

Please sign in to comment.