如何在 React 中获取登录用户的 Firebase 元数据?



我已经使用firebase来验证我的应用程序中的用户。然而,获得他们的元数据来显示最后登录日期和帐户创建数据一直是一个麻烦。这里的文档没有多大帮助。

我知道我可以从"firebase/auth"导入{UserMetadata}但在那之后我尝试的任何方法都不起作用。似乎文档是基于Typescript的,我一直得到错误。

如果可能的话,我希望得到与此格式类似的元数据

<div className="membership_start_date account_overview_card">
<h2 className='account_overview_card_title'>Member since</h2>
<p className='account_overview_card_detail'>{metadata}</p>
</div>

我试过进口UserMetaData:

import {UserMetadata} from "firebase/auth"
const Account = () => {
const metadata = UserMetadata()
return (
<p className='account_overview_card_detail'>{metadata.lastSignIn}</p>
)
}
export default Account

整个代码很长,所以我试着把它恢复到最必要的部分。我做错了什么?

UserMetadata是user对象的一部分。假设您已经有了登录方法。然后在验证状态订阅方法中,您可以访问用户的数据:

useEffect(() => {
const unregisterAuthObserver = getAuth(firebaseApp).onAuthStateChanged(
async (authUser) => {
if (authUser) {
// authUser.metadata?.creationTime <--- here
// authUser.metadata?.lastSignInTime <-- and here
}
},
);
// Make sure we un-register Firebase observers when the component unmounts.
return () => unregisterAuthObserver(); 
}, [firebaseApp]);

你甚至可以测试一个简短的版本,全局设置firebase:

getAuth().currentUser?.metadata

首先确保已正确导出fbAuth:

import { initializeApp } from "firebase/app";
import { getFunctions, connectFunctionsEmulator } from "firebase/functions";
import { getAuth, connectAuthEmulator } from "firebase/auth";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
import fbConfig from "../../firebase.json";
export const fbApp = initializeApp({
apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
databaseURL: import.meta.env.VITE_FIREBASE_DATABASE_URL,
projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_FIREBASE_APP_ID,
});
export const fbFunctions = getFunctions(fbApp);
export const fbAuth = getAuth(fbApp);
export const db = getFirestore(fbApp);
if (import.meta.env.DEV) {
connectFunctionsEmulator(
fbFunctions,
"localhost",
fbConfig.emulators.functions.port
);
connectAuthEmulator(
fbAuth,
`http://localhost:${fbConfig.emulators.auth.port}`
);
connectFirestoreEmulator(db, `localhost`, fbConfig.emulators.firestore.port);
}

然后在某个点调用所需的身份验证方法:

import { ref } from "vue";
import { defineStore } from "pinia";
import { GoogleAuthProvider, signInWithPopup, signOut } from "firebase/auth";
import { fbAuth } from "../config/firebase";
export const useUserStore = defineStore("user", () => {
const user = ref({ uid: null });
const lastUser = localStorage.getItem("lastUser");
if (lastUser) {
user.value = JSON.parse(lastUser);
}
const fbLogin = (e) => {
console.log(e);
if (!user.value || !user.value.uid) {
const provider = new GoogleAuthProvider();
signInWithPopup(fbAuth, provider).then((result) => {
console.log(result);
const {
accessToken,
displayName,
email,
emailVerified,
isAnonymous,
uid
} = result.user;
user.value = result.user;
localStorage.setItem(
"lastUser",
JSON.stringify({
accessToken,
displayName,
email,
emailVerified,
isAnonymous,
uid
})
);
});
} else {
signOut(fbAuth).then((e) => {
user.value = { uid: null };
console.log(e);
console.log("user sign out");
localStorage.removeItem("lastUser");
});
}
};
return { user, fbLogin };
});

最后检查当前用户:

<template>
<div>
<h1>Authenticate</h1>
<button @click="userStore.fbLogin">Login/Logout</button>
<p v-if="userStore?.user && userStore?.user?.uid">
Hello, {{ userStore?.user?.displayName }}!
</p>
<p v-else>Not logged</p>
</div>
</template>
<script setup>
// https://firebase.google.com/docs/auth/web/manage-users#get_a_users_profile
import { useUserStore } from "../stores/user";
const userStore = useUserStore();
</script>

完整的源代码在这里。它是用vue写的,但总体思想和它非常相似。

相关内容

  • 没有找到相关文章

最新更新