Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for firebase's auth user's role when or after logging in

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?

like image 653
theJuls Avatar asked Oct 17 '25 17:10

theJuls


1 Answers

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);
  });

Source:

Firebase Auth

like image 157
Peter Avatar answered Oct 20 '25 07:10

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!