Created
July 8, 2020 02:48
-
-
Save shadow1349/6e578104db594c0e79e1c934317bd986 to your computer and use it in GitHub Desktop.
Setting Custom User Claims in Firebase
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
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; | |
} | |
} | |
} |
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
// 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