简体   繁体   中英

How to set rules to users in firebase?

I want to create new rules for my client - one client can create one document in collection.


         match /Users/{userId} {
      allow update, delete: if request.resource.data.uid == uid;
      allow create: if 
       request.data.uid != request.resource.data.uid;

if request uid == request.resource.data.uid; he cannot.

If you want each user to only be able to create a single document, that is easiest if you use the user's UID as the document ID. In JavaScript that'd be something like this:

import { doc, setDoc } from "firebase/firestore"; 
import { getAuth } from "firebase/auth";

const user = getAuth().currentUser;

await setDoc(doc(db, "Users", user.uid), {
  displayName: user.displayName,
});

You can then enforce this content-owner only access in security rules with:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow only authenticated content owners access
    match /Users/{userId}/{documents=**} {
      allow write: if request.auth != null && request.auth.uid == userId
    }
  }
}

The main difference with your approach is that we don't check the data of the document, but instead check the document ID (which we set to the UID in our code) to the UID on the request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM