firebase는 데이터베이스를 저장하는 역할을 함.
개발자들이 서비스 개발 도구를 일일이 만드는 것은 시간과 비용이 많이 들기 때문에 이를 도와주는 앱을 개발하고, 개선하고, 키워갈 수 있는” 도구 모음(toolset)임
즉 메인 서비스를 개발하는 것이 아닌 테스트 용도라면 파이어 베이스를 사용함.
아이디어를 실현시키는 용도. 만약 실제 서비스 개발을 위한 용도라면, 파이어베이스가 아닌 다른 것을 사용할 것임.
❗️주의 사항!!
firebase는 무료가 아니다.
저렴하긴 하지만 기능마다 제한이 있음. 특히 데이터베이스 저장할 때나
사진 올릴 때 주의할 것!
https://firebase.google.com/
npm install firebase
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// 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
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: ",
appId: ""
};
// Initialize Firebase
export const app = initializeApp(firebaseConfig);
import myBase from "../myBase";
myBase.js
import { getAuth } from "firebase/auth";
export const auth = getAuth(app);
App.js
import { auth } from "../myBase";
👉 github 로그인 방식 세팅시 github페이지에서도 세팅 필요함!
github -> settings -> OAuth application ->
homepage-URL에 firebase에서 github 로그인 방식 선택했을 때 나온 callback URL를 기재하기
->register application 클릭 -> 이러면 client ID, Secret이 발급 됨.
->해당 내용을 firebase github 등록 입력창에 입력.
version 9 문서
https://firebase.google.com/docs/auth/web/password-auth?authuser=1#web-version-9
원래 myBase.js에 import 하고 가져오려고 했는데 그냥 바로 사용하는 파일에서 import해서 가져옴
Auth.js
import { auth } from "../myBase";
import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
} from "firebase/auth";
//이메일과 패스워드 입력 후 create Account 버튼 클릭시 유저 생성하는 함수
//공식문서에서 해당 함수는 promise 반환되는 함수라 async/await 사용
const handleSubmit = async (e) => {
e.preventDefault();
try {
let data; //data 선언용
if (newAccount) {
//create new account
data = await createUserWithEmailAndPassword(auth, email, password);
} else {
//login
data = await signInWithEmailAndPassword(auth, email, password);
}
console.log(data);
} catch (error) {
console.log(error);
}
위에 console.log(data)
작업으로 이메일과 패스워드 입력 후 버튼 클릭시 콘솔창에 유저 뜸. 나는 user를 갖게 된 것.
사용자들을 어떻게 기억할 것인지 선택할 수 있게 함.
App.js
const [isLogin, setIsLogin] = useState(auth.currentUser);
console.log(auth.currentUser);
setInterval(() => {
console.log(auth.currentUser);
}, 2000);
firebase가 초기화되고 모든 것을 로드할 때까지 기다려줄 시간이 없기 때문에 바로 로그아웃됨.
console.log(auth.currentUser)찍어보면 처음에는 null임
(사용자가 로그인되지 않은 상태)
이후에는 유저가 보임
이 부분을 수정해야함❗️
App.js
function App() {
const [init, setInit] = useState(false); //프로그램 초기화하길 기다려야함. 그다음에 isLogin이 바뀌도록
const [isLogin, setIsLogin] = useState(false);
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
setIsLogin(true);
} else {
setIsLogin(false);
}
setInit(true); //setInit이 false라면 router를 숨길 것이서 이렇게 처리함.
});
}, []);
return <>{init ? <Router isLogin={isLogin} /> : "Initializing....."}</>;
Auth.onAuthStateChanged():
사용자의 로그인 상태의 변화를 관찰하는 관찰자를 추가시킴 -> 이벤트 리스너
이렇게 하면 firebase를 기다려서 로그인되었다는 사실을 알아차린다음
로그인일 경우에 보여지는 router로 이동하게 되는 것임.
(새로고침하면 확인하는 동안 "Initailizing..."이 뜸)
https://firebase.google.com/docs/auth/web/google-signin?hl=ko
signInWithPopup
을 import하여 이용GoogleAuthProvider
,GithubAuthProvider
도 import 해준다.import {
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signInWithPopup,
GoogleAuthProvider,
GithubAuthProvider,
} from "firebase/auth";
Auth.js
const onSocialClick = async (event) => {
const {
target: { name },
} = event;
let provider;
if (name === "google") {
provider = new GoogleAuthProvider();
} else if (name === "github") {
provider = new GithubAuthProvider();
}
const data = await signInWithPopup(auth, provider);
console.log(data);
};
signOut
이용하기.const onLogOutClick = () => {
auth.signOut();
navigate("/");
};
<button onClick={onLogOutClick}>Log Out</button>
이렇게 하면 firebase Auth 이용하여 인증하기/ 로그인/ 로그아웃 기능 완성임
❗️오류 해결_1
구글로 로그인할 때 테스트 할 때는 잘 됐었는데, 그게 계속 잘 되는 것이 아니라 그게 잘 될때가 있고 잘 안될때가 있었다...
처음에는 뭐가 문제인지 모르겠었음.
오류 내용은
Cannot read properties of undefined (reading 'constructor')
at _assertInstanceOf (assert.ts:112:1)
뭐 이런 내용이었다. 그런데 오류 검색해도 잘 모르겠어서 다시 봤는데 알고보니,
const {
target: { name },
} = event;
이 부분에서 요소를 잘못 가지고 오는 것이었다.
target은 이벤트가 발생한 그 요소를 가지고 오는 것이고,
currentTarget은 이벤트 버블링, 캡처링이 이루어지는 과정에서 현재 이벤트가 위치하고 있는 요소를 가져오는 것이다.
target은 내가 클릭한 요소가 어떤 거냐에 따라서 인식하는 거라 계속 달라지는 바람에 그때그때 오류가 났다가 인식이 됐다가 했던 것 같음.
참고하기 :
target, currentTarget 설명 블로그 참고
❗️오류 해결_2
그리고 나는 구글이랑 깃헙 계정이 같은 계정인데 여기에서 오는 오류도 있었다.
구글 로그인시에는 잘됐는데 깃헙으로 로그인하려고 하니 안됐음.
그건 사용자계정에서 설정을 수정해줘야하는 문제였다.
아래와 같이 ID 공급업체별로 여러 계정 만들기로 체크 후 저장하면 완료임
이렇게해서 firebase를 이용한 로그인은 완성!!