Skip to content

Instantly share code, notes, and snippets.

@deltaepsilon
Last active July 23, 2018 12:57
Show Gist options
  • Save deltaepsilon/689cbf5eb706c027df5ea02094e07b85 to your computer and use it in GitHub Desktop.
Save deltaepsilon/689cbf5eb706c027df5ea02094e07b85 to your computer and use it in GitHub Desktop.
Cloud Function to manage Custom Claims
const getCustomClaimsByEmail = require('../utilities/get-custom-claims-by-email');
const setCustomClaims = require('../utilities/set-custom-claims');
module.exports = ({ admin, environment }) => user => {
const db = admin.firestore();
const usersCollection = db.collection(environment.schema.users);
const customClaimsRef = admin.database().ref(environment.schema.customClaims);
const auth = admin.auth();
const email = extractEmailFromUser(user);
return Promise.resolve()
.then(getCustomClaimsByEmail(customClaimsRef, email))
.then(setCustomClaims(auth, user.uid))
.then(claims => {
const update = mapUserUpdate(claims, user);
return usersCollection.doc(user.uid).set(update, { merge: true });
});
};
function mapUserUpdate(claims, user) {
const email = extractEmailFromUser(user);
return {
claims,
email,
emailVerified: user.emailVerified,
lastSignInTime: user.metadata.lastSignInTime,
creationTime: user.metadata.creationTime,
providerData: user.providerData,
};
}
function extractEmailFromUser(user) {
return user.email || user.providerData.find(({ email }) => email).email;
}
const BAD_KEYS_REGEXP = /[\.|\/|$|#|\[|\]]/g;
module.exports = ({ admin, environment }) => ({ email, claims }) => {
const emailSlug = email.replace(BAD_KEYS_REGEXP, '|');
return admin
.database()
.ref(environment.schema.customClaims)
.child(emailSlug)
.set({ email, claims });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment