로그인에 성공하면 메인화면으로 가도록 하는 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))
}
history > location 에서 pathname을 /main
을 전달했다.
*라우터 설정에 대해서는 별도 포스팅으로 남길 예정이다. 여기서 메인 화면으로 가기 위해 path 설정을 /main으로 해두었다.
그리고 state에 uid를 전달했다.
const goToMain = (userId) => {
history.push({
pathname: "/main",
state: {id: userId}
});
}
화면을 이동했을 때 uid를 그대로 받아올 수 있도록, history > location > state 안에 값이 있다면 state안에 저장된 uid값을 userId로 저장했다.
const history = useHistory();
const historyState = history?.location?.state;
const [userId, setUserId] = useState(historyState && historyState.id);
지난 포스팅에서 작성했던 getData함수를 수정했다. userId를 함께 전달한다.
const getData =() => {
const orderNoVal = orderNoRef.current.value;
const brandVal = brandRef.current.value;
console.log(userId, orderNoVal, brandVal)
database.saveData(userId, orderNoVal, brandVal)
}
여기서 database.saveData를 정의한 Database클래스에서는 userId 하위에 정보들이 들어가도록 경로설정을 약간 수정해주었다.
class Database {
saveData(userId, orderNo, brand) {
firebaseApp.database().ref(`${userId}/`).set({
orderNo : orderNo,
brand : brand,
});
}
}
이전 포스팅에서는 test로 지정했지만, 이번에는 유저 아이디 하위에 데이터가 저장된 것을 볼 수 있다.
사용자의 프로필 정보를 가져오려면 User 인스턴스의 속성을 사용합니다. 예를 들면 다음과 같습니다.
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을 대신 사용하라고 적혀있다. 잠재적인 공격이나 보안상의 문제 때문인 듯하다.