I have a news application connected with Firebase and I add the news manually in Firestore only, inside 5 Collection, I am not good at using Firebase, I use the test mode and now I need your help in changing it, the application is for news, meaning no one can add in it only read the data from Everyone without even logging in, I get many security messages from Google, please write me the code here because I browsed a lot of questions here and I didn't understand anything and it seems that I need a course on Firebase security.
I use a pay-per-use plan, and I'm afraid of high bills. Please help me with a strong security that protects me from fake reading or even writing.
CodePudding user response:
It is hard to answer without an understanding of your firestore collection names but here is a general solution.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// in this example, only admins can write or delete, but anyone can read.
match /news/{docId}{
allow read;
allow write, delete: if isAdmin(request);
}
// This is an example for a users collection, where the doc ID is the
// users authentication Id
// Note the userId=** -> this will apply rules to all subcollections
match /users/{userId=**}{
allow read: if isAuthenticated(request); // logged in users can read
// Only admins or the user with a matching doc Id can write.
allow write: if isAdmin(request) || isOwner(userId);
allow delete: if isAdmin(request); // only admins can delete
}
function isOwner(userID){
return request.auth.uid == userID;
}
function isAuthenticated(request){
return request.auth != null;
}
// this requires you to have set up custom claims
function isAdmin(request) {
return request.auth.token.admin
}
}
}
To learn more about protecting your collections with role based authentication, take a look at Custom Claims