Firebase Authentication 이메일 인증 구현하기

이번에 처음으로 혼자 프로젝트를 맡아서 진행하게 되었습니다🧙‍♂️

급하게 맡아서 하는 프로젝트였기 때문에,
빠른 개발을 위해 회원가입을 Firebase Authentication 을 이용하게 되었습니다

💡회원가입 로직

회원가입 -> Firebase authentication 에 정보 등록 -> 이메일 인증 링크 발송 
-> 링크 확인 -> 실제 서버에 회원 등록

createUserWithEmailAndPassword (Authentication에 정보 저장) 를 실행한 다음, sendEmailVerification (이메일 전송) 을 호출해야한다

이메일 인증을 위한 링크 인증을 PC 와 모바일에서 할 수 있도록, emailVerificationEventListener를 통해 어느 기기에서 확인을 해도 인증이 완료 될 수 있도록 코드를 추가했습니다

import { initializeApp } from "firebase/app";
import { createUserWithEmailAndPassword, getAuth, sendEmailVerification } from "firebase/auth";
import "firebase/auth";

 const sendEmail = () => {
        createUserWithEmailAndPassword(auth, email, hashPassword(password))
            .then((userCredential) => {
                const user = userCredential.user;
                sendEmailVerification(auth.currentUser)
                    .then(async () => {
                        alert("창을 닫지 마세요\n이메일을 확인해주세요");
                        setLoading(true);
                        let emailVerificationEventListener = setInterval(async () => {
                            auth.currentUser.reload();
                            if (auth.currentUser.emailVerified) {
                                clearInterval(emailVerificationEventListener);
                                setLoading(false);
                                //실제 서버에 가입
                                handleSign();
                                navigate("/login");
                            }
                        }, 1000);
                    })
                    .catch((error) => {
                        console.log();
                        alert("다시시도해주세요");
                        navigate("/signup");
                    });
            })
            .catch((error) => {
                const errorCode = error.code;
                switch (errorCode) {
                    case "auth/invalid-email": {
                        alert("이메일을 다시 입력해주세요");
                        break;
                    }
                    case "auth/email-already-in-use": {
                        alert("이미 가입된 이메일입니다");
                        break;
                    }
                    default: {
                        alert("다시 시도해주세요");
                    }
                }
                console.log(`에러메세지:${errorCode}`);
            });
    };

💡문제점

해당 로직은 이메일 인증이 완료 될 때 까지 같은 페이지에서 reload 해주기 때문에 이메일 인증이 완료되지 않은채로 창을 끄게 될 경우 에러가 발생하게 되는 문제점이 있습니다

추후에는 OAuth 를 이용한 회원가입 로직으로 변경할 계획입니다

좋은 웹페이지 즐겨찾기