Firestore Security Rules: Allow User To Create Doc Only If New Doc ID is same as User ID

前端 未结 3 603
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 02:02

When users log in for the first time, I need to also call a function that creates a document in my firestore users collection to store their profile data. Using Web SDK.

3条回答
  •  醉梦人生
    2021-01-01 02:49

    The solution i came up with. My tests showed it's not possible to create other user-docs than the own uid and it prevents normal users to change any admin state.

    
    
        rules_version = '2';
        service cloud.firestore {
          match /databases/{database}/documents {
    
            function isAdmin() {
              return get(/databases/$(database)/documents/users/$(request.auth.uid)).isAdmin == true ||
                     get(/databases/$(database)/documents/users/$(request.auth.uid)).data.isAdmin == true;
            }
            function signedIn(){
                return request.auth.uid != null;
            }
    
            match /users/{user} {
    
              // allow updates to own user-doc
              allow read, update, delete: if request.auth.uid == user &&
    
                // allow updates to own user-doc if "isAdmin" field is the same as before the update (in case user was already admin)
                (request.resource.data.isAdmin == resource.data.isAdmin ||
    
                    // or allow updates if "isAdmin" will be set to false
                    request.resource.data.isAdmin == false ||
    
                    // or allow updates if no "isAdmin" field exists after the update
                    !("isAdmin" in getAfter(/databases/$(database)/documents/users/$(request.auth.uid)).data)
                );
    
              // allow creation of user-doc with own uid and no others       
              allow create: if request.auth.uid == user &&
    
                // if no "isAdmin" field is set
                !("isAdmin" in getAfter(/databases/$(database)/documents/users/$(request.auth.uid)).data);
    
              // give full access to admins
              allow read, write: if isAdmin();
            }
          }
        }
    
    

提交回复
热议问题