yarn add firebase
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에 제외 설정을 해준다.
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=값을 입력...
import { signInWithEmailAndPassword } from "firebase/auth";
import { firebaseAuth } from "../../../firebase.config";
// 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!");
}
}
};
import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";
// 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
를 관리해주면 될 듯?