如何定义只有登录用户才能读取和写入所有 collections 和子集合的安全规则?
How do I define the security rules where only logged in user can read and write all of the collections and subcollection?
我有 collections 个 category
、products
和 orders
。然后在 products
下我有一个 history
的子集。同样在我的应用程序中,只有一种类型的用户是我直接在 Firebase 控制台中添加的。我如何定义只有登录用户才能读写这些 collections 和 subcollections 的安全规则?
对于登录,我使用的是 Firebase 身份验证:
const handleSubmit = async (e) => {
e.preventDefault();
const auth = getAuth();
console.log(email, password, "1");
setIsLoading(true);
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
setIsLoading(false);
navigate("/Homepage");
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
setIsLoading(false);
alert(errorMessage);
});
};
How can I define the security rules where only logged in user can read and write on these collections and subcollections?
以下规则使用了通配符,应该允许任何经过身份验证的用户读取和写入 Firestore 中的任何文档:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
如果你想在某个时候锁定它,因为你引入了一个并非所有用户都应该有权访问的集合,你可以将其明确化:
service cloud.firestore {
match /databases/{database}/documents {
match /category/{id} {
allow read, write: if request.auth != null;
}
match /products/{id} {
allow read, write: if request.auth != null;
}
match /logs/{id} {
allow read, write: if false;
}
}
}
有关更多信息,start here in the docs并在部署规则之前使用 Firebase 控制台中的 Playground 测试您的规则。
我有 collections 个 category
、products
和 orders
。然后在 products
下我有一个 history
的子集。同样在我的应用程序中,只有一种类型的用户是我直接在 Firebase 控制台中添加的。我如何定义只有登录用户才能读写这些 collections 和 subcollections 的安全规则?
对于登录,我使用的是 Firebase 身份验证:
const handleSubmit = async (e) => {
e.preventDefault();
const auth = getAuth();
console.log(email, password, "1");
setIsLoading(true);
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
setIsLoading(false);
navigate("/Homepage");
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
setIsLoading(false);
alert(errorMessage);
});
};
How can I define the security rules where only logged in user can read and write on these collections and subcollections?
以下规则使用了通配符,应该允许任何经过身份验证的用户读取和写入 Firestore 中的任何文档:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
如果你想在某个时候锁定它,因为你引入了一个并非所有用户都应该有权访问的集合,你可以将其明确化:
service cloud.firestore {
match /databases/{database}/documents {
match /category/{id} {
allow read, write: if request.auth != null;
}
match /products/{id} {
allow read, write: if request.auth != null;
}
match /logs/{id} {
allow read, write: if false;
}
}
}
有关更多信息,start here in the docs并在部署规则之前使用 Firebase 控制台中的 Playground 测试您的规则。