Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@firebase/testing - How to use auth custom claims in firestore rules tests?

I'm almost good with all my tests for Firestore Rules. But, I still need to test some path for the admin.

The admin in my app is not the Firebase admin, it's an user with privileges set like this in its customClaims :

claims: {admin: true}

How I can mock users customClaims with the npm package @firebase/testing ? I can't figure it out.

Thanks

PS: Below, what I'm currently doing.

export default class TestApplication {

  public static getFirestoreInstance(auth, projectId: string): firebase.firestore.Firestore {
    return firebase
       .initializeTestApp({projectId, auth})
       .firestore();
  }
}


describe(){
    const defaultAuthUser = {uid: "alice", email: "[email protected]", "token": {"admin": true};

    before(done => {
        currentProjectId = TestUtils.getRandomId();
        TestApplication.useFirestoreRules(currentProjectId, rules)
          .then(() => done())
          .catch(done);
    });

    it("I should be able to get another user if I'm an admin", () => {
      return firebase.assertSucceeds(
        TestApplication.getFirestoreInstance(defaultAuthUser, currentProjectId)
          .collection(FirebaseReference.USERS_REF)
          .doc(otherUserId)
          .get()
      );
    }).timeout(5000);
}
like image 539
Spoke44 Avatar asked Dec 03 '18 16:12

Spoke44


1 Answers

Custom claims can be passed as top-level fields within the auth object:

firebase.initializeTestApp({
  projectId: "my-test-project",
  auth: { uid: "alice", my_custom_claim: "foo" }
});

In the example from the question, this line:

const defaultAuthUser = {uid: "alice", email: "[email protected]", "token": {"admin": true};

Should be changed to:

const defaultAuthUser = {uid: "alice", email: "[email protected]", admin: true};
like image 119
Chris Pick Avatar answered Sep 21 '22 05:09

Chris Pick