Firebase 로그인, 구글로그인

준영·2023년 2월 20일
1

Firebase를 써보자..

목록 보기
1/8

공통 세팅

yarn add firebase

firebase.config.ts

import { initializeApp } from "firebase/app";
import {
  getAuth,
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
} from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_APP_ID,
  measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
};

// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const firebaseAuth = getAuth(firebaseApp);
const firebaseDb = getFirestore(firebaseApp);

export {
  firebaseAuth,
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  getFirestore,
};

firebaseConfig는 보안 때문에 .env파일로 환경변수를 설정하여 불러오는 방식을 채택
당연히 .env 파일은 .gitignore에 제외 설정을 해준다.

.env

NEXT_PUBLIC_API_KEY=값을 입력... (""안에 넣어주지 않는다!)
NEXT_PUBLIC_AUTH_DOMAIN=값을 입력...
NEXT_PUBLIC_PROJECT_ID=값을 입력...
NEXT_PUBLIC_STORAGE_BUCKET=값을 입력...
NEXT_PUBLIC_MESSAGING_SENDER_ID=값을 입력...
NEXT_PUBLIC_APP_ID=값을 입력...
NEXT_PUBLIC_MEASUREMENT_ID=값을 입력...

로그인 세팅

login.container.tsx import

import { signInWithEmailAndPassword } from "firebase/auth";
import { firebaseAuth } from "../../../firebase.config";

login.container.tsx func

// logIn func (email & pass 6 length up)
const login = async () => {
  try {
    const curUserInfo = await signInWithEmailAndPassword(
      firebaseAuth,
      id,
      pass
    );
    // init global user info
    setUserInfo(curUserInfo.user);
    console.log(curUserInfo.user);
    // change global login status
    setLoginStatus(true);
    router.push("/");
  } catch (err) {
    // global login state
    setLoginStatus(false);
    // console.log(err.code);
    if ((err.code = "auth/user-not-found")) {
      alert("User not found!");
    } else if (err.code == "auth/wrong-password") {
      alert("Wrong password!");
    }
  }
  };

구글 로그인

login.container.tsx import

import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";

login.container.tsx func

// google login func
const loginGoogle = () => {
  const googleProvider = new GoogleAuthProvider();
  signInWithPopup(firebaseAuth, googleProvider)
    .then((res) => {
    // global login & user info state
    setLoginStatus(true);
    setUserInfo(res.user);
    router.push("/");
  })
    .catch((err) => {
    console.log(err);
  });
};

이 외의 파이버베이스에서 로그인이 되었는지 확인해주는 함수 등등이 존재 하지만, 아직 사용하지 않았고, 나중에 그 함수를 이용하여 계속 검사해 주면서 setLoginStatus를 관리해주면 될 듯?


로그인

구글 로그인

profile
개인 이력, 포폴 관리 및 기술 블로그 사이트 👉 https://aimzero-web.vercel.app/

0개의 댓글