4

Is there a way to create a custom claim without having to go through cloud functions?

I really only need to set it up for a few accounts, and my current plan is spark. I can't upgrade just yet. But I need to test this feature to implement role based authentication.

Thank you and please be as detailed as possible as I'm new to firebase cli.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
user135019
  • 85
  • 5

1 Answers1

6

Yes, if you just need to setup a few users then you run a script locally to add the claims. Just follow the steps:

1. Create a NodeJS project

npm init -y

//Add Firebase Admin
npm install firebase-admin

2. Write this code in a JS file (addClaims.js):

const admin = require("firebase-admin")

admin.initializeApp({
  credential: admin.credential.cert("./serviceAccountKey.json"),
  databaseURL: "https://<project-id>.firebaseio.com/"
})

const uid = "user_uid"

return admin
  .auth()
  .setCustomUserClaims(uid, { admin: true })
  .then(() => {
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.
    console.log(`Admin claim added to ${uid}`)
  });

3. Run the script

node addClaims.js

You can also write a function that takes an array of UIDs as parameter and adds claims to all of them using a loop. To read more about service account and initializing the Admin SDK, check this documentation.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • 1
    Sir thank you so much. I've been hitting my head on the table for hours. Didn't realize you can just pass parameters to `initializeApp` and run the app locally with node. – user135019 Jul 10 '21 at 13:05
  • 1
    @user135019 glad to hear that. You can try [Firebase emulators](https://firebase.google.com/docs/emulator-suite) for local testing. – Dharmaraj Jul 10 '21 at 13:06