在 pinia 商店前运行的路由器守卫

问题描述 投票:0回答:1

我正在使用:

[email protected]
[email protected]
[email protected]

我正在使用 Firebase,我使用 pinia Store 进行身份验证。我现在的做法是:

  1. 我有一个名为 storeAuth.ts 的 pinia 商店,代码如下(部分代码):
...

export const useStoreAuth = defineStore('storeAuth', () => {
  const user = ref(null)
  const loading = ref(false)
  const errorMessage = ref("")
  const successMessage = ref("")
  const router = useRouter()

  const init = () => {
    onAuthStateChanged(auth, (firebaseUser) => {  
      if (firebaseUser) {
        user.value = {}
        user.value.id = firebaseUser.uid
        user.value.email = firebaseUser.email
        //console.log('logged in:',user);
      } else {
        user.value = null
        //console.log('logged out');
      }
    });
  }
...
const loginUser = (credentials) => {
    successMessage.value = ""
    errorMessage.value = ""
    loading.value = true

    signInWithEmailAndPassword(auth, credentials.email, credentials.password).then((userCredential) => {
      loading.value = false
      const firebaseUser = userCredential.user;
      router.push('/')
    }).catch((error) => {
      loading.value = false
      //console.log('Error while logging in:',error.message);
      switch (error.code) {
        case 'auth/user-not-found':
          errorMessage.value = "Email and/or password incorrect"
          break;

        case 'auth/wrong-password':
          errorMessage.value = "Email and/or password incorrect"
          break;

        case 'auth/too-many-requests':
          errorMessage.value = "Too many requests. Please reset your password"
          break;

        default:
          errorMessage.value = "There was an error during login"
          break;
      }
    });
  }
...

所以我用我的凭据调用函数 loginUser 然后我登录了。

现在我想使用路由保护,以防止在用户登录时进入登录页面。我试图从 pinia 商店获取用户,因为我将值存储在我的 pinia 商店的用户变量中在初始化函数中。但在 router/index.ts 中输入时始终为空。所以我尝试了以下方法: 我在我的路由器文件中输入以下配置:

let currentUser = null

const getCurrentUser = async () => {
  return new Promise<void>((resolve) => {
    onAuthStateChanged(auth, (user) => {
      currentUser = user
      resolve()
    })
  })
}

const setupNavigationGuards = async () => {
  await getCurrentUser()

  router.beforeEach((to, from, next) => {
    currentUser = auth.currentUser

    if (currentUser && (to.name === 'signin' || to.name === 'register')) {
      next({ name: 'home' })
    } else {
      next()
    }
  })
}

// Call the setupNavigationGuards function
setupNavigationGuards()

但它不起作用,最重要的是我更愿意使用我的 pinia 中的用户而不是 Firebase 中的用户,因为我还想添加一些角色并仅向管理员显示菜单...

firebase vuejs3 vue-router pinia
1个回答
0
投票

要从您的商店获得正确的用户价值,您必须从路由守卫

内部
调用您商店的useStoreAuth功能。

router.beforeEach((to, from, next) => {
  const store = useStoreAuth()

  if (store.user && (to.name === 'signin' || to.name === 'register')) {
    next({ name: 'home' })
  } else {
    next()
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.