0

im trying to find a way how to add to user Admin role via custom claims. I tried to do it with user creation cloud function, and onCall function, I dont know if claims are assigned, or not, or how to check where is code failing.

Here is my code: 2 cloud functions, I have tried to give admin role after acc creation and then manually (this function is blocked when called from button click by CORS, no idea what to do)

Any help appreciated

Cloud functions:

export const assignAdminRoleOnUserCreation = functions.auth
    .user()
    .onCreate(async (user) => {
      try {
        if (user.email === "[email protected]") {

          await admin.auth().setCustomUserClaims(user.uid, { admin: true });

          console.log(`Admin role assigned to user ${user.email} (${user.uid}).`);
        } else {
          console.log(`No admin role assigned to user ${user.email}.`);
        }
      } catch (error) {
        console.error(`Error assigning admin role to user ${user.email}:`, error);
      }
    });

  export const manuallyAssignAdmin = onCall(async (request) => {
    const targetEmail = "[email protected]"
  
    try {
      const userRecord = await getAuth().getUserByEmail(targetEmail)
  
      await getAuth().setCustomUserClaims(userRecord.uid, { admin: true })
  
      return { message: `Admin role assigned to ${targetEmail}` }
    } catch (error) {
      console.error("Error assigning admin role:", error)
      throw new Error("Failed to assign admin role")
    }
  })

how i call onCall function at front end:

async function assignAdminManually() {
const assignAdmin = httpsCallable(functions, 'manuallyAssignAdmin')

try {
  const result = await assignAdmin()
  console.log(result.data.message)
  alert('Admin role assigned successfully!')
} catch (error) {
  console.error('Error assigning admin role:', error)
  alert('Failed to assign admin role.')
}

}

How I try to check admin role:

  const isAdmin = async () => {
if (cachedIsAdmin !== null) {
  return cachedIsAdmin; 
}

const auth = getAuth();
const user = auth.currentUser;
console.log(auth)
if (user) {
  try {
    const idTokenResult = await user.getIdTokenResult();

    if (idTokenResult.claims.admin) {
      cachedIsAdmin = true;
    } else {
      cachedIsAdmin = false;
    }
  } catch (error) {
    console.error("Error getting ID token result:", error);
    cachedIsAdmin = false;
  }
} else {
  cachedIsAdmin = false;
}

return cachedIsAdmin;

};

1 Answer 1

0
const auth = getAuth();
const user = auth.currentUser;
console.log(auth)
if (user) {

omg it was working whole time... problem was at this, where auth were already loaded but user not, so function returned false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.