[ Firebase ] 로그인 및 회원가입 (소셜로그인)

Yang⭐·2022년 12월 8일
0
post-thumbnail

사용계기

간단한 일기장 웹 페이지를 만들기 위해 직접 DB를 구축하기보다 firebase를 사용해보았다.

주로 사용하게 될 기능은 회원가입 및 소셜로그인, 일기 데이터 저장이었다.


초기 설정하기

  1. yarn add firebase로 설치
  2. firebase 페이지 내에서 프로젝트 추가 후 프로젝트 만들기
  3. Authentication 항목을 클릭하고 시작한다.
  4. 새 제공업체 추가에서 기본 email (회원가입용), 구글, github로그인을 추가해줬다. (나중에 시간있으면 apple도 추가해볼 생각이다.)
  5. 프로젝트 설정페이지로 이동 후 Firebase를 초기화해줄 코드를 내 프로젝트에 복붙해줬다. ( key값은 전부.env에 저장해서 불러옴)
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: import.meta.env.VITE_API_KEY,
  authDomain: import.meta.env.VITE_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_PROJECT_ID,
  storageBucket: import.meta.env.VITE_STORAGE_BUCKET,
  messagingSenderId: import.meta.env.VITE_MESSAGIN_ID,
  appId: import.meta.env.VITE_APP_ID,
  measurementId: import.meta.env.VITE_MEASUR_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const authService = getAuth(app);

회원가입 기능

  createUserWithEmailAndPassword(authService, email, password)
          .then((userCredential) => {
            // Signed in
            const { user } = userCredential;
            if (user) handleSuccess("회원가입이 완료됐습니다 ^^*");
          })
          .catch((error) => {
            const errorCode = error.code;
            if (errorCode?.includes("email-already-in-use"))
              handleError("이미 존재하는 이메일입니다.");
            else if (errorCode?.includes("weak-password"))
              handleError("비밀번호를 6자리 이상 설정해주세요");
          });
  • createUserWithEmailAndPassword 메소드에 신규 이메일과 패스워드를 전달한다.
  • catch문에서 에러코드로 예외처리를 해주었다.

로그인 기능

signInWithEmailAndPassword(authService, email, password)
          .then((userCredential) => {
            // Signed in
            const { user } = userCredential;
            user.getIdToken().then((token) => setToken(token));
            if (user) navigate("/home");
          })
          .catch((error) => {
            const errorCode = error.code;
            if (errorCode?.includes("user-not-found")) setLoginError("이메일이 존재하지 않아요");
            else if (errorCode?.includes("wrong-password"))
              setLoginError("비밀번호가 일치하지 않아요");
          });
  • signInWithEmailAndPassword 메소드에 가입된 이메일 패스워드를 전달한다.
  • 📌 로그인 상태를 유지하기 위해 토큰은 로컬스토리지에 저장해서 토큰관리를 해줬다.
  • catch문에서 회원가입처럼 에러코드로 예외처리함

소셜로그인

const githubProvider = new GithubAuthProvider();
const googleProvider = new GoogleAuthProvider();

github이랑 구글로그인만 추가해서 위 provider를 생성해줬다.

 signInWithPopup(authService, googleProvider)
      .then((result) => {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        setToken(token);
        window.location.href = "/";
      })
      .catch((error) => {
        handleError("로그인에 실패했어요 ㅜㅜ");
      });
  • 소셜로그인 시 팝업 창으로 로그인하려면 signInWithPopup, 로그인 페이지로 리디렉션하여 로그인하려면 signInWithRedirect 메소드를 사용해야한다.

참고로 Electron에서 소셜로그인 기능을 추가하려고 했는데 auth/operation-not-supported-in-this-environment 에러가 떴다.
팝업, 리다이렉트 둘 다 실패함..😥


매우 간단스!

firebase를 이용해 엄청 간단하게 회원가입/로그인/소셜로그인 기능을 구현할 수 있었다.

0개의 댓글