Skip to content

Instantly share code, notes, and snippets.

@DennisAlund
Created April 19, 2024 06:05
Show Gist options
  • Save DennisAlund/d190a857a5eab0a96f06161bfeaa8eaf to your computer and use it in GitHub Desktop.
Save DennisAlund/d190a857a5eab0a96f06161bfeaa8eaf to your computer and use it in GitHub Desktop.
export const updateUserRoles = functions.firestore
.document('/users/{userId}')
.onUpdate(async (change, context) => {
const beforeData = change.before.data();
const afterData = change.after.data();
// Check if roles have changed
if (JSON.stringify(beforeData.roles) === JSON.stringify(afterData.roles)) {
functions.logger.info('Roles are unchanged. Do nothing.');
return null;
}
const uid = context.params.userId;
const newRoles = afterData.roles;
// Get the current auth user and merge the new roles into the claims
const user = await admin.auth().getUser(uid);
const newClaims = { ...user.customClaims, roles: newRoles };
return admin.auth().setCustomUserClaims(uid, newClaims);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment