유저 아이디 별로 데이터 저장하기

GY·2021년 10월 18일
0

[React] FIrebase + React

목록 보기
4/8

🍔로그인 성공시 uid받아오기

로그인에 성공하면 메인화면으로 가도록 하는 goToMain함수에 uid를 인자로 전달했다.

  const onLogin = () => {
    const idVal = idRef.current.value;
    const passwordVal = passwordRef.current.value;
    authService.signIn(idVal, passwordVal)
    .then(result => goToMain(result.user.uid))
    .then(setErrorState(false))
    .catch(setErrorState(true))
  }


🍔컴포넌트 state에 id넣기

history > location 에서 pathname을 /main을 전달했다.

🍟router history.state - id 값 저장

*라우터 설정에 대해서는 별도 포스팅으로 남길 예정이다. 여기서 메인 화면으로 가기 위해 path 설정을 /main으로 해두었다.

그리고 state에 uid를 전달했다.

  const goToMain = (userId) => {
    history.push({
      pathname: "/main",
      state: {id: userId}
    });
  }


🍟useState - useId 값 설정

화면을 이동했을 때 uid를 그대로 받아올 수 있도록, history > location > state 안에 값이 있다면 state안에 저장된 uid값을 userId로 저장했다.

  const history = useHistory();
  const historyState = history?.location?.state;
  const [userId, setUserId] = useState(historyState && historyState.id);


🍟함수에 userId를 인자로 전달

지난 포스팅에서 작성했던 getData함수를 수정했다. userId를 함께 전달한다.

  const getData =() => {
    const orderNoVal = orderNoRef.current.value;
    const brandVal = brandRef.current.value;

    console.log(userId, orderNoVal, brandVal)
    database.saveData(userId, orderNoVal, brandVal)
  }


🍟ref - database 저장경로 지정

여기서 database.saveData를 정의한 Database클래스에서는 userId 하위에 정보들이 들어가도록 경로설정을 약간 수정해주었다.

class Database {
  saveData(userId, orderNo, brand) {
    firebaseApp.database().ref(`${userId}/`).set({
      orderNo : orderNo,
      brand : brand,
    });
  }
}


🍔저장된 데이터 확인

이전 포스팅에서는 test로 지정했지만, 이번에는 유저 아이디 하위에 데이터가 저장된 것을 볼 수 있다.



🍔하지만....

FIrebase 공식문서 내용

사용자 프로필 가져오기

사용자의 프로필 정보를 가져오려면 User 인스턴스의 속성을 사용합니다. 예를 들면 다음과 같습니다.

웹 버전 8

const user = firebase.auth().currentUser;
if (user !== null) {
  // The user object has basic properties such as display name, email, etc.
  const displayName = user.displayName;
  const email = user.email;
  const photoURL = user.photoURL;
  const emailVerified = user.emailVerified;

  // The user's ID, unique to the Firebase project. Do NOT use
  // this value to authenticate with your backend server, if
  // you have one. Use User.getToken() instead.
  const uid = user.uid;
}

  • 이렇게 하지 않아도 firebase에서 제공하는 사용자 정보를 가져오는 API가 있으니, 이걸 사용해 수정해보는 것이 좋을 것 같다.
  • 또한 백엔드에서 인증을 위해 uid를 사용하지 말고, getToken을 대신 사용하라고 적혀있다. 잠재적인 공격이나 보안상의 문제 때문인 듯하다.

Reference

firebase 공식문서 -

react router 공식문서

react공식문서 - Hook

profile
Why?에서 시작해 How를 찾는 과정을 좋아합니다. 그 고민과 성장의 과정을 꾸준히 기록하고자 합니다.

0개의 댓글