firebase 사용법 2 (이메일을 이용한 기본 로그인)

김부릉·2023년 2월 20일
0
  1. firebase config, initialize
import firebase from "firebase/compat/app";
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
...
};

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

export default firebase;

영상을 따라하다 안되서 결국엔 검색.
지금은 되지만 나중에 또 안되서 바뀔 수도 있다.

  1. 로그인 상태인지 확인하기
const [isLoggedIn, setIsLoggedIn] = useState(authService.currentUser);
  • getAuth() 해온 정보중에서 현재유저의 상태로 /페이지가 로그인 화면이 될지 홈화면이 될지 route 해준다.
  1. 로그인 방법 설정하기
  • firebase웹페이지 -> Nwitter 프로젝트 선택 ->Authentication ->Sign in method -> 로그인 제공업체 추가
  • 이메일, 구글, github 선택함
  1. Auth.js 에 로그인 form 만들기

  2. 로그인 하기

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

const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in 
    const user = userCredential.user;
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    // ..
  });

https://firebase.google.com/docs/auth/web/password-auth?hl=ko
auth 문서에 기본 코드 예시
getAuth 와 createUser~ 매서드를 임포트 받아서 파라미터로 getAuth(), email, password를 넣어주면 로그인이 된다.
프로젝트 Authentication ->User에 들어가면 등록한 아이디를 확인 할 수 있다.

  1. 로그인 상태인지 확인하기
    https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#onauthstatechanged

onAuthStateChanged() 매서드 사용
user의 상태를 받아와서 로그인 상태를 구분한다

import { getAuth, onAuthStateChanged } from "firebase/auth";

useEffect(() => {
    const auth = getAuth();
    onAuthStateChanged(auth, (user) => {
      if (user) {
        setIsLoggedIn(true);
      } else {
        setIsLoggedIn(false);
      }
      setInit(true);
    });
  });

0개의 댓글