Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
What rule do I need to allow access to users data in Firestore?

I'm learning Firestore and have built an angular app. I'm using Firebase authentication and having trouble figuring out the rules to use to allow a user access to their data. So for example a products collection which each product has a userId which is actually their email address.

Example: enter image description here

The current rule I have is as follows and is not working (i've tried everything I can figure based on docs, stackoverflow, etc.):

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userEmail} {
        allow read, write: if request.auth != null;
    }
    match /products/{userId}{
        allow read, write: if request.auth.uid.userEmail == userId
    }  
  }
}

The only thing i've done that does work (i.e. I get all products back) is if I do a match/{document=**) which opens it up to anyone which is NOT what I want. :)

Any ideas?

Edit: Incase someone is wondering about the angular code. Again, if I set the rule to allow anything I DO get data back. If I restrict it, so far I get nothing. So, I know the code works (getAll) thus it must be the rules are not right.

Edit: I updated the code to write the users email to the console just before requesting all products data from the store. It successfully output the user's email.

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { AngularFireAuth } from '@angular/fire/auth';
import { Product } from '../models/product.model';

@Injectable({
  providedIn: 'root'
})
export class ProductsService {

  private dbPath = '/products';

  productsRef: AngularFirestoreCollection<Product>;

  constructor(public afAuth: AngularFireAuth, private db: AngularFirestore) {
    this.productsRef = db.collection(this.dbPath);
  }

  getAll(): AngularFirestoreCollection<Product>{
    this.afAuth.authState.subscribe(user => {
      console.log('Dashboard: user', user);

      if (user) {
          let emailLower = user.email.toLowerCase();
          console.log("Email: " + emailLower);
      }
  });

    return this.productsRef;
  }

  create(product: Product): any {
    return this.productsRef.add(product);
  }

  update(id: string, data: any): Promise<void>{
    return this.productsRef.doc(id).update(data);
  }

  delete(id: string): Promise<void> {
    return this.productsRef.doc(id).delete();
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think there is some issue with the security rules built. You can refer to the Firestore security rules to learn more about writing rules and for testing your rules you can refer documentation where mentioned :

Cloud Firestore provides a rules simulator that you can use to test your ruleset. You can access the simulator from the Rules tab in the Cloud Firestore section of the Firebase console. The rules simulator lets you simulate authenticated and unauthenticated reads, writes, and deletes.

a) From the screenshot of the Firestore database products collection, the document ID appears to be an auto-generated alphanumeric sequence. So below match rules are going to match document ID (auto-generated) in {userEmail} & {userId} variables instead of the user email or user ID as the variable name suggests.

 match /users/{userEmail}
 match /products/{userId}

You may of course create the Document IDs to have email addresses rather than auto generated sequences in which case above match conditions might work as expected.

b) The usage of request.auth.uid.userEmail is incorrect. The correct way to refer to email from a user's request authentication state is "request.auth.token.email". You can read about the request.auth & resource variable references on Firestore public docs -documentation1 & documentation2 to use correct syntax.

c) Below are some corrections made to the security rules. This should work.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userDocId} {
        allow read, write: if request.auth != null;
    }
    match /products/{productDocId}{
        allow read, write: if request.auth.token.email == resource.data.userId
    }
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I believe the correct syntax is

        allow read, write: if request.auth.token.email == userId

Please refer to the documentation here for more details.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda