I am creating a angular web app with firebase as back-end in which only users with a specific email should be able to register. These white list emails should be defined by a Admin in the front-end.
So the challange is to somewhere store these e-Mails with the possibility to further expand them. In this post it is already described for a specific domain but i can't figure out how to add further e-mails via code to the security rules.
You would have to store those emails (when added by an Admin) in Cloud Firestore documents and then check if a document for that email exists in security rules.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /collection/{docID} {
allow read, write: if request.auth != null && exists(/databases/$(database)/documents/emails/$(request.auth.token.email));
}
match /emails/{email} {
allow read, write: if request.auth != null && request.auth.token.admin == true;
}
}
}
I am not sure how the admins are recognized but make sure only admins can write to that emails
collection. In the above example, admins must have a custom claim "admin" to add new emails.
Another option would be to use custom claims for whitelisted users as well. You can use Firebase Cloud Functions which adds whitelisted
claim to users when admin enters their email.
exports.addClaim = functions.https.onCall((data, context) => {
const {uid, token: {admin}} = context.auth;
const {email} = data;
//Check if caller of function is Admin
if (!admin) return {error: 403};
// Add whitelisted claim to user
});
Then you can verify the whitelisted claim in security rules:
allow read, write: if request.auth != null && request.auth.token.whitelisted == true;
Major benefit of using custom claims way is you can use them in security rules of Firestore, RTDB and storage as well. If you store documents for whitelisting users, that can be used in Firestore's rules only.