【发布时间】:2018-10-17 21:30:06
【问题描述】:
我必须在这里遗漏一些非常基本的东西......但是每当我调用我的 Cloud Firestore 数据库并尝试制定任何类型的安全规则时,它们总是会失败。
做类似的事情
match /users/{userId} {
allow create, read, update: if true;
}
有效,但它显然违背了这一点。但是,如果我进行任何形式的额外审查,例如所有文档中的首选示例,例如
match /users/{userId} {
allow create, read, update: if request.auth.uid != null;
}
每次都失败。我在如何将客户端代码连接在一起时是否遗漏了一些明显的东西?
这是我的客户端代码,它让用户登录,然后调用数据库来获取用户。 (请注意,在我的数据库中,用户的密钥是通过电子邮件,而不是通过 uid)
// this is a snippet from the code where I log the user in
firebase.auth().signInWithEmailAndPassword(email, FIREBASE_USER_PASSWORD)
.then(user => {
// the user comes back successfully logged in,
// I grab its uid and add it to a preparedUser object that I've been building,
// then pass this user to my getFirestoreUserObject function
preparedUser.uid = user.uid;
getFirestoreUserObject({dispatch, user: preparedUser, navigate});
})
// then the getFirestoreUserObject function:
// note that all the code below works fine when there are no security rules in place
const getFirestoreUserObject = ({dispatch, user, navigate}) => {
const {name, email, imageUrl} = user;
// if I ask for currentUser here, I get back my logged in user
const currentUser = firebase.auth().currentUser;
// email is defined correctly here as the user's email
firebase.firestore().collection('users').doc(`${email}`)
.get() // the request fails here due to insufficient permissions
.then(doc => {
if (doc.exists) {
const currentUser = doc.data();
getUserFavorites({dispatch, currentUser, navigate});
} else {
createUserInFirestore({dispatch, user, navigate});
}
})
};
我有什么明显的遗漏吗?如果我通过firebase.auth() 登录用户,然后在调用firebase.firestore() 之后立即登录,那不应该有经过身份验证的用户的上下文吗?如果没有,我如何将其传递给 firestore 调用?
谢谢!
【问题讨论】:
-
我认为这里的问题是“紧接着”。就像使用 firebase 登录的一切都是异步的一样,所以它需要(很短)一段时间才能完成。
-
谢谢,@AndréKool。在成功的 auth
.then()块之后进行 db 调用的事实不应该意味着 firebase 方面的工作已经完成吗?另外,在我上面的 sn-p 中,当我调用currentUser时,在我接触到数据库之前,我成功地从firebase.auth()取回了 currentUser。
标签: firebase firebase-authentication google-cloud-firestore firebase-security