간단한 일기장 웹 페이지를 만들기 위해 직접 DB를 구축하기보다 firebase를 사용해보았다.
주로 사용하게 될 기능은 회원가입 및 소셜로그인, 일기 데이터 저장이었다.
yarn add firebase
로 설치Authentication
항목을 클릭하고 시작한다.새 제공업체 추가
에서 기본 email (회원가입용), 구글, github로그인을 추가해줬다. (나중에 시간있으면 apple도 추가해볼 생각이다.)// 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
를 이용해 엄청 간단하게 회원가입/로그인/소셜로그인 기능을 구현할 수 있었다.