package com.example.emailAuthenticationvelog.domain.auth.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReqAuthenticateCodeApiV1DTO {
private String email;
private String code;
}
// 인증 번호 검증
@PostMapping("/authentication-code")
public HttpEntity<?> authenticateCode(@RequestBody ReqAuthenticateCodeApiV1DTO reqAuthenticateCodeApiV1DTO) {
return authServiceApiV1.authenticateCode(reqAuthenticateCodeApiV1DTO);
}
@Transactional
public HttpEntity<?> authenticateCode(ReqAuthenticateCodeApiV1DTO reqAuthenticateCodeApiV1DTO) {
// 유효한 인증 코드 데이터를 찾아서
Optional<MemberAuthenticationCodeEntity> memberAuthenticationCodeEntityOptional = memberAuthenticationCodeRepository
.findByEmailAndEndDateAfterAndDeleteDateIsNull(reqAuthenticateCodeApiV1DTO.getEmail(),
LocalDateTime.now());
// 없으면 인증 코드 없음 반환
if (memberAuthenticationCodeEntityOptional.isEmpty()) {
return new ResponseEntity<>(
ResDTO.builder()
.code(-1)
.message("인증 코드 없음")
.build(),
HttpStatus.BAD_REQUEST);
}
// 있으면 찾아서
MemberAuthenticationCodeEntity memberAuthenticationCodeEntity = memberAuthenticationCodeEntityOptional.get();
// 해당 entity의 인증 코드와 입력한 인증 코드가 일치하는 지 검증
if (memberAuthenticationCodeEntity.getCode().equals(reqAuthenticateCodeApiV1DTO.getCode())) {
// 인증 성공 처리
memberAuthenticationCodeEntity.setVerified(true);
return new ResponseEntity<>(
ResDTO.builder()
.code(0)
.message("인증 성공")
.build(),
HttpStatus.OK);
} else {
return new ResponseEntity<>(
ResDTO.builder()
.code(-1)
.message("인증 실패")
.build(),
HttpStatus.BAD_REQUEST);
}
}
document.querySelector("#confirmEmail").addEventListener("click", function () {
// 입력 창에서 값 가져오기
var email = document.querySelector("#email").value;
var authenticationCode = document.querySelector("#authenticationCode").value;
// 이메일과 인증 코드가 비어있는지 확인한다.
if (email === "" || authenticationCode === "") {
alert("이메일과 인증 코드를 입력해주세요.");
return;
}
// 이메일 주소를 JSON 형태로 만든다.
var data = {
"email": email,
"code": authenticationCode
};
// POST /email-authentication 요청을 보낸다.
fetch("/api/v1/auth/authentication-code", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then((response) => response.json())
.then((result) => {
if(result.code === 0){
console.log("err" ,result);
// 응답 결과를 alert로 보여준다.
alert(result.message);
}
if(result.code === -1){
// 응답 결과를 alert로 보여준다.
console.log("err" ,result);
alert(result.message);
}
});
});
이메일 전송까지는 그대로.
전송 후 이메일에서 인증번호를 복사해 입력한다.
코드가 같다면 인증 성공.