Firebase는 백엔드 없이 간편하게 앱을 구현할 수 있도록 도와준다.
그 중 authentication(인증), 그 중에서도 구글 로그인에 대해 정리해보려고 한다.
공식 문서를 참고할 때에는 firebase > build > authentication 로 들어가면 된다.
authentication에서는 visit console 과 view docs가 있는데 처음에는 visit console로 가서 프로젝트를 생성하고 config 정보를 얻어야 한다.
나는 그 이후의 과정을 정리하려고 한다.
view docs > federated identity provider integration > google - web
// googleAuthProvider.js
import { GoogleAuthProvider } from "firebase/auth";
export const provider = new GoogleAuthProvider();
// login.js
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { provider } from '../config/googleAuthProvider'
const auth = getAuth();
signInWithPopup(auth, provider)
// 팝업으로 로그인할 수 있도록 도와주는 함수이다.
.then((result) => {
const credential = GoogleAuthProvider.credentialFromResult(result);
// 로그인 절차를 걸치고 나면 credential을 통해 유저의 정보를 얻을 수 있다.
const token = credential.accessToken;
const user = result.user;
}).catch((error) => {
// 에러 핸들링
});
import { getAuth } from "firebase/auth";
const auth = getAuth();
export const signout = () => {
signOut(auth).catch(console.error);
};
유저가 로그인 한 상태인지 확인할 수 있는 방법으로는 관찰자를 넣어주는 것이다.
export const onAuthState = (callback) => {
onAuthStateChanged(auth, async (user) => {
callback(user);
});
};
나의 경우에는 컴포넌트 내에서 state에 유저의 정보를 저장하고있어야 했기 때문에 함수 내에 콜백을 넣어주어 setState를 넣어주면 그 안에 user가 들어가도록 설정 해두었다.
이렇게 해두면 유저가 로그인, 로그아웃했을 때마다 상태가 달라짐을 알수 있다.
firebase 를 처음 사용하다보니 가장 어려웠던 점은 "어떤 파일에 이 코드들을 입력해야하는 지" 잘 모르겠다는 것이었다.
결론적으로 말하면 google provider는 config 폴더 안에서 초기 설정을 하고
인증하는데 필요한 signInWithPopup 메서드는 로그인 컴포넌트에서 사용하면 된다.