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.
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();
}
}
