firebase 实时数据库,如何只读取自己的数据?
firebase realtime database, how to read only own data?
我的 nextjs webapp 中有一个实时数据库,我将其用于通知。
我的数据库架构如下:
我仅以管理员身份从服务器端写入数据,但通过以下方式从客户端读取数据:
const fetchNotifications = () => {
const starCountRef = ref(db, `notifications/${user?.id}`);
const q = query(starCountRef, orderByChild('createdAt'), limitToLast(100));
onValue(q, (snapshot) => {
//Handle data
});
};
此刻我有以下规则:
{
"rules": {
".read": "auth != null",
".write": false,
"notifications":{
"$user_id":{".indexOn":"createdAt"}
}
}
}
如您所见,每个经过身份验证的人都可以阅读所有内容。我希望用户只阅读他自己的通知。 ObjectID 是我的 mongoDB.
的引用
例如,如果我有 ID = 1
,我只想访问路径 /notifications/1
的数据,如果我尝试从 /notifications/2
获取数据,那么我什么也得不到(或错误)。
首先,我如何从 firebase 中看到我在本地数据库中使用的 ID?我必须先让他知道吗?第二,如何在我的规则中写入它?
如果直接在 notifications
下的键是 Firebase 身份验证 UID(如您的规则所建议的),您可以通过以下方式限制对用户节点的访问:
{
"rules": {
//".read": "auth != null", // Remove this line
".write": false,
"notifications":{
"$user_id":{
".read": "auth.uid === $user_id", // add this line
".indexOn":"createdAt"
}
}
}
}
另请参阅 securing content-owner only access 上的 Firebase 文档。
我的 nextjs webapp 中有一个实时数据库,我将其用于通知。
我的数据库架构如下:
我仅以管理员身份从服务器端写入数据,但通过以下方式从客户端读取数据:
const fetchNotifications = () => {
const starCountRef = ref(db, `notifications/${user?.id}`);
const q = query(starCountRef, orderByChild('createdAt'), limitToLast(100));
onValue(q, (snapshot) => {
//Handle data
});
};
此刻我有以下规则:
{
"rules": {
".read": "auth != null",
".write": false,
"notifications":{
"$user_id":{".indexOn":"createdAt"}
}
}
}
如您所见,每个经过身份验证的人都可以阅读所有内容。我希望用户只阅读他自己的通知。 ObjectID 是我的 mongoDB.
的引用 例如,如果我有 ID = 1
,我只想访问路径 /notifications/1
的数据,如果我尝试从 /notifications/2
获取数据,那么我什么也得不到(或错误)。
首先,我如何从 firebase 中看到我在本地数据库中使用的 ID?我必须先让他知道吗?第二,如何在我的规则中写入它?
如果直接在 notifications
下的键是 Firebase 身份验证 UID(如您的规则所建议的),您可以通过以下方式限制对用户节点的访问:
{
"rules": {
//".read": "auth != null", // Remove this line
".write": false,
"notifications":{
"$user_id":{
".read": "auth.uid === $user_id", // add this line
".indexOn":"createdAt"
}
}
}
}
另请参阅 securing content-owner only access 上的 Firebase 文档。