JAVASCRIPT

firebase web version 8에서 회원가입, 인증 구현하기.

Neda 2023. 1. 3. 01:35

※ 버전8과 버전9는 사용법이 다를 수 있으므로 

npm firebase --version  명령어로 확인 필요

 

0. Firebase 웹 SDK 버전 8에서 버전 9으로 올리는 방법

 

버전 8에서 모듈식 웹 SDK로 업그레이드  |  Firebase

Google은 흑인 공동체를 위한 인종적 평등을 추구하기 위해 노력하고 있습니다. 자세히 알아보기 이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 의견 보내기 버전 8에서 모듈

firebase.google.com

 

1. 파이어 베이스 시작하기 (app.initializeApp)

 

JavaScript 프로젝트에 Firebase 추가

Google은 흑인 공동체를 위한 인종적 평등을 추구하기 위해 노력하고 있습니다. 자세히 알아보기 이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 의견 보내기 JavaScript 프로젝

firebase.google.com

 

2. 인증 추가하기 (auth.getAuth, auth.signInWithEmailAndPassword,  createUserWithEmailAndPassword)

 

웹사이트에서 Firebase 인증 시작하기

Firebase Summit에서 발표된 모든 내용을 살펴보고 Firebase로 앱을 빠르게 개발하고 안심하고 앱을 실행하는 방법을 알아보세요. 자세히 알아보기 이 페이지는 Cloud Translation API를 통해 번역되었습니

firebase.google.com


 

✅인증SDK 추가 및 초기화(firebase-auth.js)

import { initializeApp } from "firebase/app";
import {
  getAuth,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  signOut
} from "firebase/auth";
import config from "config.json";

const app = initializeApp(config);
const auth = getAuth(app);

export const signup = async ({ email, password }) => {
  const { user } = await createUserWithEmailAndPassword(auth, email, password);
  return user;
};

export const login = async ({ email, password }) => {
  const { user } = await signInWithEmailAndPassword(auth, email, password);
  return user;
};

export const getCurrentUser = () => {
  return auth.currentUser;
};

export const logout = async () => {
  return await signOut(auth);
};

 

✅신규 사용자 등록(Signup)

import { signup } from "./firebase-auth";

const _handleSignupButtonPress = async () => {
    try {
      const user = await signup({ email, password });
      console.log("Signup Success", user.email);
    } catch (e) {
      console.log("Signup Error", e.message);
    }
};

 

✅사용자 인증(Login)

import { login } from "./firebase-auth";

 const _handleLoginButtonPress = async () => {
    try {
      const user = await login({ email, password });
      console.log("Login Success", user);
    } catch (e) {
      console.log("Login Error", e.message);
    }
  };

 

✅사용자 정보 가져오기(currentUser)

import { getCurrentUser } from "./firebase-auth";

const user = getCurrentUser();

const uid = user.uid;
const displayName = user.displayName;
const email = user.email;
const phoneNumber = user.phoneNumber;
const photoURL = user.photoURL;
const emailVerified = user.emailVerified;

 

✅사용자 로그아웃(Logout)

 import { logout } from "./firebase-auth";

 const _handleLogoutButtonPress = async () => {
    try {
      await logout();
      console.log("Logout Success");
    } catch (e) {
      console.log("Logout error: ", e.message);
    }
  };