Skip to content

Instantly share code, notes, and snippets.

@shadow1349
Created July 8, 2020 02:48
Show Gist options
  • Save shadow1349/6e578104db594c0e79e1c934317bd986 to your computer and use it in GitHub Desktop.
Save shadow1349/6e578104db594c0e79e1c934317bd986 to your computer and use it in GitHub Desktop.
Setting Custom User Claims in Firebase
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /AdminStuff/{StuffId} {
allow read, write: if isAdmin();
}
function isAdmin() {
return request.auth.token['isAdmin'] == true;
}
}
}
// Firebase Functions
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
export const UserUpdated = functions.firestore.document('Users/{UserId}').onUpdate(async (update, context) => {
const userAfter = update.after.data();
// Let's assume the user document has a field called isAdmin that is a boolean
if(userAfter.isAdmin === true) {
await admin.auth().setCustomUserClaims(context.params.UserId, {admin: true});
} else {
await admin.auth().setCustomUserClaims(context.params.UserId, {admin: false});
}
// do whatever else
return Promise.resolve(null);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment