diff --git a/src/main/java/org/example/siljeun/domain/auth/controller/AuthController.java b/src/main/java/org/example/siljeun/domain/auth/controller/AuthController.java index 0ee8150..24d458e 100644 --- a/src/main/java/org/example/siljeun/domain/auth/controller/AuthController.java +++ b/src/main/java/org/example/siljeun/domain/auth/controller/AuthController.java @@ -1,6 +1,7 @@ package org.example.siljeun.domain.auth.controller; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.example.siljeun.domain.auth.dto.request.LoginRequest; import org.example.siljeun.domain.auth.dto.request.SignUpRequest; import org.example.siljeun.domain.auth.dto.response.LoginResponse; @@ -17,6 +18,7 @@ @RestController @RequestMapping("/auth") @RequiredArgsConstructor +@Slf4j public class AuthController { private final AuthService authService; @@ -33,6 +35,7 @@ public ResponseEntity signUp(@RequestBody SignUpRequest request) @PostMapping("/login") public ResponseDto login(@RequestBody LoginRequest request) { try { + log.debug("----- 로그인 메서드 실행 -----"); LoginResponse response = authService.login(request.username(), request.password()); return ResponseDto.success("로그인 성공", response); } catch (Exception e) { diff --git a/src/main/java/org/example/siljeun/domain/auth/service/AuthService.java b/src/main/java/org/example/siljeun/domain/auth/service/AuthService.java index 98cbc21..e17f34b 100644 --- a/src/main/java/org/example/siljeun/domain/auth/service/AuthService.java +++ b/src/main/java/org/example/siljeun/domain/auth/service/AuthService.java @@ -24,8 +24,8 @@ public SignUpResponse signUp(SignUpRequest request) { String password = passwordEncoder.encode(request.password()); // 회원 생성 및 저장 - User user = new User(request.email(), request.username(), password, request.nickname(), - request.role(), request.provider()); + User user = new User(request.email(), request.username(), password, request.name(), + request.nickname(), request.role(), request.provider()); User savedUser = userRepository.save(user); return new SignUpResponse(savedUser.getId(), savedUser.getEmail(), savedUser.getUsername()); diff --git a/src/main/java/org/example/siljeun/domain/oauth/client/KakaoApiClient.java b/src/main/java/org/example/siljeun/domain/oauth/client/KakaoOAuthClient.java similarity index 50% rename from src/main/java/org/example/siljeun/domain/oauth/client/KakaoApiClient.java rename to src/main/java/org/example/siljeun/domain/oauth/client/KakaoOAuthClient.java index 3d1f01a..f76628c 100644 --- a/src/main/java/org/example/siljeun/domain/oauth/client/KakaoApiClient.java +++ b/src/main/java/org/example/siljeun/domain/oauth/client/KakaoOAuthClient.java @@ -1,16 +1,13 @@ package org.example.siljeun.domain.oauth.client; -import java.util.Map; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.example.siljeun.domain.oauth.dto.KakaoAccessToken; import org.example.siljeun.domain.oauth.dto.KakaoUserInfo; -import org.example.siljeun.global.config.KakaoOAuthProperties; -import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -18,56 +15,57 @@ @Component @RequiredArgsConstructor -public class KakaoApiClient { +@Slf4j +public class KakaoOAuthClient { private final RestTemplate restTemplate; - private final KakaoOAuthProperties properties; + // 현재 카카오 API 서버에서 인가 코드를 제공한 상태이다 + // 서비스 서버가 인가 코드를 이용해 카카오 API 서버로 액세스 토큰을 요청한다 public String getAccessToken(String code) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap params = new LinkedMultiValueMap<>(); + // 아래 4가지 값은 필수 params.add("grant_type", "authorization_code"); - params.add("client_id", "eaee0e144aeb9afef54d5c449448baea"); - params.add("redirect_uri", "http://localhost:8080/oauth/kakao/callback"); - params.add("code", code); + params.add("client_id", "eaee0e144aeb9afef54d5c449448baea"); // 카카오 REST API 키 + params.add("redirect_uri", "http://localhost:8080/oauth/kakao/callback"); // 여기서 문제 발생? + params.add("code", code); // 인가 코드 HttpEntity> request = new HttpEntity<>(params, headers); - ResponseEntity> response = restTemplate.exchange( + // 명시한 URL로 (인가 코드를 담은) POST 요청을 보내면 카카오 API 서버에서 액세스 토큰을 응답한다 + KakaoAccessToken response = restTemplate.postForEntity( "https://kauth.kakao.com/oauth/token", - HttpMethod.POST, request, - new ParameterizedTypeReference<>() { - } - ); + KakaoAccessToken.class + ).getBody(); - if (response.getStatusCode() != HttpStatus.OK || response.getBody() == null) { - throw new RuntimeException("카카오 Access Token 요청 실패"); - } + log.debug("----- 액세스 토큰: {} -----", response.accessToken()); - return response.getBody().get("access_token").toString(); + return response.accessToken(); } + // 서비스 서버가 카카오 인증 서버에 저장된 회원 정보를 요청한다 public KakaoUserInfo getUserInfo(String accessToken) { - HttpHeaders headers = new HttpHeaders(); + // HTTP 헤더 설정 + final HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(accessToken); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - HttpEntity request = new HttpEntity<>(headers); + // 설정한 HTTP 헤더를 이용해 요청 생성 + final HttpEntity request = new HttpEntity<>(headers); - ResponseEntity response = restTemplate.exchange( + // GET 메서드로 회원 정보를 요청한 후 KakaoUserInfo 객체에 담음 + final KakaoUserInfo response = restTemplate.exchange( "https://kapi.kakao.com/v2/user/me", HttpMethod.GET, request, KakaoUserInfo.class - ); - - if (response.getStatusCode() != HttpStatus.OK || response.getBody() == null) { - throw new RuntimeException("카카오 사용자 정보 요청 실패"); - } + ).getBody(); - return response.getBody(); + return response; } -} +} \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/domain/oauth/client/NaverApiClient.java b/src/main/java/org/example/siljeun/domain/oauth/client/NaverApiClient.java deleted file mode 100644 index 88c1713..0000000 --- a/src/main/java/org/example/siljeun/domain/oauth/client/NaverApiClient.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.example.siljeun.domain.oauth.client; - -public class NaverApiClient { - -} diff --git a/src/main/java/org/example/siljeun/domain/oauth/controller/OAuthController.java b/src/main/java/org/example/siljeun/domain/oauth/controller/OAuthController.java index ffc0e55..4c11678 100644 --- a/src/main/java/org/example/siljeun/domain/oauth/controller/OAuthController.java +++ b/src/main/java/org/example/siljeun/domain/oauth/controller/OAuthController.java @@ -1,8 +1,9 @@ package org.example.siljeun.domain.oauth.controller; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.example.siljeun.domain.auth.dto.response.LoginResponse; import org.example.siljeun.domain.oauth.service.KakaoOAuthService; -import org.example.siljeun.global.dto.ResponseDto; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @@ -12,14 +13,21 @@ @RestController @RequiredArgsConstructor @RequestMapping("/oauth") +@Slf4j public class OAuthController { private final KakaoOAuthService kakaoOAuthService; + /* + 1. 클라이언트가 카카오 로그인을 요청한다 + 2. /oauth/kakao/callback?code={code}로 리다이렉트된다 + 3. 이때 카카오에서 쿼리 스트링으로 인가 코드를 넘겨준다 + 4. 넘어온 인가 코드를 이용해서 카카오 로그인 API를 호출한다 + */ @GetMapping("/kakao/callback") - public ResponseEntity kakaoCallback(@RequestParam String code) { - String jwt = kakaoOAuthService.kakaoLogin(code); - return ResponseEntity.ok(jwt); + public ResponseEntity kakaoCallback(@RequestParam String code) { + log.debug("---------- METHOD: kakaoCallback ----------"); + return ResponseEntity.ok(kakaoOAuthService.kakaoLogin(code)); } } \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoAccessToken.java b/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoAccessToken.java new file mode 100644 index 0000000..ad8ad55 --- /dev/null +++ b/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoAccessToken.java @@ -0,0 +1,13 @@ +package org.example.siljeun.domain.oauth.dto; + +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; + +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) +public record KakaoAccessToken(String tokenType, + String accessToken, + Integer expiresIn, + String refreshToken, + Integer refreshTokenExpiresIn) { + +} diff --git a/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoAccount.java b/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoAccount.java new file mode 100644 index 0000000..0f271d1 --- /dev/null +++ b/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoAccount.java @@ -0,0 +1,12 @@ +package org.example.siljeun.domain.oauth.dto; + +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; + +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) +public record KakaoAccount( + KakaoProfile profile, // 프로필 정보(닉네임, 프로필 사진) + String email +) { + +} \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoProfile.java b/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoProfile.java new file mode 100644 index 0000000..c85a06c --- /dev/null +++ b/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoProfile.java @@ -0,0 +1,12 @@ +package org.example.siljeun.domain.oauth.dto; + +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; + +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) +public record KakaoProfile( + String nickname, + String profileImageUrl +) { + +} \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoUserInfo.java b/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoUserInfo.java index f5c855f..f6660c1 100644 --- a/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoUserInfo.java +++ b/src/main/java/org/example/siljeun/domain/oauth/dto/KakaoUserInfo.java @@ -1,41 +1,12 @@ package org.example.siljeun.domain.oauth.dto; -import java.util.Map; -import lombok.AllArgsConstructor; -import lombok.Getter; - -@Getter -@AllArgsConstructor -public class KakaoUserInfo implements OAuth2UserInfo { - - private Map attributes; - private Map attributesAccount; - private Map attributesProfile; - - public KakaoUserInfo(Map attributes) { - this.attributes = attributes; - this.attributesAccount = (Map) attributes.get("kakao_account"); - this.attributesProfile = (Map) attributesAccount.get("profile"); - } - - @Override - public String getProvider() { - return "Kakao"; - } - - @Override - public String getProviderId() { - return attributes.get("id").toString(); - } - - @Override - public String getEmail() { - return attributesAccount.get("email").toString(); - } - - @Override - public String getNickname() { - return attributesProfile.get("nickname").toString(); - } +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; + +@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class) +public record KakaoUserInfo( + Long id, // 회원 번호 + KakaoAccount kakaoAccount // 카카오 계정 정보 +) { } \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/domain/oauth/dto/NaverUserInfo.java b/src/main/java/org/example/siljeun/domain/oauth/dto/NaverUserInfo.java deleted file mode 100644 index 3aff8c2..0000000 --- a/src/main/java/org/example/siljeun/domain/oauth/dto/NaverUserInfo.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.example.siljeun.domain.oauth.dto; - -public class NaverUserInfo { - -} diff --git a/src/main/java/org/example/siljeun/domain/oauth/dto/OAuth2UserInfo.java b/src/main/java/org/example/siljeun/domain/oauth/dto/OAuth2UserInfo.java deleted file mode 100644 index e47bd09..0000000 --- a/src/main/java/org/example/siljeun/domain/oauth/dto/OAuth2UserInfo.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.example.siljeun.domain.oauth.dto; - -import java.util.Map; - -public interface OAuth2UserInfo { - - public Map getAttributes(); - - String getProvider(); - - String getProviderId(); - - String getEmail(); - - String getNickname(); - -} \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/domain/oauth/service/KakaoOAuthService.java b/src/main/java/org/example/siljeun/domain/oauth/service/KakaoOAuthService.java index 8776f1c..cbd4cb0 100644 --- a/src/main/java/org/example/siljeun/domain/oauth/service/KakaoOAuthService.java +++ b/src/main/java/org/example/siljeun/domain/oauth/service/KakaoOAuthService.java @@ -1,40 +1,73 @@ package org.example.siljeun.domain.oauth.service; import lombok.RequiredArgsConstructor; -import org.example.siljeun.domain.oauth.client.KakaoApiClient; +import lombok.extern.slf4j.Slf4j; +import org.example.siljeun.domain.auth.dto.response.LoginResponse; +import org.example.siljeun.domain.oauth.client.KakaoOAuthClient; import org.example.siljeun.domain.oauth.dto.KakaoUserInfo; import org.example.siljeun.domain.user.entity.User; import org.example.siljeun.domain.user.enums.Provider; +import org.example.siljeun.domain.user.enums.Role; import org.example.siljeun.domain.user.repository.UserRepository; import org.example.siljeun.global.security.JwtUtil; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor +@Slf4j public class KakaoOAuthService { - private final KakaoApiClient kakaoApiClient; + private final KakaoOAuthClient kakaoOAuthClient; private final UserRepository userRepository; private final JwtUtil jwtUtil; + private final PasswordEncoder passwordEncoder; - public String kakaoLogin(String code) { - // 1. 액세스 토큰 요청 - String accessToken = kakaoApiClient.getAccessToken(code); + // 인가 코드를 이용해 카카오 로그인 API를 호출한다 + public LoginResponse kakaoLogin(String code) { + // 1. 카카오에 인가 코드를 넘겨서 액세스 토큰을 획득한다 + log.debug("----- 액세스 토큰 발급 -----"); + final String accessToken = kakaoOAuthClient.getAccessToken(code); - // 2. 사용자 정보 요청 - KakaoUserInfo userInfo = kakaoApiClient.getUserInfo(accessToken); + // 2. 카카오에 액세스 토큰을 넘겨서 카카오에 저장된 사용자 정보를 획득한다 + log.debug("----- 사용자 정보 획득 -----"); + final KakaoUserInfo userInfo = kakaoOAuthClient.getUserInfo(accessToken); - // 3. 회원 가입 또는 로그인 처리 - User user = userRepository.findByEmail(userInfo.getEmail()) + // 3. 해당 정보를 이용해 회원 가입 또는 로그인을 처리한다 + log.debug("----- 회원 가입 또는 로그인 -----"); + User user = userRepository.findByEmail(userInfo.kakaoAccount().email()) .orElseGet(() -> registerUser(userInfo)); - // 4. JWT 토큰 발급 - return jwtUtil.createToken(user.getUsername()); + // 4. 서비스 서버에 저장된 회원 정보를 이용해 JWT 토큰을 발급받는다 + log.debug("----- JWT 토큰 발급 -----"); + String token = jwtUtil.createToken(user.getUsername()); + + return new LoginResponse(token); } private User registerUser(KakaoUserInfo userInfo) { - User user = new User(userInfo.getEmail(), userInfo.getNickname(), Provider.KAKAO, - userInfo.getProviderId()); + String username = "kakao" + userInfo.id(); + String password = passwordEncoder.encode(username); + User user = new User( + userInfo.kakaoAccount().email(), + username, + password, + userInfo.kakaoAccount().profile().nickname(), + userInfo.kakaoAccount().profile().nickname(), + Role.USER, + Provider.KAKAO, + userInfo.id() + ); + log.debug("--------------------회원 가입 메서드 실행--------------------"); + log.debug("email: {}, username: {}, password: {}, name: {}, nickname: {}, id: {}", + userInfo.kakaoAccount().email(), + username, + password, + userInfo.kakaoAccount().profile().nickname(), + userInfo.kakaoAccount().profile().nickname(), + userInfo.id() + ); + return userRepository.save(user); } diff --git a/src/main/java/org/example/siljeun/domain/oauth/service/NaverOAuthService.java b/src/main/java/org/example/siljeun/domain/oauth/service/NaverOAuthService.java deleted file mode 100644 index 0fec45e..0000000 --- a/src/main/java/org/example/siljeun/domain/oauth/service/NaverOAuthService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.example.siljeun.domain.oauth.service; - -import org.springframework.stereotype.Service; - -@Service -public class NaverOAuthService { - -} \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/domain/payment/service/PaymentService.java b/src/main/java/org/example/siljeun/domain/payment/service/PaymentService.java index 3f778fd..dfb99e6 100644 --- a/src/main/java/org/example/siljeun/domain/payment/service/PaymentService.java +++ b/src/main/java/org/example/siljeun/domain/payment/service/PaymentService.java @@ -5,6 +5,8 @@ import org.example.siljeun.domain.payment.entity.Payment; import org.example.siljeun.domain.payment.repository.PaymentRepository; import org.example.siljeun.domain.reservation.service.ReservationService; +import org.example.siljeun.domain.seat.enums.SeatStatus; +import org.example.siljeun.domain.seatscheduleinfo.service.SeatScheduleInfoService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -14,6 +16,7 @@ public class PaymentService { private final PaymentRepository paymentRepository; private final ReservationService reservationService; + private final SeatScheduleInfoService seatScheduleInfoService; @Transactional public void savePayment(PaymentConfirmRequestDto dto) { @@ -24,6 +27,10 @@ public void savePayment(PaymentConfirmRequestDto dto) { .build(); paymentRepository.save(payment); + + seatScheduleInfoService.updateSeatScheduleInfoStatus(dto.getSeatScheduleInfoId(), SeatStatus.RESERVED); + seatScheduleInfoService.applySeatLockTTL(dto.getSeatScheduleInfoId(), SeatStatus.RESERVED); + reservationService.save(dto.getUserId(), dto.getSeatScheduleInfoId()); } } diff --git a/src/main/java/org/example/siljeun/domain/reservation/controller/ReservationController.java b/src/main/java/org/example/siljeun/domain/reservation/controller/ReservationController.java index 02e9343..34b1f58 100644 --- a/src/main/java/org/example/siljeun/domain/reservation/controller/ReservationController.java +++ b/src/main/java/org/example/siljeun/domain/reservation/controller/ReservationController.java @@ -44,13 +44,4 @@ public ResponseEntity> findById( ReservationInfoResponse dto = reservationService.findById(username, reservationId); return ResponseEntity.ok(ResponseDto.success("예매 조회 성공", dto)); } - - @PostMapping() - public ResponseEntity> createReservation( - @RequestBody @Valid ReservationCreateRequest reservationCreateRequest, - @AuthenticationPrincipal PrincipalDetails userDetails - ){ - reservationService.createReservation(reservationCreateRequest, userDetails.getUserId()); - return ResponseEntity.ok(ResponseDto.success("결제 진행하기", null)); - } } diff --git a/src/main/java/org/example/siljeun/domain/reservation/exception/ErrorCode.java b/src/main/java/org/example/siljeun/domain/reservation/exception/ErrorCode.java index 6c0b852..90cf25a 100644 --- a/src/main/java/org/example/siljeun/domain/reservation/exception/ErrorCode.java +++ b/src/main/java/org/example/siljeun/domain/reservation/exception/ErrorCode.java @@ -18,6 +18,14 @@ public enum ErrorCode { // seatScheduleInfo NOT_FOUNT_SEAT_SCHEDULE_INFO(404, "해당 공연에 대한 좌석 정보가 존재하지 않습니다."), + ALREADY_SELECTED_SEAT(409, "이미 선점된 좌석입니다."), + SEAT_LIMIT_ONE_PER_USER(409, "1인당 1개의 좌석만 예약 가능합니다."), + + // venue + NOT_FOUND_VENUE(404, "해당 공연장을 찾을 수 없습니다."), + + // seat + SEAT_CAPACITY_EXCEEDED(400, "좌석 수가 공연장 수용 인원(capacity)을 초과했습니다."), // jwt UNAUTHORIZED(401, "토큰이 유효하지 않습니다."), diff --git a/src/main/java/org/example/siljeun/domain/reservation/service/ReservationService.java b/src/main/java/org/example/siljeun/domain/reservation/service/ReservationService.java index 23c38b2..442f7aa 100644 --- a/src/main/java/org/example/siljeun/domain/reservation/service/ReservationService.java +++ b/src/main/java/org/example/siljeun/domain/reservation/service/ReservationService.java @@ -13,9 +13,9 @@ import org.example.siljeun.domain.seatscheduleinfo.repository.SeatScheduleInfoRepository; import org.example.siljeun.domain.seatscheduleinfo.entity.SeatScheduleInfo; import org.example.siljeun.domain.seat.enums.SeatStatus; +import org.example.siljeun.domain.seatscheduleinfo.service.SeatScheduleInfoService; import org.example.siljeun.domain.user.entity.User; import org.example.siljeun.domain.user.repository.UserRepository; -import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -29,16 +29,13 @@ public class ReservationService { private final ReservationRepository reservationRepository; private final UserRepository userRepository; private final WaitingQueueService waitingQueueService; - private final SeatScheduleInfoRepository seatScheduleInfoRepository; - private final RedisTemplate redisTemplate; - + private final SeatScheduleInfoService seatScheduleInfoService; @Transactional public void save(Long userId, Long seatScheduleInfoId) { User user = userRepository.findById(userId) .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER)); - SeatScheduleInfo seatScheduleInfo = seatScheduleInfoRepository.findById(seatScheduleInfoId) - .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUNT_SEAT_SCHEDULE_INFO)); + SeatScheduleInfo seatScheduleInfo = seatScheduleInfoService.findById(seatScheduleInfoId); Reservation reservation = new Reservation(user, seatScheduleInfo); reservationRepository.save(reservation); @@ -71,8 +68,11 @@ public void delete(String username, Long reservationId) { throw new CustomException(ErrorCode.INVALID_RESERVATION_USER); } + Long seatScheduleInfoId = reservation.getSeatScheduleInfo().getId(); reservationRepository.delete(reservation); - reservation.getSeatScheduleInfo().updateSeatScheduleInfoStatus(SeatStatus.AVAILABLE); + + seatScheduleInfoService.updateSeatScheduleInfoStatus(seatScheduleInfoId, SeatStatus.AVAILABLE); + seatScheduleInfoService.applySeatLockTTL(seatScheduleInfoId, SeatStatus.AVAILABLE); } public ReservationInfoResponse findById(String username, Long reservationId) { @@ -87,45 +87,4 @@ public ReservationInfoResponse findById(String username, Long reservationId) { return ReservationInfoResponse.from(reservation); } - - @Transactional - public void createReservation(ReservationCreateRequest reservationCreateRequest, Long userId){ - - //유저 확인 - User user = userRepository.findById(userId) - .orElseThrow(() -> new EntityNotFoundException("유저를 찾을 수 없습니다.")); - - Long scheduleId = reservationCreateRequest.scheduleId(); - //유저가 해당 회차에 선택한 좌석 검증 - String redisSelectedKey = "user:scheduleSelected" + userId + ":" + scheduleId; - log.info("예매 정보 생성 시도 user : " + userId + "scheduleId : " + scheduleId + " key) " + redisSelectedKey ); - String selectedId = redisTemplate.opsForValue().get(redisSelectedKey); - - if (selectedId == null) { - throw new IllegalStateException("선택한 좌석이 없습니다."); - } - - SeatScheduleInfo seatScheduleInfo = seatScheduleInfoRepository.findById(Long.valueOf(selectedId)) - .orElseThrow(() -> new EntityNotFoundException("좌석 정보를 찾을 수 없습니다.")); - - //해당 좌석의 상태 검증 - String redisStatusHashKey = "seatStatus:" + scheduleId; - Object redisStatusObj = redisTemplate.opsForHash().get(redisStatusHashKey, selectedId); - - if (redisStatusObj == null || !redisStatusObj.toString().equals(SeatStatus.SELECTED.name())) { - throw new IllegalStateException("좌석 상태가 유효하지 않습니다. 다시 선택해주세요."); - } - - //예매 정보 생성 - Reservation reservation = new Reservation(user, seatScheduleInfo); - reservationRepository.save(reservation); - - //좌석 상태 결제 진행 중으로 변경 - seatScheduleInfo.updateSeatScheduleInfoStatus(SeatStatus.HOLD); - seatScheduleInfoRepository.save(seatScheduleInfo); - redisTemplate.opsForHash().put(redisStatusHashKey, selectedId, SeatStatus.HOLD.name()); - - //유저가 선점한 좌석 정보 - 결제 진행 상태일 때의 만료 시간 1시간 - redisTemplate.expire(redisSelectedKey, Duration.ofMinutes(60)); - } } diff --git a/src/main/java/org/example/siljeun/domain/seat/enums/SeatStatus.java b/src/main/java/org/example/siljeun/domain/seat/enums/SeatStatus.java index 9941c06..9bd5302 100644 --- a/src/main/java/org/example/siljeun/domain/seat/enums/SeatStatus.java +++ b/src/main/java/org/example/siljeun/domain/seat/enums/SeatStatus.java @@ -2,7 +2,7 @@ public enum SeatStatus { BLOCKED, //미판매 - CANCELLED, //취소 + CANCELLED, //취소 - 취소표는 특정 시간대에 한 번에 풀어놓는 상태를 고려하여 넣어놓았으나 현재 구현 상태에서는 사용하지 않음 RESERVED, //예매됨 HOLD, //결제 진행 중 SELECTED, //선택됨 diff --git a/src/main/java/org/example/siljeun/domain/seat/service/SeatService.java b/src/main/java/org/example/siljeun/domain/seat/service/SeatService.java index 13e60b3..75a8ff0 100644 --- a/src/main/java/org/example/siljeun/domain/seat/service/SeatService.java +++ b/src/main/java/org/example/siljeun/domain/seat/service/SeatService.java @@ -1,6 +1,8 @@ package org.example.siljeun.domain.seat.service; import lombok.RequiredArgsConstructor; +import org.example.siljeun.domain.reservation.exception.CustomException; +import org.example.siljeun.domain.reservation.exception.ErrorCode; import org.example.siljeun.domain.seat.dto.request.SeatCreateRequest; import org.example.siljeun.domain.seat.entity.Seat; import org.example.siljeun.domain.venue.entity.Venue; @@ -15,18 +17,18 @@ @Service @RequiredArgsConstructor +@Transactional public class SeatService { private final VenueRepository venueRepository; private final SeatRepository seatRepository; - @Transactional public void createSeats(Long venueId, List seatCreateRequests){ Venue venue = venueRepository.findById(venueId) - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "해당 공연장을 찾을 수 없습니다.")); //Throw 예외 설정 필요 + .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_VENUE)); if (seatCreateRequests.size() > venue.getSeatCapacity()) { - throw new IllegalArgumentException("좌석 수가 공연장 수용 인원(capacity)을 초과했습니다."); + throw new CustomException(ErrorCode.SEAT_CAPACITY_EXCEEDED); } //공연장 ID, 구역, 열, 번호를 바탕으로 고유하도록 설정하였으나 //좌석 정보가 중복되는 경우를 다루지 않아 추후 리팩토링이 필요함 diff --git a/src/main/java/org/example/siljeun/domain/seatscheduleinfo/controller/SeatScheduleInfoController.java b/src/main/java/org/example/siljeun/domain/seatscheduleinfo/controller/SeatScheduleInfoController.java index e19e85f..f7e8a2d 100644 --- a/src/main/java/org/example/siljeun/domain/seatscheduleinfo/controller/SeatScheduleInfoController.java +++ b/src/main/java/org/example/siljeun/domain/seatscheduleinfo/controller/SeatScheduleInfoController.java @@ -1,27 +1,25 @@ package org.example.siljeun.domain.seatscheduleinfo.controller; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; +import org.example.siljeun.domain.seatscheduleinfo.dto.request.SeatScheduleUpdateStatusRequest; import org.example.siljeun.domain.seatscheduleinfo.service.SeatScheduleInfoService; import org.example.siljeun.global.dto.ResponseDto; import org.example.siljeun.global.security.PrincipalDetails; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.*; import java.util.Map; @Controller @RequiredArgsConstructor -@RequestMapping("/schedules/{scheduleId}") public class SeatScheduleInfoController { private final SeatScheduleInfoService seatScheduleInfoService; - @PostMapping("/seat-schedule-infos") + @PostMapping("/schedules/{scheduleId}/seat-schedule-infos") public ResponseEntity> forceSeatScheduleInfoInRedis( @PathVariable Long scheduleId ) @@ -30,7 +28,7 @@ public ResponseEntity> forceSeatScheduleInfoInRedis( return ResponseEntity.ok(ResponseDto.success("Redis 적재 완료 scheduleId : " + scheduleId, null)); } - @PostMapping("/seat-schedule-infos/{seatScheduleInfoId}") + @PostMapping("/schedules/{scheduleId}/seat-schedule-infos/{seatScheduleInfoId}") public ResponseEntity> selectSeat( @PathVariable Long scheduleId, @PathVariable Long seatScheduleInfoId, @@ -40,10 +38,18 @@ public ResponseEntity> selectSeat( return ResponseEntity.ok(ResponseDto.success( "좌석이 선택되었습니다. seatScheduleInfoId : " + seatScheduleInfoId.toString(), null)); } - @GetMapping("/seat-schedule-infos") + @GetMapping("/schedules/{scheduleId}/seat-schedule-infos") public ResponseEntity> getSeatScheduleInfos( @PathVariable Long scheduleId ) { return ResponseEntity.ok(seatScheduleInfoService.getSeatStatusMap(scheduleId)); } + +// @PatchMapping("/seat-schedule-infos") +// public ResponseEntity> updateSeatScheduleInfoStatus( +// @RequestBody @Valid SeatScheduleUpdateStatusRequest seatScheduleRequest +// ){ +// seatScheduleInfoService.updateSeatSchedulerInfoStatus(seatScheduleRequest.seatScheduleInfoId(), seatScheduleRequest.status()); +// return ResponseEntity.ok(ResponseDto.success("좌석의 상태가 변경되었습니다.", null)); +// } } diff --git a/src/main/java/org/example/siljeun/domain/seatscheduleinfo/scheduler/SeatExpirationScheduler.java b/src/main/java/org/example/siljeun/domain/seatscheduleinfo/scheduler/SeatExpirationScheduler.java new file mode 100644 index 0000000..4f27231 --- /dev/null +++ b/src/main/java/org/example/siljeun/domain/seatscheduleinfo/scheduler/SeatExpirationScheduler.java @@ -0,0 +1,87 @@ +package org.example.siljeun.domain.seatscheduleinfo.scheduler; + +import lombok.RequiredArgsConstructor; +import org.example.siljeun.domain.seat.enums.SeatStatus; +import org.example.siljeun.domain.seatscheduleinfo.entity.SeatScheduleInfo; +import org.example.siljeun.domain.seatscheduleinfo.repository.SeatScheduleInfoRepository; +import org.example.siljeun.global.util.RedisKeyProvider; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Component +@RequiredArgsConstructor +public class SeatExpirationScheduler { + + private final RedisTemplate redisTemplate; + private final SeatScheduleInfoRepository seatScheduleInfoRepository; + + @Scheduled(fixedDelay = 60_000) + public void expireSeatsToAvailable() { + long now = System.currentTimeMillis(); + expireByStatus(SeatStatus.SELECTED, now); + expireByStatus(SeatStatus.HOLD, now); + } + + private void expireByStatus(SeatStatus status, long nowMillis) { + String zsetKey = RedisKeyProvider.trackExpiresKey(status.name()); + //상태-> 좌석Id들 1, 2, 3, 4,..... + 만료 시간 + //중에서 만료 시간이 지금 이전인 것들 조회 + Set expiredIds = redisTemplate + .opsForZSet() + .rangeByScore(zsetKey, 0, nowMillis); + if (expiredIds == null || expiredIds.isEmpty()) { + + return; + } + + //만료 시간이 지난 Id들을 Long 타입으로 변경하고 실제 객체를 가져와서 상태를 변경 후 저장 + List ids = expiredIds.stream() + .map(Long::valueOf) + .toList(); + List infos = seatScheduleInfoRepository.findAllById(ids); + infos.forEach(info -> info.updateSeatScheduleInfoStatus(SeatStatus.AVAILABLE)); + seatScheduleInfoRepository.saveAll(infos); + + final Map> hashBatch = new HashMap<>(); + for (SeatScheduleInfo info : infos) { + String hashKey = RedisKeyProvider.seatStatusKey(info.getSchedule().getId()); + hashBatch + .computeIfAbsent(hashKey, k -> new HashMap<>()) + .put(info.getId().toString(), SeatStatus.AVAILABLE.name()); + } + + RedisCallback pipelineWork = connection -> { + // ZSET 제거 + connection.zRem( + zsetKey.getBytes(), + expiredIds.stream() + .map(String::getBytes) + .toArray(byte[][]::new) + ); + + // 해시 업데이트 + for (Map.Entry> e : hashBatch.entrySet()) { + byte[] hashKey = redisTemplate.getStringSerializer().serialize(e.getKey()); + Map serialized = new HashMap<>(); + e.getValue().forEach((field, value) -> + serialized.put( + redisTemplate.getStringSerializer().serialize(field.toString()), + redisTemplate.getStringSerializer().serialize(value.toString()) + ) + ); + connection.hMSet(hashKey, serialized); + } + + return null; + }; + + redisTemplate.executePipelined(pipelineWork); + } +} \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/domain/seatscheduleinfo/service/SeatScheduleInfoService.java b/src/main/java/org/example/siljeun/domain/seatscheduleinfo/service/SeatScheduleInfoService.java index 56cc1d9..85baad7 100644 --- a/src/main/java/org/example/siljeun/domain/seatscheduleinfo/service/SeatScheduleInfoService.java +++ b/src/main/java/org/example/siljeun/domain/seatscheduleinfo/service/SeatScheduleInfoService.java @@ -3,6 +3,8 @@ import jakarta.persistence.EntityNotFoundException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.example.siljeun.domain.reservation.exception.CustomException; +import org.example.siljeun.domain.reservation.exception.ErrorCode; import org.example.siljeun.domain.schedule.entity.Schedule; import org.example.siljeun.domain.schedule.repository.ScheduleRepository; import org.example.siljeun.domain.seat.entity.Seat; @@ -11,9 +13,11 @@ import org.example.siljeun.domain.seatscheduleinfo.entity.SeatScheduleInfo; import org.example.siljeun.domain.seat.enums.SeatStatus; import org.example.siljeun.global.lock.DistributedLock; +import org.example.siljeun.global.util.RedisKeyProvider; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.server.ResponseStatusException; import java.time.Duration; @@ -31,57 +35,62 @@ public class SeatScheduleInfoService { @DistributedLock(key = "'seat:' + #seatScheduleInfoId") public void selectSeat(Long userId, Long scheduleId, Long seatScheduleInfoId) { + //예외 상황 처리 SeatScheduleInfo seatScheduleInfo = seatScheduleInfoRepository.findById(seatScheduleInfoId). - orElseThrow(() -> new EntityNotFoundException("해당 회차별 좌석 정보가 존재하지 않습니다.")); + orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUNT_SEAT_SCHEDULE_INFO)); Schedule schedule = seatScheduleInfo.getSchedule(); - if(schedule.getTicketingStartTime().isAfter(LocalDateTime.now())){ - log.info("예매 미오픈."); - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "예매 불가능한 시간입니다. 예매 오픈 시간 : " + schedule.getTicketingStartTime()); + throw new CustomException(ErrorCode.NOT_TICKETING_TIME); } if (!seatScheduleInfo.isAvailable()) { - log.info("이미 선점된 좌석입니다."); - throw new ResponseStatusException(HttpStatus.CONFLICT, "이미 선점된 좌석입니다."); + throw new CustomException(ErrorCode.ALREADY_SELECTED_SEAT); } + String redisSelectedKey = RedisKeyProvider.userSelectedSeatKey(userId, scheduleId); + if (Boolean.TRUE.equals(redisTemplate.hasKey(redisSelectedKey))) { + throw new CustomException(ErrorCode.SEAT_LIMIT_ONE_PER_USER); + } + + //DB 상태 변경 seatScheduleInfo.updateSeatScheduleInfoStatus(SeatStatus.SELECTED); seatScheduleInfoRepository.save(seatScheduleInfo); - //userId와 schedule Id가 key이고 seatSchduleInfoId로 구성된 value인 형태로 저장 - String redisSelectedKey = "user:scheduleSelected" + userId + ":" + scheduleId; + //유저가 선점한 좌석을 Redis에 저장 (정보 조회용) + redisTemplate.opsForValue() + .set(redisSelectedKey, seatScheduleInfoId.toString()); + redisTemplate.expire(redisSelectedKey, Duration.ofMinutes(5)); - if (Boolean.TRUE.equals(redisTemplate.hasKey(redisSelectedKey))) { - throw new ResponseStatusException(HttpStatus.CONFLICT, "1인당 1개의 좌석만 예약 가능합니다."); - } + //TTL 관리를 위한 키 생성 + String redisLockKey = RedisKeyProvider.seatOccupyKey(seatScheduleInfoId); + redisTemplate.opsForValue().set(redisLockKey, userId.toString()); - redisTemplate.opsForValue().set(redisSelectedKey, seatScheduleInfoId.toString()); - redisTemplate.expire(redisSelectedKey, Duration.ofMinutes(5)); + //Redis 상태 변경 + updateSeatScheduleInfoStatusInRedis(scheduleId, seatScheduleInfoId, SeatStatus.SELECTED); - //seatScheduleInfoId의 seatStatus 상태 변경 - String redisHashKey = "seatStatus:" + scheduleId; - redisTemplate.opsForHash().put(redisHashKey, seatScheduleInfoId.toString(), SeatStatus.SELECTED.name()); - log.info("redisHashKey : " + redisHashKey + " = " + " redisSelectedKey : " + redisSelectedKey); + //TTL 적용 + applySeatLockTTL(seatScheduleInfoId, SeatStatus.SELECTED); } public Map getSeatStatusMap(Long scheduleId) { Schedule schedule = scheduleRepository.findById(scheduleId) - .orElseThrow(() -> new EntityNotFoundException("해당 회차가 존재하지 않습니다.")); + .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_SCHEDULE)); - List seatScheduleInfos = - seatScheduleInfoRepository.findAllBySchedule(schedule); + List seatScheduleInfos = seatScheduleInfoRepository.findAllBySchedule(schedule); + if(seatScheduleInfos.isEmpty()){ + throw new CustomException(ErrorCode.NOT_FOUNT_SEAT_SCHEDULE_INFO); + } List fieldKeys = seatScheduleInfos.stream() .map(info -> info.getId().toString()) .toList(); - String redisHashKey = "seatStatus:" + scheduleId; - List redisStatuses = redisTemplate.opsForHash().multiGet(redisHashKey, new ArrayList<>(fieldKeys)); + String redisKey = RedisKeyProvider.seatStatusKey(scheduleId); + List redisStatuses = redisTemplate.opsForHash().multiGet(redisKey, new ArrayList<>(fieldKeys)); Map seatStatusMap = new HashMap<>(); - for (int i = 0; i < seatScheduleInfos.size(); i++) { SeatScheduleInfo info = seatScheduleInfos.get(i); Object redisStatusObj = redisStatuses.get(i); @@ -90,7 +99,7 @@ public Map getSeatStatusMap(Long scheduleId) { ? redisStatusObj.toString() : seatScheduleInfos.get(i).getStatus().name(); - seatStatusMap.put("seatScheduleInfo-" + info.getId().toString(), status); + seatStatusMap.put(info.getId().toString(), status); } return seatStatusMap; @@ -98,11 +107,11 @@ public Map getSeatStatusMap(Long scheduleId) { public void forceSeatScheduleInfoInRedis(Long scheduleId){ Schedule schedule = scheduleRepository.findById(scheduleId) - .orElseThrow(() -> new EntityNotFoundException("해당 회차가 존재하지 않습니다.")); + .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_SCHEDULE)); List seatInfos = seatScheduleInfoRepository.findAllBySchedule(schedule); - String redisHashKey = "seatStatus:" + schedule.getId(); + String redisHashKey = RedisKeyProvider.seatStatusKey(scheduleId); Map seatStatusMap = new HashMap<>(); for (SeatScheduleInfo seat : seatInfos) { @@ -111,4 +120,54 @@ public void forceSeatScheduleInfoInRedis(Long scheduleId){ redisTemplate.opsForHash().putAll(redisHashKey, seatStatusMap); } + @Transactional + public void updateSeatScheduleInfoStatus(Long seatScheduleInfoId, SeatStatus seatStatus){ + SeatScheduleInfo seatScheduleInfo = seatScheduleInfoRepository.findById(seatScheduleInfoId) + .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUNT_SEAT_SCHEDULE_INFO)); + seatScheduleInfo.updateSeatScheduleInfoStatus(seatStatus); + + Long scheduleId = seatScheduleInfo.getSchedule().getId(); + updateSeatScheduleInfoStatusInRedis(scheduleId, seatScheduleInfoId, seatStatus); + } + + public void updateSeatScheduleInfoStatusInRedis(Long scheduleId, Long seatScheduleInfoId, SeatStatus seatStatus){ + String redisKey = RedisKeyProvider.seatStatusKey(scheduleId); + String fieldKey = seatScheduleInfoId.toString(); + redisTemplate.opsForHash().put(redisKey, fieldKey, seatStatus.name()); + } + + public void applySeatLockTTL(Long seatScheduleInfoId, SeatStatus seatStatus){ + String member = seatScheduleInfoId.toString(); + + String seatLockkey = RedisKeyProvider.seatOccupyKey(seatScheduleInfoId); + String zsetSelectedKey = RedisKeyProvider.trackExpiresKey(SeatStatus.SELECTED.name()); + String zsetHoldKey = RedisKeyProvider.trackExpiresKey(SeatStatus.HOLD.name()); + + Duration ttl = null; + long nowMillis = System.currentTimeMillis(); + + redisTemplate.opsForZSet().remove(zsetSelectedKey, member); + redisTemplate.opsForZSet().remove(zsetHoldKey, member); + + switch(seatStatus){ + case SELECTED: + ttl = Duration.ofMinutes(5); + redisTemplate.expire(seatLockkey, ttl); + redisTemplate.opsForZSet().add(zsetSelectedKey, member, nowMillis+ttl.toMillis()); + break; + case HOLD: + ttl = Duration.ofMinutes(60); + redisTemplate.expire(seatLockkey, ttl); + redisTemplate.opsForZSet().add(zsetHoldKey, member, nowMillis+ttl.toMillis()); + break; + default: + redisTemplate.persist(seatLockkey); + break; + } + } + + public SeatScheduleInfo findById(Long seatScheduleInfoId){ + return seatScheduleInfoRepository.findById(seatScheduleInfoId) + .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUNT_SEAT_SCHEDULE_INFO)); + } } diff --git a/src/main/java/org/example/siljeun/domain/user/entity/User.java b/src/main/java/org/example/siljeun/domain/user/entity/User.java index 14ec94f..575d8c1 100644 --- a/src/main/java/org/example/siljeun/domain/user/entity/User.java +++ b/src/main/java/org/example/siljeun/domain/user/entity/User.java @@ -51,23 +51,31 @@ public class User extends BaseEntity { @Column(nullable = false) private Provider provider; - private String providerId; + private Long providerId; private LocalDateTime deletedAt; - public User(String email, String username, String password, String nickname, Role role, - Provider provider) { + // 로컬 회원 가입용 생성자 + public User(String email, String username, String password, String name, String nickname, + Role role, Provider provider) { this.email = email; this.username = username; this.password = password; + this.name = name; this.nickname = nickname; this.role = role; this.provider = provider; } - public User(String email, String nickname, Provider provider, String providerId) { + // 소셜 회원 가입용 생성자 + public User(String email, String username, String password, String name, String nickname, + Role role, Provider provider, Long providerId) { this.email = email; + this.username = username; + this.password = password; + this.name = name; this.nickname = nickname; + this.role = role; this.provider = provider; this.providerId = providerId; } diff --git a/src/main/java/org/example/siljeun/global/config/RedisConfig.java b/src/main/java/org/example/siljeun/global/config/RedisConfig.java index 4e97908..9097b30 100644 --- a/src/main/java/org/example/siljeun/global/config/RedisConfig.java +++ b/src/main/java/org/example/siljeun/global/config/RedisConfig.java @@ -6,6 +6,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; @@ -59,11 +60,14 @@ public RedisTemplate redisJsonTemplate(RedisConnectionFactory co } @Bean + @Primary RedisTemplate redisStringTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.setHashValueSerializer(new StringRedisSerializer()); return template; } } diff --git a/src/main/java/org/example/siljeun/global/config/SecurityConfig.java b/src/main/java/org/example/siljeun/global/config/SecurityConfig.java index 9afd186..70a80e3 100644 --- a/src/main/java/org/example/siljeun/global/config/SecurityConfig.java +++ b/src/main/java/org/example/siljeun/global/config/SecurityConfig.java @@ -31,14 +31,17 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth - .requestMatchers("/auth/**", "/oauth2/**", "/login/**", "/ws/**", "/ws","/checkout.html","/payments","/success.html").permitAll() + .requestMatchers("/auth/**", "/oauth/**", "/oauth2/**", "/login/**", "/ws/**", "/ws", + "/checkout.html", "/payments", "/success.html").permitAll() .anyRequest().authenticated() ) -// .oauth2Login(oauth2 -> oauth2 -// .successHandler(customOAuth2SuccessHandler) -// .defaultSuccessUrl("/auth/oauth2/success", true) -// .failureUrl("/auth/oauth2/failure") -// ) + .oauth2Login(oauth2 -> oauth2 + .successHandler(customOAuth2SuccessHandler) + .defaultSuccessUrl("/auth/oauth2/success") + .failureUrl("/auth/oauth2/failure") + ) +// .formLogin(form -> form +// .loginPage("/login")) .addFilterBefore(new JwtAuthenticationFilter(jwtUtil, userDetailsService), UsernamePasswordAuthenticationFilter.class); diff --git a/src/main/java/org/example/siljeun/global/security/CustomOAuth2SuccessHandler.java b/src/main/java/org/example/siljeun/global/security/CustomOAuth2SuccessHandler.java index dff18e0..8a32da3 100644 --- a/src/main/java/org/example/siljeun/global/security/CustomOAuth2SuccessHandler.java +++ b/src/main/java/org/example/siljeun/global/security/CustomOAuth2SuccessHandler.java @@ -6,6 +6,7 @@ import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; @@ -14,6 +15,7 @@ @Component @RequiredArgsConstructor +@Slf4j public class CustomOAuth2SuccessHandler implements AuthenticationSuccessHandler { private final JwtUtil jwtUtil; @@ -21,6 +23,8 @@ public class CustomOAuth2SuccessHandler implements AuthenticationSuccessHandler @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { + log.debug("----- 로그인 성공 -----"); + // principal에서 사용자 정보 추출 OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal(); String username = "kakao_" + oAuth2User.getAttribute("id").toString(); @@ -41,6 +45,9 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write("{\"message\": \"Login successful\"}"); response.getWriter().flush(); + + // 기본 경로로 리다이렉트 + response.sendRedirect("/"); } } diff --git a/src/main/java/org/example/siljeun/global/security/PrincipalDetails.java b/src/main/java/org/example/siljeun/global/security/PrincipalDetails.java index 40c0d2a..dc7e71c 100644 --- a/src/main/java/org/example/siljeun/global/security/PrincipalDetails.java +++ b/src/main/java/org/example/siljeun/global/security/PrincipalDetails.java @@ -2,12 +2,14 @@ import java.util.Collection; import java.util.List; +import lombok.Getter; import lombok.RequiredArgsConstructor; import org.example.siljeun.domain.user.entity.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; +@Getter @RequiredArgsConstructor public class PrincipalDetails implements UserDetails { @@ -49,7 +51,8 @@ public boolean isCredentialsNonExpired() { @Override public boolean isEnabled() { - return user.getDeletedAt() != null; + // 삭제되지 않은 계정은 모두 활성화된 것으로 취급 + return user.getDeletedAt() == null; } -} +} \ No newline at end of file diff --git a/src/main/java/org/example/siljeun/global/util/RedisKeyProvider.java b/src/main/java/org/example/siljeun/global/util/RedisKeyProvider.java new file mode 100644 index 0000000..1d5f31f --- /dev/null +++ b/src/main/java/org/example/siljeun/global/util/RedisKeyProvider.java @@ -0,0 +1,23 @@ +package org.example.siljeun.global.util; + +public class RedisKeyProvider { + + //회차에 따른 회차별 좌석 정보 Id와 상태 + public static String seatStatusKey(Long scheduleId){ + return "seatStatus:" + scheduleId; + } + + //유저가 선점한 특정 회차의 좌석 상태 정보 Id + public static String userSelectedSeatKey(Long userId, Long scheduleId){ + return "user:"+userId+":schedule:"+scheduleId; + } + + //회차별 좌석 상태 정보 점유중 + public static String seatOccupyKey(Long seatScheduleInfoId){ + return "seat:occupy:"+seatScheduleInfoId; + } + + public static String trackExpiresKey(String status){ + return "expires:"+status; + } +} diff --git a/src/main/resources/static/checkout.html b/src/main/resources/static/checkout.html index c0d9c69..f3a1dd6 100644 --- a/src/main/resources/static/checkout.html +++ b/src/main/resources/static/checkout.html @@ -37,7 +37,7 @@ // ------ 주문의 결제 금액 설정 ------ await widgets.setAmount({ currency: "KRW", - value: 50000, + value: 5000, }); await Promise.all([