Created
April 19, 2024 06:05
-
-
Save DennisAlund/d190a857a5eab0a96f06161bfeaa8eaf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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