Firebase

[Firebase] Authentication으로 Email 로그인 구현하기 (2) - 로그인/회원가입

jundyu 2024. 10. 6. 19:45

 

이전 글에서 Email로 로그인/회원가입하기 위해 기본적인 설정하는 방법들을 알아봤습니다. 이전 포스트에 이어서 리액트와 Firebase의 Authentication으로 실제 로그인/회원가입하는 코드를 설명드리겠습니다.
 

 

[Firebase] Authentication으로 Email 로그인 구현하기 (1) - 기초

들어가며Firebase에서 제공하는 인증 기능은 구현이 간편할뿐만 아니라 사용자 데이터 보호를 위한 보안 메커니즘이 적용되어 있습니다. 또한 확장성도 뛰어나서 개발 후 추가적인 로그인/회원가

jundyu.tistory.com

 

 

회원가입

먼저 회원가입 핸들러입니다.

import React, { useState } from "react";
import { auth } from "../../firebase";
import { createUserWithEmailAndPassword } from "firebase/auth";

const SignUpForm = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    // 회원가입 버튼 클릭 핸들러
    async function handleSignUp(event) {
        event.preventDefault();
        
        try {
            const userCredential = await createUserWithEmailAndPassword(
                auth,
                email,
                password
            );
        
            // 필요한 로직 구현 //
        } catch (error) {
            console.log(error);
        }
    }

    return (
        // 생략 //
    );
}

1. createUserWithEmailAndPassword 메서드를 import하고, 인증 관리 객체인 auth를 사용하기 위해 설정 파일인 firebase.js로부터 import 했습니다.
2. 회원가입 버튼을 클릭하면 handleSingUp 이벤트 핸들러가 동작합니다. 이때 createUserWithEmailAndPassword 메서드는 auth 객체와 사용자가 입력한 email, password를 인자로 전달받습니다.
3. createUserWithEmailAndPassword 메서드는 자동으로 중복 검사와 이메일 형식 확인 등을 처리하므로, 개발자가 별도로 유효성 검사를 구현하지 않아도 됩니다. 그러나, 추가적인 유효성 검사를 통해 더 견고한 회원가입 프로세스를 만들 수 있습니다.
4. 회원가입이 완료되면 main 페이지로 이동하는 등 필요한 로직을 실행할 수 있습니다.
 

createUserWithEmailAndPassword에서 자주 발생하는 에러!
1. auth/email-already-in-use - 이미 사용되고 있는 이메일
2. auth/invalid-email - 유효하지 않은 이메일 주소 형식
3. auth/weak-password - 보안 기준을 충족하지 않은 비밀번호
4. auth/operation-not-allowed - Firebase Console에서 이메일/비밀번호 기반 인증 비활성화

 

로그인

다음으로 로그인입니다. 로그인도 회원가입만큼이나 간단합니다.

import React, { useState } from "react";
import { auth } from "../../firebase";
import { signInWithEmailAndPassword } from "firebase/auth";

const LoginForm = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    // 로그인 핸들러
    const handleLogin = async (event) => {
        event.preventDefault();

        try{
            await signInWithEmailAndPassword(auth, email, password);
            
            // 필요한 로직 구현 //
        } catch (error) {
        	console.log(error);
        }
    }

    return (
        <>생략</>
    );
}

1. signInWithEmailAndPassword 메서드와 auth 객체를 import 합니다.
2. 로그인 버튼을 누르면 handleLogin 핸들러가 동작합니다. 이때 signInWithEmailAndPassword 메서드의 인자에 auth, email, password를 순서대로 전달합니다.
3. signInWithEmailAndPassword 메서드로 로그인을 성공한 경우, 필요한 로직을 실행합니다.
 

signInWithEmailAndPassword에서 자주 발생하는 에러!
1. auth/wrong-password - 비밀번호를 잘못 입력
2. auth/user-not-found - 입력한 이메일이 존재하지 않음
3. auth/invaild-email - 잘못된 이메일 형식

 

.
.
.

 

마치며

여기까지 회원가입과 로그인 구현 코드였습니다. 여기까지 따라오고 이해하셨다면 로그인/회원가입이 허무하게 느껴질 것 같다고 생각합니다. 다음 글에선 로그아웃 및 회원탈퇴를 구현해보겠습니다.
 

 

[Firebase] Authentication으로 Email 로그인 구현하기 (3) - 로그아웃/회원탈퇴

[Firebase] Authentication으로 Email 로그인 구현하기 (2) - 로그인/회원가입 지난 글에서 로그인/회원가입까지 알아보았습니다. 마지막으로 로그아웃 및 회원탈퇴하는 방법을 살펴보겠습니다. 로그아

jundyu.tistory.com