Home > Net >  How to add Auth Custom claims
How to add Auth Custom claims

Time:12-18

Firebase function

I am trying to set my user role to admin using a callable function:

export const addAdminRole = functions.https.onCall(async (data, context) => {
  admin.auth().setCustomUserClaims(data.uid, {
    admin: true,
    seller: false,
  });
});

Cient

And here is how I am calling the function on the client:

 const register = (email: string, password: string) => {
    createUserWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        // Signed in
        const user = userCredential.user;
        const addAdminRole = httpsCallable(functions, "addAdminRole");
        addAdminRole({ email: user.email, uid: user.uid })
          .then((result) => {
            console.log(result);
          })
          .catch((error) => console.log(error));
        history.push(`/home/${user.uid}`);
      })

      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // ..
      });
  };

The user is created but, my Admin role is not added

CodePudding user response:

The problem may come from the fact that you don't correctly handle the promise returned by the setCustomUserClaims() method in your Cloud Function and therefore the Cloud Function platform may clean up you CF before it reaches its terminating state. Correctly managing the life-cycle of your Cloud Function is key, as explained here in the doc.

The following should solve the problem:

export const addAdminRole = functions.https.onCall(async (data, context) => {
    try {
        await admin.auth().setCustomUserClaims(data.uid, {
            admin: true,
            seller: false,
          });
          
          return {result: "Success"}
    } catch (error) {
        // See https://firebase.google.com/docs/functions/callable#handle_errors
    }
  });

In addition, you can refactor your front-end code as follows to correctly chain the promises:

const register = (email: string, password: string) => {
    createUserWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        // Signed in
        const user = userCredential.user;
        const addAdminRole = httpsCallable(functions, "addAdminRole");
        return addAdminRole({ email: user.email, uid: user.uid });        
      })
      .then((result) => {
        console.log(result);
        history.push(`/home/${user.uid}`);
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // ..
      });
  };
  • Related