diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 62021135..31fdc320 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -82,6 +82,8 @@ jobs: sudo docker pull ${{ secrets.DOCKER_REPO }}/ustory sudo docker-compose up -d sudo docker image prune -a -f +# sudo docker run --name github-actions-demo --rm -d -p 8080:8080 ${{ secrets.DOCKER_REPO }}/ustory + # NOTE: The Gradle Wrapper is the default and recommended way to run Gradle (https://docs.gradle.org/current/userguide/gradle_wrapper.html). # If your project does not have the Gradle Wrapper configured, you can use the following configuration to run Gradle with a specified version. diff --git a/src/main/java/com/elice/ustory/domain/user/constant/EmailMessageConstants.java b/src/main/java/com/elice/ustory/domain/user/constant/EmailMessageConstants.java new file mode 100644 index 00000000..c9481b45 --- /dev/null +++ b/src/main/java/com/elice/ustory/domain/user/constant/EmailMessageConstants.java @@ -0,0 +1,14 @@ +package com.elice.ustory.domain.user.constant; + +public class EmailMessageConstants { + public static final String NOT_FOUND_USER_EMAIL = "존재하지 않는 email입니다: %s"; + public static final String EMAIL_VERIFICATION_SENT = "가입된 이메일이라면 인증코드가 발송됩니다."; + public static final String EMAIL_VERIFICATION_FAILED = "가입되지 않은 이메일이므로 메일이 발송되지 않았습니다. 보안을 위해, 사용자에게 해당 이메일의 가입 여부를 반환하지 않습니다."; + public static final String EMAIL_CODE_NOT_MATCH = "인증 코드 요청이 주어진 이메일이지만, 인증 코드가 일치하지 않습니다."; + public static final String EMAIL_CODE_VALID = "이메일과 인증 코드가 일치하여, 유효한 인증 코드로 검증되었습니다."; + public static final String EMAIL_CODE_NONE = "인증 코드 요청이 오지 않은 이메일입니다."; + public static final String EMAIL_CODE_NONE_DETAIL = "인증 코드 요청이 오지 않은 이메일입니다. 보안을 위해, 사용자에게 해당 이메일의 가입 여부를 반환하지 않습니다."; + public static final String EMAIL_IN_USE = "사용중인_이메일"; + public static final String EMAIL_SOFT_DELETED = "탈퇴된_이메일"; + public static final String SUCCESS = "SUCCESS"; +} diff --git a/src/main/java/com/elice/ustory/domain/user/entity/RegexPatterns.java b/src/main/java/com/elice/ustory/domain/user/constant/RegexPatterns.java similarity index 89% rename from src/main/java/com/elice/ustory/domain/user/entity/RegexPatterns.java rename to src/main/java/com/elice/ustory/domain/user/constant/RegexPatterns.java index f0d21ced..877ce9eb 100644 --- a/src/main/java/com/elice/ustory/domain/user/entity/RegexPatterns.java +++ b/src/main/java/com/elice/ustory/domain/user/constant/RegexPatterns.java @@ -1,4 +1,4 @@ -package com.elice.ustory.domain.user.entity; +package com.elice.ustory.domain.user.constant; public class RegexPatterns { public static final String EMAIL_REG = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$"; diff --git a/src/main/java/com/elice/ustory/domain/user/constant/UserMessageConstants.java b/src/main/java/com/elice/ustory/domain/user/constant/UserMessageConstants.java new file mode 100644 index 00000000..c253990a --- /dev/null +++ b/src/main/java/com/elice/ustory/domain/user/constant/UserMessageConstants.java @@ -0,0 +1,11 @@ +package com.elice.ustory.domain.user.constant; + +public class UserMessageConstants { + public static final String NOT_FOUND_USER_ID_MESSAGE = "존재하지 않는 userId입니다: %d"; + public static final String NOT_FOUND_USER_EMAIL_MESSAGE = "존재하지 않는 email입니다: %s"; + public static final String NOT_VALID_NICKNAME_MESSAGE = "사용할 수 없는 nickname입니다: %s"; + public static final String DUPLICATE_EMAIL_MESSAGE = "이미 가입된 email입니다: %s"; + public static final String NOT_CREATED_DIARY_MESSAGE = "다음의 email로 가입 중인 유저의, 개인 다이어리를 생성하는 과정에서 문제가 발생하였습니다. 가입 정보는 저장되지 않습니다: %s"; + public static final String UNAUTHORIZED_MESSAGE = "헤더에 토큰이 입력되지 않았습니다."; + public static final String NOT_VALID_PASSWORD_MESSAGE = "비밀번호 확인이 일치하지 않습니다."; +} diff --git a/src/main/java/com/elice/ustory/domain/user/controller/UserController.java b/src/main/java/com/elice/ustory/domain/user/controller/UserController.java index 90991a4d..ff4377f0 100644 --- a/src/main/java/com/elice/ustory/domain/user/controller/UserController.java +++ b/src/main/java/com/elice/ustory/domain/user/controller/UserController.java @@ -140,7 +140,9 @@ public ResponseEntity validateNickname(@Valid @Request return ResponseEntity.ok(validateNicknameResponse); } - @Operation(summary = "Send Mail To Validate Email For Sign-Up API", description = "회원가입 시 이메일 검증을 위한 인증코드를 해당 메일로 발송한다. 이미 가입된 이메일인 경우 예외 발생.") + @Operation(summary = "Send Mail To Validate Email For Sign-Up API", + description = "회원가입 시 이메일 검증을 위한 인증코드를 해당 메일로 발송한다. 이미 가입된 이메일인 경우 예외 발생." + + "
detailMessage는 둘 중 하나: '사용중인\\_이메일' 또는 '탈퇴된\\_이메일'") @ApiResponses({ @ApiResponse(responseCode = "200", description = "Ok", content = @Content(mediaType = "application/json", schema = @Schema(implementation = AuthCodeCreateResponse.class))), @ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))), diff --git a/src/main/java/com/elice/ustory/domain/user/dto/ChangePwdRequest.java b/src/main/java/com/elice/ustory/domain/user/dto/ChangePwdRequest.java index f0a4abe4..3a44ec89 100644 --- a/src/main/java/com/elice/ustory/domain/user/dto/ChangePwdRequest.java +++ b/src/main/java/com/elice/ustory/domain/user/dto/ChangePwdRequest.java @@ -1,6 +1,6 @@ package com.elice.ustory.domain.user.dto; -import com.elice.ustory.domain.user.entity.RegexPatterns; +import com.elice.ustory.domain.user.constant.RegexPatterns; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.Pattern; import lombok.Getter; diff --git a/src/main/java/com/elice/ustory/domain/user/dto/LoginRequest.java b/src/main/java/com/elice/ustory/domain/user/dto/LoginRequest.java index 540c0a86..285b962e 100644 --- a/src/main/java/com/elice/ustory/domain/user/dto/LoginRequest.java +++ b/src/main/java/com/elice/ustory/domain/user/dto/LoginRequest.java @@ -1,6 +1,6 @@ package com.elice.ustory.domain.user.dto; -import com.elice.ustory.domain.user.entity.RegexPatterns; +import com.elice.ustory.domain.user.constant.RegexPatterns; import jakarta.validation.constraints.Pattern; import lombok.Data; diff --git a/src/main/java/com/elice/ustory/domain/user/dto/SignUpRequest.java b/src/main/java/com/elice/ustory/domain/user/dto/SignUpRequest.java index 64e4a340..fcb82276 100644 --- a/src/main/java/com/elice/ustory/domain/user/dto/SignUpRequest.java +++ b/src/main/java/com/elice/ustory/domain/user/dto/SignUpRequest.java @@ -1,6 +1,6 @@ package com.elice.ustory.domain.user.dto; -import com.elice.ustory.domain.user.entity.RegexPatterns; +import com.elice.ustory.domain.user.constant.RegexPatterns; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.*; import lombok.Data; diff --git a/src/main/java/com/elice/ustory/domain/user/dto/UpdateRequest.java b/src/main/java/com/elice/ustory/domain/user/dto/UpdateRequest.java index c3a8e6ca..9cd29383 100644 --- a/src/main/java/com/elice/ustory/domain/user/dto/UpdateRequest.java +++ b/src/main/java/com/elice/ustory/domain/user/dto/UpdateRequest.java @@ -1,7 +1,5 @@ package com.elice.ustory.domain.user.dto; -import com.elice.ustory.domain.user.entity.RegexPatterns; -import jakarta.validation.constraints.Pattern; import lombok.Data; @Data diff --git a/src/main/java/com/elice/ustory/domain/user/dto/auth/AuthCodeCreateRequest.java b/src/main/java/com/elice/ustory/domain/user/dto/auth/AuthCodeCreateRequest.java index f6070cb6..6e112760 100644 --- a/src/main/java/com/elice/ustory/domain/user/dto/auth/AuthCodeCreateRequest.java +++ b/src/main/java/com/elice/ustory/domain/user/dto/auth/AuthCodeCreateRequest.java @@ -1,6 +1,6 @@ package com.elice.ustory.domain.user.dto.auth; -import com.elice.ustory.domain.user.entity.RegexPatterns; +import com.elice.ustory.domain.user.constant.RegexPatterns; import jakarta.validation.constraints.Pattern; import lombok.*; diff --git a/src/main/java/com/elice/ustory/domain/user/dto/auth/AuthCodeVerifyRequest.java b/src/main/java/com/elice/ustory/domain/user/dto/auth/AuthCodeVerifyRequest.java index 69ef4a8c..2d328258 100644 --- a/src/main/java/com/elice/ustory/domain/user/dto/auth/AuthCodeVerifyRequest.java +++ b/src/main/java/com/elice/ustory/domain/user/dto/auth/AuthCodeVerifyRequest.java @@ -1,6 +1,6 @@ package com.elice.ustory.domain.user.dto.auth; -import com.elice.ustory.domain.user.entity.RegexPatterns; +import com.elice.ustory.domain.user.constant.RegexPatterns; import jakarta.validation.constraints.Pattern; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/src/main/java/com/elice/ustory/domain/user/dto/auth/ChangePwdCallRequest.java b/src/main/java/com/elice/ustory/domain/user/dto/auth/ChangePwdCallRequest.java index ffe42401..b5405bba 100644 --- a/src/main/java/com/elice/ustory/domain/user/dto/auth/ChangePwdCallRequest.java +++ b/src/main/java/com/elice/ustory/domain/user/dto/auth/ChangePwdCallRequest.java @@ -1,6 +1,6 @@ package com.elice.ustory.domain.user.dto.auth; -import com.elice.ustory.domain.user.entity.RegexPatterns; +import com.elice.ustory.domain.user.constant.RegexPatterns; import jakarta.validation.constraints.Pattern; import lombok.Getter; diff --git a/src/main/java/com/elice/ustory/domain/user/dto/auth/ChangePwdVerifyRequest.java b/src/main/java/com/elice/ustory/domain/user/dto/auth/ChangePwdVerifyRequest.java index 452c3776..c2bc7107 100644 --- a/src/main/java/com/elice/ustory/domain/user/dto/auth/ChangePwdVerifyRequest.java +++ b/src/main/java/com/elice/ustory/domain/user/dto/auth/ChangePwdVerifyRequest.java @@ -1,6 +1,7 @@ package com.elice.ustory.domain.user.dto.auth; -import com.elice.ustory.domain.user.entity.RegexPatterns; +import com.elice.ustory.domain.user.constant.RegexPatterns; +import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.Pattern; import lombok.Getter; diff --git a/src/main/java/com/elice/ustory/domain/user/repository/UserRepository.java b/src/main/java/com/elice/ustory/domain/user/repository/UserRepository.java index 8552a7f2..084c8c0d 100644 --- a/src/main/java/com/elice/ustory/domain/user/repository/UserRepository.java +++ b/src/main/java/com/elice/ustory/domain/user/repository/UserRepository.java @@ -2,9 +2,10 @@ import com.elice.ustory.domain.user.entity.Users; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import java.util.List; import java.util.Optional; @Repository @@ -13,4 +14,9 @@ public interface UserRepository extends JpaRepository { Optional findByEmail(String loginEmail); boolean existsByEmail(String loginEmail); + @Query(value = "SELECT COUNT(*) FROM users u WHERE u.email = :email", nativeQuery = true) + int countByEmailWithSoftDeleted(@Param("email") String email); + + @Query(value = "SELECT COUNT(*) FROM users u WHERE u.nickname = :nickname", nativeQuery = true) + int countByNicknameWithSoftDeleted(@Param("nickname") String nickname); } diff --git a/src/main/java/com/elice/ustory/domain/user/service/EmailService.java b/src/main/java/com/elice/ustory/domain/user/service/EmailService.java index 95f7493d..d9b28629 100644 --- a/src/main/java/com/elice/ustory/domain/user/service/EmailService.java +++ b/src/main/java/com/elice/ustory/domain/user/service/EmailService.java @@ -1,11 +1,12 @@ package com.elice.ustory.domain.user.service; +import com.elice.ustory.domain.user.constant.EmailMessageConstants; import com.elice.ustory.domain.user.dto.auth.*; import com.elice.ustory.domain.user.entity.EmailConfig; import com.elice.ustory.domain.user.entity.Users; import com.elice.ustory.domain.user.repository.UserRepository; +import com.elice.ustory.global.exception.model.ConflictException; import com.elice.ustory.global.exception.model.NotFoundException; -import com.elice.ustory.global.exception.model.ValidationException; import com.elice.ustory.global.jwt.JwtTokenProvider; import com.elice.ustory.global.redis.email.AuthCode; import com.elice.ustory.global.redis.email.AuthCodeForChangePwd; @@ -32,6 +33,7 @@ public class EmailService { private final AuthCodeRepository authCodeRepository; private final AuthCodeForChangePwdRepository authCodeForChangePwdRepository; private final EmailConfig emailConfig; + private String fromEmail; @PostConstruct @@ -65,8 +67,10 @@ public void sendMail(String toEmail, String title, String content) throws Messag public AuthCodeCreateResponse sendValidateSignupMail(String toEmail) throws MessagingException { // 0. 이메일 중복 체크 - if (validateEmail(toEmail).getIsSuccess() == false) { - throw new ValidationException("이미 가입된 이메일입니다."); + + EmailVerifyResponse emailVerifyResponse = validateEmail(toEmail); + if (emailVerifyResponse.getIsSuccess() == false) { + throw new ConflictException(emailVerifyResponse.getStatus()); }; // 1. 메일 내용 생성 @@ -115,17 +119,17 @@ public AuthCodeVerifyResponse verifySignupAuthCode(AuthCodeVerifyRequest authCod if (!foundAuthCode.equals(givenAuthCode)) { return AuthCodeVerifyResponse.builder() .isValid(false) - .message("인증 코드 요청이 주어진 이메일이지만, 인증 코드가 일치하지 않습니다.") + .message(EmailMessageConstants.EMAIL_CODE_NOT_MATCH) .build(); } return AuthCodeVerifyResponse.builder() .isValid(true) - .message("이메일과 인증 코드가 일치하여, 유효한 인증 코드로 검증되었습니다.") + .message(EmailMessageConstants.EMAIL_CODE_VALID) .build(); } else { return AuthCodeVerifyResponse.builder() .isValid(false) - .message("인증 코드 요청이 오지 않은 이메일입니다.") + .message(EmailMessageConstants.EMAIL_CODE_NONE) .build(); } } @@ -134,13 +138,21 @@ public EmailVerifyResponse validateEmail(String email) { if (userRepository.existsByEmail(email)) { return EmailVerifyResponse.builder() .isSuccess(false) - .status("EMAIL_DUPLICATE") + .status(EmailMessageConstants.EMAIL_IN_USE) + .build(); + } + + int emailCountWithSoftDeleted = userRepository.countByEmailWithSoftDeleted(email); + if (emailCountWithSoftDeleted > 0) { + return EmailVerifyResponse.builder() + .isSuccess(false) + .status(EmailMessageConstants.EMAIL_SOFT_DELETED) .build(); } return EmailVerifyResponse.builder() .isSuccess(true) - .status("SUCCESS") + .status(EmailMessageConstants.SUCCESS) .build(); } @@ -149,9 +161,9 @@ public ChangePwdCallResponse sendValidateUserMailForPwd(ChangePwdCallRequest cha String toEmail = changePwdCallRequest.getToEmail(); if (!userRepository.existsByEmail(toEmail)) { return ChangePwdCallResponse.builder() - .message("가입된 이메일이라면 인증코드가 발송됩니다.") + .message(EmailMessageConstants.EMAIL_VERIFICATION_SENT) .fromEmail(null) - .toEmail("가입되지 않은 이메일이므로 메일이 발송되지 않았습니다. 보안을 위해, 사용자에게 해당 이메일의 가입 여부를 반환하지 않습니다.") + .toEmail(EmailMessageConstants.EMAIL_VERIFICATION_FAILED) .title(null) .authCode(null) .build(); @@ -182,7 +194,7 @@ public ChangePwdCallResponse sendValidateUserMailForPwd(ChangePwdCallRequest cha // 4. api 결괏값 반환 return ChangePwdCallResponse.builder() - .message("가입된 이메일이라면 인증코드가 발송됩니다.") + .message(EmailMessageConstants.EMAIL_VERIFICATION_SENT) .fromEmail(fromEmail) .toEmail(toEmail) .title(title) @@ -206,7 +218,7 @@ public ChangePwdVerifyResponse verifyChangePwdCode(ChangePwdVerifyRequest change } else { // jwt 발급 시작: 이메일 인증 성공 시, 비밀번호 재설정을 위한 임시 토큰 발급 Users currentUser = userRepository.findByEmail(toMail) - .orElseThrow(() -> new NotFoundException("사용자를 찾을 수 없습니디")); + .orElseThrow(() -> new NotFoundException(String.format(EmailMessageConstants.NOT_FOUND_USER_EMAIL, toMail))); Long userId = currentUser.getId(); String accessToken = jwtTokenProvider.createAccessToken(userId); // jwt 발급 끝 @@ -214,13 +226,13 @@ public ChangePwdVerifyResponse verifyChangePwdCode(ChangePwdVerifyRequest change return ChangePwdVerifyResponse.builder() .accessToken(accessToken) .isValid(true) - .message("이메일과 인증 코드가 일치하여, 유효한 인증 코드로 검증되었습니다.") + .message(EmailMessageConstants.EMAIL_CODE_VALID) .build(); } } else { return ChangePwdVerifyResponse.builder() .isValid(false) - .message("인증 코드 요청이 오지 않은 이메일입니다. 보안을 위해, 사용자에게 해당 이메일의 가입 여부를 반환하지 않습니다.") + .message(EmailMessageConstants.EMAIL_CODE_NONE_DETAIL) .build(); } } diff --git a/src/main/java/com/elice/ustory/domain/user/service/UserService.java b/src/main/java/com/elice/ustory/domain/user/service/UserService.java index 2b0b3ff1..005da61b 100644 --- a/src/main/java/com/elice/ustory/domain/user/service/UserService.java +++ b/src/main/java/com/elice/ustory/domain/user/service/UserService.java @@ -1,5 +1,6 @@ package com.elice.ustory.domain.user.service; +import com.elice.ustory.domain.user.constant.UserMessageConstants; import com.elice.ustory.domain.diary.entity.Color; import com.elice.ustory.domain.diary.entity.Diary; import com.elice.ustory.domain.diary.entity.DiaryCategory; @@ -11,10 +12,7 @@ import com.elice.ustory.domain.user.dto.*; import com.elice.ustory.domain.user.entity.Users; import com.elice.ustory.domain.user.repository.UserRepository; -import com.elice.ustory.global.exception.model.InternalServerException; -import com.elice.ustory.global.exception.model.NotFoundException; -import com.elice.ustory.global.exception.model.UnauthorizedException; -import com.elice.ustory.global.exception.model.ValidationException; +import com.elice.ustory.global.exception.model.*; import com.elice.ustory.global.jwt.JwtTokenProvider; import com.elice.ustory.global.redis.refresh.RefreshTokenService; import jakarta.servlet.http.HttpServletRequest; @@ -41,7 +39,8 @@ public class UserService { private final RefreshTokenService refreshTokenService; public Users findById(Long userId) { - return userRepository.findById(userId).orElseThrow(); + return userRepository.findById(userId) + .orElseThrow(() -> new NotFoundException(String.format(UserMessageConstants.NOT_FOUND_USER_ID_MESSAGE, userId))); } public FindByNicknameResponse searchUserByNickname(String nickname) { @@ -68,28 +67,26 @@ public FindByNicknameResponse searchUserByNickname(String nickname) { @Transactional public Users signUp(SignUpRequest signUpRequest) { - // TODO: null 체크는 dto에서 미리 처리되므로 제거(dto-pattern) - - // 1-0. 입력값 유효성 체크 시작. 유효하지 않은 값은 차례로 하나씩 반환. - // TODO: 이메일을 인증된 값으로 넘겨준 게 맞는지 한 번 더 확인 - String nickname = signUpRequest.getNickname(); + // 1-0. 입력값 유효성 체크 시작 // 1-1. 닉네임 유효 재확인 + String nickname = signUpRequest.getNickname(); ValidateNicknameRequest validateNicknameRequest = new ValidateNicknameRequest(); validateNicknameRequest.setNickname(nickname); if (isValidNickname(validateNicknameRequest).getIsValid() == false) { - throw new ValidationException("사용할 수 없는 닉네임입니다."); + throw new ValidationException(String.format(UserMessageConstants.NOT_VALID_NICKNAME_MESSAGE, nickname)); }; // 1-2. 이메일 중복 재확인 String email = signUpRequest.getEmail(); - if (userRepository.findByEmail(email).isPresent()) { - throw new ValidationException("이미 가입된 이메일입니다."); + + int emailCountWithSoftDeleted = userRepository.countByEmailWithSoftDeleted(email); + if (emailCountWithSoftDeleted > 0) { + throw new ConflictException(String.format(UserMessageConstants.DUPLICATE_EMAIL_MESSAGE, email)); } - // 1-3. 이름 null 체크(현재 별도 조건 없음) + // 1-3. 이름 확인 (현재 별도 조건 없음) String name = signUpRequest.getName(); - checkUsernameRule(name); // 1-4. 비밀번호 일치 체크 String password = signUpRequest.getPassword(); @@ -129,7 +126,7 @@ public Users signUp(SignUpRequest signUpRequest) { diaryRepository.save(userDiary); diaryUserRepository.save(new DiaryUser(new DiaryUserId(userDiary, builtUser))); } catch (Exception e) { - throw new InternalServerException("개인 다이어리를 생성하는 과정에서 문제가 발생하였습니다."); + throw new InternalServerException(String.format(UserMessageConstants.NOT_CREATED_DIARY_MESSAGE, email)); } return newUser; @@ -138,10 +135,9 @@ public Users signUp(SignUpRequest signUpRequest) { @Transactional public Users updateUser(UpdateRequest updateRequest, Long userId) { //TODO: 회원 정보 수정 시 Access Token 재발급 해야함 - //TODO: Optional 예외처리 Users user = userRepository .findById(userId) - .orElseThrow(); + .orElseThrow(() -> new NotFoundException(String.format(UserMessageConstants.NOT_FOUND_USER_ID_MESSAGE, userId))); String name = updateRequest.getName(); String nickname = updateRequest.getNickname(); @@ -167,7 +163,7 @@ public Users updateUser(UpdateRequest updateRequest, Long userId) { public void updateLostPassword(Long userId, ChangePwdRequest changePwdRequest) { Users currentUser = userRepository.findById(userId) - .orElseThrow(() -> new NotFoundException("유저를 찾을 수 없습니다.")); + .orElseThrow(() -> new NotFoundException(String.format(UserMessageConstants.NOT_FOUND_USER_ID_MESSAGE, userId))); // 입력된 비밀번호 두 개의 일치 여부 확인 후, 다르면 에러 반환 String password = changePwdRequest.getPassword(); @@ -184,9 +180,8 @@ public void updateLostPassword(Long userId, ChangePwdRequest changePwdRequest) { public Users deleteUser(Long userId) { - //TODO: 예외처리 Users user = userRepository.findById(userId) - .orElseThrow(() -> new NotFoundException("유저를 찾을 수 없습니다.")); + .orElseThrow(() -> new NotFoundException(String.format(UserMessageConstants.NOT_FOUND_USER_ID_MESSAGE, userId))); user.setDeletedAt(LocalDateTime.now()); @@ -199,9 +194,8 @@ public LoginResponse login(LoginRequest loginRequest, HttpServletResponse respon String rawPassword = loginRequest.getPassword(); LoginResponse loginResponse = new LoginResponse(); - //TODO: 예외처리 Users loginUser = userRepository.findByEmail(id) - .orElseThrow(() -> new NotFoundException("해당 이메일을 가진 유저를 찾을 수 없습니다.")); + .orElseThrow(() -> new NotFoundException(String.format(UserMessageConstants.NOT_FOUND_USER_EMAIL_MESSAGE, id))); String encodedPassword = loginUser.getPassword(); log.info("[getSignInResult] Id : {}", id); @@ -237,7 +231,7 @@ public LogoutResponse logout(HttpServletRequest request) { String token = request.getHeader("Authorization"); if (token == null) { - throw new UnauthorizedException("헤더에 토큰을 입력해주세요."); + throw new UnauthorizedException(UserMessageConstants.UNAUTHORIZED_MESSAGE); } if (token.startsWith("Bearer ")) { token = token.substring(7); @@ -251,7 +245,7 @@ public LogoutResponse logout(HttpServletRequest request) { public MyPageResponse showMyPage(Long userId) { Users currentUser = userRepository.findById(userId) - .orElseThrow(() -> new NotFoundException("유저를 찾을 수 없습니다.")); + .orElseThrow(() -> new NotFoundException(String.format(UserMessageConstants.NOT_FOUND_USER_ID_MESSAGE, userId))); String nickname = currentUser.getNickname(); String name = currentUser.getName(); String profileDescription = currentUser.getProfileDescription(); @@ -270,7 +264,8 @@ public MyPageResponse showMyPage(Long userId) { public ValidateNicknameResponse isValidNickname(ValidateNicknameRequest validateNicknameRequest) { String nickname = validateNicknameRequest.getNickname(); - if (userRepository.findByNickname(nickname).isPresent()) { + int nicknameCountWithSoftDeleted = userRepository.countByNicknameWithSoftDeleted(nickname); + if (nicknameCountWithSoftDeleted > 0) { return ValidateNicknameResponse.builder() .isValid(false) .isDuplicate(true) @@ -289,13 +284,8 @@ public boolean checkExistByEmail(String email) { public void checkNewPasswordMatch(String firstEnter, String secondEnter) { if (!firstEnter.equals(secondEnter)) { - throw new ValidationException("비밀번호가 일치하지 않습니다."); + throw new ValidationException(UserMessageConstants.NOT_VALID_PASSWORD_MESSAGE); } } - public void checkUsernameRule(String username) { - if (username == null) { - throw new ValidationException("사용자 이름을 입력해주세요."); - } - } } \ No newline at end of file diff --git a/src/main/java/com/elice/ustory/global/resolver/JwtAuthorizationArgumentResolver.java b/src/main/java/com/elice/ustory/global/resolver/JwtAuthorizationArgumentResolver.java index 0a288db2..0bcd1a3d 100644 --- a/src/main/java/com/elice/ustory/global/resolver/JwtAuthorizationArgumentResolver.java +++ b/src/main/java/com/elice/ustory/global/resolver/JwtAuthorizationArgumentResolver.java @@ -1,5 +1,6 @@ package com.elice.ustory.global.resolver; +import com.elice.ustory.global.exception.model.InvalidTokenException; import com.elice.ustory.global.jwt.JwtAuthorization; import com.elice.ustory.global.jwt.JwtUtil; import jakarta.servlet.http.HttpServletRequest; @@ -37,16 +38,13 @@ public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer m return jwtUtil.getUserPk(accessToken); } - // 토큰은 없지만 필수가 아닌 경우 체크 JwtAuthorization annotation = parameter.getParameterAnnotation(JwtAuthorization.class); if (annotation != null && !annotation.required()) { - // 필수가 아닌 경우 기본 객체 리턴 return jwtUtil.getUserPk(accessToken); } } - // 토큰 값이 없으면 에러 - throw new RuntimeException("권한 없음."); + throw new InvalidTokenException("토큰 형식이 잘못되었습니다."); } }