簡體   English   中英

Firebase/Nuxt 模塊與 Vuex 使用身份驗證中間件存儲數據:為什么用戶 object 顯示為 null?

[英]Firebase/Nuxt module with Vuex store data with auth middleware: Why is user object shown as null?

我有一個類似的問題: https://github.com/nuxt-community/firebase-module/issues/252

但是,我嘗試了建議的解決方案,但不確定是否正確,因此在此處發布以尋求幫助:

這是我的問題:使用中間件時,如果我嘗試直接訪問頁面(例如輸入 URL 與導航),用戶存儲 object 將返回為null

導航時沒有問題,但問題在於通過在瀏覽器 window 中鍵入 URL 或進行硬刷新直接訪問頁面。 我的用例試圖阻止登錄用戶訪問登錄頁面(或注冊頁面),因此我想我會寫一個像這樣的中間件,但控制台日志顯示用戶是null直接頁面訪問和硬刷新。

middleware/auth

export default function ({ app, store, redirect }) {
  console.log('user?', store.state.user.currentUser)
}

我遵循了Auth SSR 教程,但也許我在某處犯了錯誤。 有人可以幫我正確配置嗎?

nuxt.config.js

export default {
  vue: {
    config: {
      productionTip: false,
      devtools: true
    }
  },
  publicRuntimeConfig: {
    baseURL: process.env.BASE_URL || 'http://localhost:3000'
  },
  privateRuntimeConfig: {},
  head: {
    htmlAttrs: {
      lang: 'en'
    },
    title: 'pixstery',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
  },

  // Global CSS (https://go.nuxtjs.dev/config-css)
  css: [],

  // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
  plugins: [
    // {
    //   src: '~/plugins/vuex-persist',
    //   mode: 'client'
    // }
  ],

  // Auto import components (https://go.nuxtjs.dev/config-components)
  components: true,

  // Modules for dev and build (recommended) (https://go.nuxtjs.dev/config-modules)
  buildModules: [
    // https://go.nuxtjs.dev/eslint
    '@nuxtjs/eslint-module',
    // https://go.nuxtjs.dev/tailwindcss
    '@nuxtjs/tailwindcss',
    '@nuxtjs/html-validator'
  ],

  // Modules (https://go.nuxtjs.dev/config-modules)
  modules: ['@nuxtjs/pwa', '@nuxtjs/firebase', '@nuxt/content'],
  firebase: {
    config: {
      apiKey: 'AIzaSyD4ge8g6oe0xp6vQ1y85AbvI8PXcDKzoKk',
      authDomain: 'xxx.firebaseapp.com',
      databaseURL: '<databaseURL>',
      projectId: 'xxx',
      storageBucket: 'xxx.appspot.com',
      messagingSenderId: '471446831599',
      appId: '1:471446831599:web:16ec77402cbb336f67b61a',
      measurementId: 'G-XFVH7QFG4L' // optional
    },
    services: {
      auth: {
        persistence: 'local', // default
        initialize: {
          onAuthStateChangedAction: 'user/onAuthStateChangedAction',
          subscribeManually: false
        },
        ssr: true
        // emulatorPort: 9099,
        // emulatorHost: 'http://localhost'
      },
      firestore: {
        chunkName:
          process.env.NODE_ENV !== 'production' ? 'firebase-auth' : '[id]', // default
        enablePersistence: true
        // emulatorPort: 8080,
        // emulatorHost: 'localhost'
      },
      functions: {
        location: 'us-central1'
        // emulatorPort: 12345,
        // emulatorHost: 'http://10.10.10.3'
      },
      storage: true
    }
  },
  pwa: {
    // disable the modules you don't need
    meta: false,
    icon: false,
    // if you omit a module key form configuration sensible defaults will be applied
    // manifest: false,

    workbox: {
      importScripts: [
        // ...
        '/firebase-auth-sw.js'
      ],
      // by default the workbox module will not install the service worker in dev environment to avoid conflicts with HMR
      // only set this true for testing and remember to always clear your browser cache in development
      // dev: process.env.NODE_ENV === 'development'
      dev: true
    }
  },

  // Content module configuration (https://go.nuxtjs.dev/config-content)
  content: {},

  // Build Configuration (https://go.nuxtjs.dev/config-build)
  build: {},
  router: {
    middleware: ['auth']
  }
}

store/user

  async nuxtServerInit({ dispatch, commit }, { res }) {
    if (res && res.locals && res.locals.user) {
      const { allClaims: claims, idToken: token, ...authUser } = res.locals.user

      await dispatch('onAuthStateChangedAction', {
        authUser,
        claims,
        token
      })
    }
  },
  async onAuthStateChangedAction({ commit, dispatch }, { authUser, claims }) {
    console.log('auth state changed....')
    console.log('authUser: ', authUser)
    console.log('claims: ', claims)

    try {
      if (!authUser) {
        await dispatch('logOutUser')
        return
      } else if (authUser && authUser.emailVerified) {
        const {
          uid,
          email,
          emailVerified,
          displayName = '',
          photoURL,
          metadata,
          providerData,
          providerId,
          tenantId
        } = authUser
        commit('SET_AUTH_USER', {
          uid,
          email,
          emailVerified,
          displayName,
          photoURL, // results in photoURL being undefined for server auth
          metadata,
          providerData,
          providerId,
          tenantId,
          isAdmin: claims.custom_claim // use custom claims to control access (see https://firebase.google.com/docs/auth/admin/custom-claims)
        })
        console.log('fetching profile...')
        await dispatch('getUserProfile', authUser)
      } else {
        console.log('User logged out or not verified')
        return
      }
    } catch (error) {
      console.error('Error with Auth State observer: ', error)
    }
  },

因此,使用上面的代碼,我的login頁面(當用戶已經登錄時)的硬刷新(或通過瀏覽器 URL 直接導航)在控制台中顯示了這一點(注意user?, null

在此處輸入圖像描述

感謝您的任何幫助!

問題的根源可能有兩個:

  1. 嘗試將您的nuxtServerInit操作移動到store/index.js

目前,您在store/user.js中有nuxtServerInit ,這意味着實際操作的命名空間為user/nuxtServerInit 因此它不被調用。

  1. 你提到硬重裝。 在硬重載期間,Service Worker 被繞過,因此它不會將身份驗證令牌傳遞給服務器端。 這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM