设置Firestore用户安全规则

时间:2019-04-25 19:32:15

标签: firebase google-cloud-firestore firebase-security-rules

我是Firestore的新手,我正在尝试设置简单的安全规则,以便只有登录的用户才能创建新的数据库条目,并且用户只能读写自己的条目。

service cloud.firestore {
  match /databases/{database}/documents {
    match /Users/{userID} {

      // Can only create a new entry if signed in with a uid. 
      allow create: if request.auth.uid != null;

      // Can only update an entry if signed in with uid and changing own information (saved under uid)
      allow update: if request.auth.uid != null &&
        userID == request.auth.uid;

      // Can only read (get/list) an entry if signed in with uid and reading own information (saved under uid)
      allow read: if request.auth.uid != null &&
        resource.data.userID == request.auth.uid;
}

} }

创建新条目的情况很好,但是我想知道这是否足够安全。

对于更新和阅读,我还想检查用户是否正在更新/阅读他们自己的条目。文档名称是Firebase中的uid(换句话说就是UserID),因此只需检查一下request.auth.uid是否相同即可解决问题,但是我编写它的方式有些问题。呼叫被阻止,当我在模拟器中运行该呼叫时,出现错误:缺少权限或权限不足。查阅文档和此tutorial video后,我不知道。

1 个答案:

答案 0 :(得分:1)

以下情况足以满足您的情况:

// True if the user is signed in or the requested data is 'public'
function signedInOrPublic() {
  return request.auth.uid != null || resource.data.visibility == 'public';
}

// Make sure the uid of the requesting user matches name of the user
// document. The wildcard expression {userId} makes the userId variable
// available in rules.
match /users/{userId} {
  allow read, update, delete: if request.auth.uid == userId;
  allow create: if signedInOrPublic();
}