nuxt-community / firebase-module

🔥 Easily integrate Firebase into your Nuxt project. 🔥
https://firebase.nuxtjs.org
MIT License
641 stars 99 forks source link

Secure page with custom claims on Auth? With browser refresh working. #504

Closed sparkonium closed 3 years ago

sparkonium commented 3 years ago

What would be the recommended way to secure a page with a custom claim?

So far it looks like we must read it from nuxtServerInit and commit a mutation with ctx.res.locals.user.allClaims and have the middleware use store.getters to get/check the mutation?

I tried another way where nuxtServerInit calls a dispatch to onAuthStateChanged which checks authUser.getIdTokenResult() to add custom claims to authUser which then commits the mutation but it did not work.

Accessing store.state.authUser did not work on a page refresh (no problems with router)

It is running on a Firebase Cloud Function with nuxt-start and the refresh is to allow for the user experience to not get logged out on browser refresh.

tibs245 commented 3 years ago

Only on emulators or same on production ?

Because with emulators : This is a bug : https://github.com/nuxt-community/firebase-module/issues/465

But on production. The simple connection is stoked by Firestore natively.

  SET_AUTH_USER(state, { authUser, claims }) {
    state.authUser = {
      uid: authUser.uid,
      email: authUser.email,
    }

    state.userClaims = claims
  }

  onAuthStateChanged({ commit, dispatch }, { authUser, claims }) {
    if (!authUser) {
      commit('RESET_STORE')
      return
    }
    commit('SET_AUTH_USER', { authUser, claims })

With this code, personally, I can access to auth user with my middleware for test if user is connected And I can access to claims to verify user right with : state: store.state.auth.fireAuth.userClaims

If you edit user claims when is connected : You need execute this.$fire.auth.currentUser.getIdToken(true) for actualize claims

For that you can create a action on fireAuth store

sparkonium commented 3 years ago

It was in production, now I tested it in Emulator, works great. I was working on the next steps and just read your last part.

If you edit user claims when is connected : You need execute this.$fire.auth.currentUser.getIdToken(true) for actualize claims

It would actualize the claim, do you use another Action to update the authUser state or you are able to reuse onAuthStateChanged?

Opened another issue/question: #521

lupas commented 3 years ago

Closing since original issue has been resolved.