Reputation: 7460
My firebase app has two different roles: user
and admin
. I assign these during the creation, which is done as follows:
const admin = require('firebase-admin')
...
const user = await admin.auth().createUser({
email,
emailVerified: true,
password,
displayName: name,
disabled: false
})
await admin.auth().setCustomUserClaims(user.uid, { role: 'user' })
For creating the admin we obviously do the same, but the last line becomes as follows:
await admin.auth().setCustomUserClaims(user.uid, { role: 'admin' })
These separate roles are use in the firebase rules to keep users from accessing certain collections as well as some cloud functions to prevent them from doing certain operations.
What I would like to do is on my client app to limit access to certain sections by checking the user role.
As it stands, when I authenticate I do not have access to the user role, so I don't know how to limit their access based on their role. Here is my authentication code:
// authenticating a user
const handle = firebase.auth().onAuthStateChanged(user => {
console.log('Authenticated user', user)
// do stuff
})
The issue here is that at this point the user object given to me by onAuthStateChanged
doesn't have the role.
From the providerData
attribute all I have is the following:
displayName
email
phoneNumber
photoURL
providerId
uid
The question is how can I access the user role on the client app to be able to block certain types of users from accessing restricted parts of the client app?
Upvotes: 4
Views: 2605
Reputation: 2927
Try the following snippet:
firebase.auth().currentUser.getIdTokenResult()
.then((idTokenResult) => {
// Confirm the user is an Admin.
if (!!idTokenResult.claims.admin) {
// Show admin UI.
showAdminUI();
} else {
// Show regular user UI.
showRegularUI();
}
})
.catch((error) => {
console.log(error);
});
Upvotes: 3