我的 Quasar 应用程序在浏览器刷新和 Firebase 身份验证方面遇到问题。
用户登录然后点击浏览器刷新后,firebase.auth().currentUser
返回 null(因为它是异步执行的)。这意味着当 beforeEach
被执行 currentUser
为 null 并提示用户登录页面。但是我看到当回调到 onAuthStateChanged
正在被调用,用户正在正确设置。
在 Quasar 应用程序中,onAuthStateChanged
是否有任何模式?可以在导航过程中使用,以便重用现有的用户 session ?
// Vue-router => index.js
firebase.auth().onAuthStateChanged(user => {
console.log('onAuthStateChanged Invoked => ' + user);
});
router.beforeEach((to, from, next) => {
let currentUser = firebase.auth().currentUser;
let requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !currentUser) {
next('signin');
} else {
if (requiresAuth && currentUser.emailVerified === false) {
next('signin');
} else {
next();
}
}
});
最佳答案
我直接在我的路由器保护中使用 firebase.auth().onAuthStateChanged 函数,如下所示:
我检查路由是否需要经过身份验证的用户(可选),然后加载当前登录的用户并将其提交到我的 Vuex 存储中。
这样,在路由保护检查访问之前,当前登录的用户就处于我的 Vuex 状态。否则,特别是在页面重新加载后,用户尚未加载,并且守卫重定向到登录页面......
...
Router.beforeEach((to, from, next) => {
let requiresAuth = to.matched.some(record => record.meta.requiresAuth)
// If route requires auth --> load auth state first from firebase
if (requiresAuth) {
firebase.auth().onAuthStateChanged(user => {
store.commit("user/SET_USER", user);
let currentUser = firebase.auth().currentUser
store.commit("user/SET_USER_FULL", currentUser);
user.getIdToken().then(token => {
store.commit("user/SET_TOKEN", token)
});
if (!user) next('login')
else next();
});
} else next()
})
export default Router
我使用类星体。这段代码在我的路由器/index.js 中。不要忘记像这样导入您的商店: import store from '../store'
关于javascript - Firebase onAuthStateChanged 和 Navigation Guards 的模式 - Quasar 应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50323975/