간단한 투두리스트로 시작했는데, 생각해보니 로그인기능을 추가해야 사람들이 진짜 사용할 수 있겠다 싶었다. 간편하게 만들 수 있는 서버인 firebase가 생각나 연동해보기로 하였다.
파이어베이스를 프로젝트에 사용하려면 먼저 firebase sdk를 설치해야한다. 이를 위해 다음 절차를 거쳐야 한다.
npm install firebase
firebase.js에 getAuth 함수 import 후 auth객체 생성
import { getAuth } from "firebase/auth";
....
export const firebaseAuth = getAuth(app);
....
OnAuthStateChanged 함수(firebase 제공) useEffect에 추가(위에서 export한 auth객체를 사용)
이 함수는 Auth상태가 앱 내 어디선가 변하면 이를 감지하고 변화시 특정 작업을 하는 함수이다.
import "./App.css";
import { firebaseAuth, firestore } from "./service/firebase";
import { collection, query, where, getDocs } from "firebase/firestore";
import { onAuthStateChanged } from "firebase/auth";
import { AppRouter } from "./Routers/AppRouter";
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userInfo, setUserInfo] = useState(null);
const [init, setInit] = useState(false);
useEffect(() => {
onAuthStateChanged(firebaseAuth, async (user) => {
if (user) {
const q = query(
collection(firestore, "users"),
where("uid", "==", user.uid)
);
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
const data = doc.data();
setUserInfo({
uid: data.uid,
email: data.email,
displayName: data.displayName,
date_created: data.date_created,
});
});
setIsLoggedIn(true);
}
setInit(true);
});
}, []);
회원가입 기능 붙이기 (createUserWithEmailAndPassword
함수 사용)
우리의 경우 SignupPage.jsx
를 만들어 회원가입 폼을 만들고, 회원가입 버튼에 다음과 같은 핸들러를 붙였다. createUserWithEmailAndPassword
는 firebase/auth
모듈에서 가져올 수 있다. handleSignup
함수를 보면, 우리가 작성한 회원가입 폼 내용을 바탕으로 firebase authentication에 유저를 생성한 뒤 우리의 데이터베이스(firestore)에 addDoc
을 사용하여 유저 튜플을 추가해주고 있다.
import { createUserWithEmailAndPassword } from "firebase/auth";
import { addDoc, collection } from "firebase/firestore";
...
const handleSignup = async (e) => {
e.preventDefault();
await createUserWithEmailAndPassword(
firebaseAuth,
input.email,
input.password
)
.then(async (userCredential) => {
const user = userCredential.user;
await addDoc(collection(firestore, "users"), {
uid: user.uid,
...input,
});
navigate("/");
})
.catch((error) => {
console.log(error);
});
};
...
로그인 기능 붙이기 (signInWithEmailAndPassword
함수 사용)
마찬가지로 로그인 또한 SignInPage.jsx
에 핸들러 함수로 구현해준다. 핸들러를 보면 로그인이 성공하면 (then
절) 홈페이지("/"
)로 이동시켜주고 있다.
import { signInWithEmailAndPassword } from "firebase/auth";
...
const handleSignin = async (e) => {
e.preventDefault();
await signInWithEmailAndPassword(firebaseAuth, input.email, input.password)
.then(() => {
navigate("/");
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.warn(`${errorCode} = ${errorMessage}`);
});
};
...
test@test.com 이라는 계정을 만들고 firebase 콘솔을 확인해보자.
다음과 같이 firebase authentication 콘솔에 유저가 추가된 것을 확인할 수 있다.
firestore의 users collection에도 잘 들어왔다.