Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

firebase - Nuxt middleware: How to access vuex store?

I am trying to block user on client-side from editing another user's profile. My URL structure is like so:

/users/edit/XpuBjKFoLSRHJAloNg38Amqn2jQ2

Thus, if user tries to acccess path of another user (ie, http://localhost:3000/users/edit/blahdasd) I need to redirect him to homepage.

I tried to set up an anonymous middle ware like so on my page:

export default {
  middleware({ store, params, redirect }) {
    if (store.state.user.currentUser.uid !== params.uid) {
      return redirect('/')
    }
  },

But, I get page error of:

Cannot read property 'uid' of null

So, how do I correctly access the store here? I have no problem accessing uid from computed property on same page:

    user() {
      return this.$store.state.user.currentUser
    },

Update (more information):

Here is my edit user profile page:

export default {
  middleware({ store, params, redirect }) {
    if (store.state.user.currentUser.uid !== params.uid) {
      // return redirect('/')
      console.log(store.state.user.currentUser.uid)
      console.log(params.uid)
    }
  },
  computed: {
    user() {
      return this.$store.state.user.currentUser
    },

And here is my store/user.js file:

export const state = () => ({
  currentUser: null,
})

export const mutations = {
  SET_AUTH_USER(state, payload) {
    state.currentUser = payload
  }
}

export const actions = {
  async onAuthStateChangedAction({ commit, dispatch }, { authUser }) {
    console.log('auth state changed....')
    try {
      if (authUser && authUser.emailVerified) {
        const {
          uid,
          email,
          emailVerified,
          displayName = '',
          photoURL,
          metadata,
          providerData,
          providerId,
          tenantId
        } = authUser
        commit('SET_AUTH_USER', {
          uid,
          email,
          emailVerified,
          displayName,
          photoURL,
          metadata,
          providerData,
          providerId,
          tenantId
        })
        console.log('fetching profile...')
        await dispatch('getUserProfile', authUser)
      } else {
        console.log('User logged out or not verified')
        return null
      }
    } catch (error) {
      console.error('Error with Auth State observer: ', error)
    }

  },

question from:https://stackoverflow.com/questions/65859448/nuxt-middleware-how-to-access-vuex-store

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...