Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[FEATURE-77] 인증 코드 검증 API 분리 및 Kakao Oauth 로그인 응답 구조 변경 #78

Merged
merged 1 commit into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -67,21 +67,21 @@ public ResponseDto<Void> requestEmail(
}

/**
* 3. 인증 코드 검증
* 3. 회원가입 인증 코드 검증
* - 사용자가 이메일로 받은 인증 코드 검증하는 컨트롤러
* - 회원가입 & 비밀번호 재설정 모두 사용
* - /auth/check/code
**/
@PostMapping("/emails/verification")
public ResponseDto<Void> verifyAuthCode(
@PostMapping("/join/emails/verification")
public ResponseDto<Void> verifyJoinAuthCode(
@Valid @RequestBody EmailAuthenticationDto emailAuthenticationDto,
BindingResult bindingResult
) {
this.checkRequestValidation(bindingResult);
this.authService.verifyAuthCode(emailAuthenticationDto);
return ResponseDto.onSuccess(null);
this.authService.verifyJoinAuthCode(emailAuthenticationDto);
return ResponseDto.onSuccess();
}


/**
* 4. 일반 로그인
* - /auth/login
Expand Down Expand Up @@ -109,6 +109,21 @@ public ResponseDto<Void> requestEmailForPassword(
return ResponseDto.onSuccess(null);
}


/**
* 비밀번호 재설정 인증 코드 검증
* - 사용자가 이메일로 받은 인증 코드 검증하는 컨트롤러
**/
@PostMapping("/password/emails/verification")
public ResponseDto<Void> verifyPasswordResetAuthCode(
@Valid @RequestBody EmailAuthenticationDto emailAuthenticationDto,
BindingResult bindingResult
) {
this.checkRequestValidation(bindingResult);
this.authService.verifyPasswordResetAuthCode(emailAuthenticationDto);
return ResponseDto.onSuccess();
}

/**
* 6. 비밀번호 재설정 요청 컨트롤러
* - /auth/password/reset
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.example.betteriter.global.common.response.ResponseDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
Expand All @@ -18,10 +19,10 @@ public class KakaoOauthController {
private final KakaoOauthService kakaoOauthService;

@GetMapping("/login/callback/kakao")
public ResponseDto<UserServiceTokenResponseDto> kakaoOauthLogin(
public ResponseEntity<UserServiceTokenResponseDto> kakaoOauthLogin(
@RequestParam String code
) throws IOException {
return ResponseDto.onSuccess(this.kakaoOauthService.kakaoOauthLogin(code));
return ResponseEntity.ok(this.kakaoOauthService.kakaoOauthLogin(code));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,6 @@ public Long join(JoinDto joinDto) {
return this.processJoin(joinDto, this.passwordUtil.encode(joinDto.getPassword()));
}

private Long processJoin(JoinDto joinDto, String encryptPassword) {
return this.userRepository.save(joinDto.toUserEntity(encryptPassword, joinDto.toUserDetailEntity()))
.getId();
}

/* 로그인 */
@Transactional
public UserServiceTokenResponseDto login(LoginDto loginRequestDto) {
Expand Down Expand Up @@ -94,32 +89,46 @@ public void requestEmailForPasswordReset(EmailDto emailDto) {
/* 비밀번호 재설정 */
@Transactional
public void resetPassword(PasswordResetRequestDto request) {
// 해당 이메일 유저 존재 여부 확인 및 로그인 타입 확인
User user = this.checkEmailExistenceAndType(request.getEmail());
user.setPassword(this.passwordUtil.encode(request.getPassword()));
log.info(this.passwordUtil.encode(request.getPassword()));
}

/* 인증 코드 체크 */
/* 회원 가입 인증 코드 체크 */
@Transactional
public void verifyAuthCode(EmailAuthenticationDto request) {
// 1. 이메일 중복 여부 확인
public void verifyJoinAuthCode(EmailAuthenticationDto request) {
// 1. 이메일 체크
this.checkEmailDuplication(request.getEmail());
// 2.요청받은 인증코드 존재 여부 확인
// 2. 요청 인증 코드 검증
this.verifyAuthCode(request);
}

/* 비밀번호 재설정 인증 코드 체크 */
@Transactional
public void verifyPasswordResetAuthCode(EmailAuthenticationDto request) {
// 해당 이메일 유저 존재 여부 확인 및 로그인 타입 확인
this.checkEmailExistenceAndType(request.getEmail());
// 2. 요청 인증 코드 검증
this.verifyAuthCode(request);
}

private void verifyAuthCode(EmailAuthenticationDto request) {
// 요청받은 인증코드 존재 여부 확인
String authCode = this.redisUtil.getData(request.getEmail());
if (authCode == null) {
log.debug("AuthService.verifyAuthCode() Exception Occurs! - auth code is null");
throw new UserHandler(_AUTH_CODE_NOT_EXIST);
}
// 3. 요청 auth code 와 redis 저장된 auth code 가 다른지 확인
// 요청 auth code 와 redis 저장된 auth code 가 다른지 확인
if (!request.getCode().equals(authCode)) {
log.warn("AuthService.verifyAuthCode() Exception Occurs! - auth code not match");
throw new UserHandler(_AUTH_CODE_NOT_MATCH);
}
// 4.인증 코드 검증 성공(redis 데이터 삭제)
// 인증 코드 검증 성공(redis 데이터 삭제)
this.redisUtil.deleteData(request.getEmail());
}


/* 닉네임 중복 여부 */
@Transactional
public Boolean checkNickname(String nickname) {
Expand All @@ -139,12 +148,20 @@ private String makeAuthCodeAndSave(EmailDto emailDto) {
return authCode;
}

/* 이메일 중복 여부 체크 및 인증 타입 체크 for 회원가입 */
private void checkEmailDuplication(String email) {
if (this.userRepository.findByEmail(email).isPresent()) {
throw new UserHandler(_EMAIL_DUPLICATION);
}
}

/* 이메일 중복 여부 체크 및 인증 타입 체크 for 비밀번호 재설정 */
private void checkEmailExistence(String email) {
if (this.userRepository.findByEmail(email).isEmpty()) {
throw new UserHandler(_EMAIL_NOT_FOUND);
}
}

private void checkPassword(LoginDto loginRequestDto, User user) {
if (!this.passwordUtil.isEqual(loginRequestDto.getPassword(), user.getPassword())) {
throw new UserHandler(ErrorCode._PASSWORD_NOT_MATCH);
Expand Down Expand Up @@ -197,4 +214,8 @@ private void checkUserLoginType(User user) {
}
}

private Long processJoin(JoinDto joinDto, String encryptPassword) {
return this.userRepository.save(joinDto.toUserEntity(encryptPassword, joinDto.toUserDetailEntity()))
.getId();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.example.betteriter.fo_domain.user.dto.oauth.KakaoJoinDto;
import com.example.betteriter.fo_domain.user.dto.oauth.KakaoToken;
import com.example.betteriter.fo_domain.user.repository.UserRepository;
import com.example.betteriter.global.config.properties.JwtProperties;
import com.example.betteriter.global.util.JwtUtil;
import com.example.betteriter.global.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -37,7 +36,6 @@ public class KakaoOauthService {
private final UserRepository userRepository;
private final InMemoryClientRegistrationRepository inMemoryClientRegistrationRepository;
private final JwtUtil jwtUtil;
private final JwtProperties jwtProperties;

/**
* - findUser : 회원 저장 및 리턴
Expand Down Expand Up @@ -104,6 +102,7 @@ private User saveUserWithKakaoUserInfo(KakaoToken kakaoToken,
ClientRegistration kakaoClientRegistration) throws IOException {
Map<String, Object> attributes = getUserAttributes(kakaoToken, kakaoClientRegistration);
KakaoOauthUserInfo kakaoOauthUserInfo = new KakaoOauthUserInfo(attributes);

String oauthId = kakaoOauthUserInfo.getOauthId();
String kakaoEmail = kakaoOauthUserInfo.getKakaoEmail();
return this.userRepository.findByOauthId(oauthId).orElseGet(() -> this.userRepository.save(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public enum ErrorCode {
_USER_NOT_FOUND(HttpStatus.BAD_REQUEST, "USER_NOT_FOUND_400", "일치하는 회원 정보를 찾을 수 없습니다."),
_PASSWORD_NOT_MATCH(HttpStatus.UNAUTHORIZED, "AUTH_PASSWORD_NOT_MATCH_401", "비밀번호가 일치하지 않습니다."),
_EMAIL_DUPLICATION(HttpStatus.BAD_REQUEST, "AUTH_EMAIL_DUPLICATION_401", "이미 존재하는 이메일입니다."),
_EMAIL_NOT_FOUND(HttpStatus.BAD_REQUEST, "AUTH_EMAIL_NOT_FOUND_401", "이메일이 존재하지 않습니다."),
_AUTH_CODE_ALREADY_EXIT(HttpStatus.BAD_REQUEST, "AUTH_CODE_ALREADY_EXIST_401", "이미 인증 코드가 존재합니다."),
_AUTH_CODE_NOT_EXIST(HttpStatus.BAD_REQUEST, "AUTH_CODE_NOT_EXIST_401", "인증 코드가 존재하지 않습니다."),
_AUTH_CODE_NOT_MATCH(HttpStatus.BAD_REQUEST, "AUTH_CODE_NOT_MATCH_401", "인증 코드가 일치하지 않습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public UserServiceTokenResponseDto createServiceToken(User user) {
.accessToken(this.jwtProperties.getBearer() + " " + accessToken)
.refreshToken(refreshToken)
.expiredTime(LocalDateTime.now().plusSeconds(this.jwtProperties.getAccessExpiration() / 1000))
.isExisted(user.getUsersDetail().getNickName() != null)
.isExisted(user.getUsersDetail() != null)
.build();
}

Expand Down
Loading