Spring Boot - 이메일 인증 (5) 구현 - 인증 코드 검증

ysh·2023년 11월 26일
0

인턴십

목록 보기
21/25

인증 로직

  • 이제 발송하고 DB에 저장된 인증 코드를 기준으로 인증을 진행해보자.

ReqAuthenticateCodeApiV1DTO.java - 인증 코드 검증 데이터 받을 DTO

  • 이메일, 인증 코드 받기 위함
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;
}

AuthControllerApiV1.java - Api 주소 매핑

  • DTO를 받아 service로 넘겨주자.
// 인증 번호 검증
    @PostMapping("/authentication-code")
    public HttpEntity<?> authenticateCode(@RequestBody ReqAuthenticateCodeApiV1DTO reqAuthenticateCodeApiV1DTO) {
        return authServiceApiV1.authenticateCode(reqAuthenticateCodeApiV1DTO);
    }

AuthServiceApiV1.java - 코드 검증 로직

@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);
        }

    }

index.html - 인증 버튼 이벤트 추가

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);
                }
            });
    });

인증 테스트

  • 이메일 전송까지는 그대로.

  • 전송 후 이메일에서 인증번호를 복사해 입력한다.

  • 코드가 같다면 인증 성공.

마무리

profile
유승한

0개의 댓글

관련 채용 정보