我正在开发一个类似于 Linktree 的项目,并实现了用于身份验证的 Firebase 和用于数据库的 Firestore。身份验证系统运行正常,并且用户数据正在保存在名为
users
的集合中。但是,当我重定向到用户的仪表板时,我在应显示数据的区域看到 undefined
。
在用户的仪表板代码中,我导入了数据库获取所需的所有内容。
import { db, auth } from "@/lib/firebaseConfig";
import { getDoc, doc } from "firebase/firestore";
import { signOut, onAuthStateChanged } from "firebase/auth";
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, async (user) => {
if (user) {
console.log("User authenticated:", user.uid); // Add a log to check user UID
try {
const userDocRef = doc(db, "users", user.uid);
const userDoc = await getDoc(userDocRef);
if (userDoc.exists()) {
console.log("User document found:", userDoc.data()); // Log the data
setUserData(userDoc.data());
} else {
console.log("User document does not exist."); // Log for debugging
alert("User document does not exist.");
}
} catch (error) {
console.error("Error fetching user data:", error);
alert(
`Error fetching user data: ${
error instanceof Error ? error.message : String(error)
}`
);
}
} else {
console.log("No user is authenticated. Redirecting to login.");
router.push("/"); // Redirect to home or login if no user is signed in
}
});
return () => unsubscribe();
}, [router]);
这是我的
firebaseConfig.ts
文件
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const auth = getAuth(app);
export { db, auth };
这是我最新的 Firestore 规则
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if true;
}
}
}
之前
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Allow read and write access to authenticated users on their own documents in the "users" collection
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
我已尝试多次更改规则,包括使用实际用户的
uid
到代码中,但没有任何效果。我也查阅了各种AI工具,但在这种情况下都没有效果。
第一个屏幕截图中的
grenishrai
文档 ID 看起来不像 UID,因此它与您的代码在此处执行的操作不匹配:
const userDocRef = doc(db, "users", user.uid);
为了使您的代码正常工作,请确保写入以完全相同的方式构建的文档引用。