When editing Firestore rules, I have error: "Invalid variable name: request"
I am a bit confused because the rules works for me as they should. Is it editor error or mine?
The code:
match /users/{userId} {// USER DOCS
function isSignedIn() {return request.auth != null;}
function isValidUser() {return request.auth.uid == userId;}
function isPremium(){
let user=get(/databases/$(database)/documents/users/$(request.auth.uid));
return user.data.role=="premium"
}...
and editor image:
Your request.auth
is scoped to that isSignedIn()
function block so in that scope request is Invalid variable name to make it work you have to declare that function outside of the match /users/{userId}
match rule like shown in here
Answer:
Firestore Security rules using functions need to be defined outside the matchers just like provided in this docs about custom functions. In your case request.auth
is scoped to isSignedIn()
function block so in that scope request is Invalid variable name.
You have to declare functions and use as follows :
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() {
return request.auth.uid != null;
}
function isValidUser(userId) {
return request.auth.uid == userId;
}
function isPremium(){
return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "premium";
}
match /users/{userId} {
allow read, write: if isSignedIn() && isValidUser(userId) && isPremium();
}
}
}
Reference taken from : Access other documents
, Custom functions