【发布时间】:2019-02-26 07:24:45
【问题描述】:
我正在尝试使用 Firebase 身份验证在 Nuxt 中实施身份验证保护,但我一直遇到问题。目前我可以登录,但登录后没有加载正确的页面,登录后用户应该被重定向到“/profile-overview”页面,但这不会发生。当我从“个人资料”页面导航到另一个页面然后返回时,我会自动转到“个人资料概览”页面。所以登录有效,登录后页面的导航/刷新出现问题。另外,当我刷新用户再次注销的页面时,我会除了用户仍然登录吗?
到目前为止我的代码:
页面:
loginGoogle () {
this.$store.dispatch('signInWithGoogle').then(() => {
console.log('reload')
location.reload()
//window.location.reload(true)
}).catch((e) => {
this.title = 'Google login failed'
this.message =
"Something went wrong, please try again later. If this problem keeps happening please contact: jonas@co-house.be " + "Error: " + e.message;
this.dialog = true;
})
},
中间件:
export default function ({ store, redirect, route }) {
console.log('user state' + store.state.user)
console.log('route ' + route.name)
store.state.user != null && route.name == 'profile' ? redirect('/profile-overview') : ''
store.state.user == null && isAdminRoute(route) ? redirect('/profile') : ''
}
function isAdminRoute(route) {
if (route.matched.some(record => record.path == '/profile-overview')) {
return true
}
}
插件:
从'@/services/fireInit.js'导入{ auth}
export default context => {
const { store } = context
return new Promise((resolve, reject) => {
auth.onAuthStateChanged(user => {
if (user) {
return resolve(store.commit('setUser', user))
}
return resolve()
})
})
}
商店(仅登录功能:
signInWithGoogle ({ commit }) {
return new Promise((resolve, reject) => {
auth.signInWithPopup(GoogleProvider).then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
return resolve(store.commit(state.user, result.user))
// ...
}).catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
})
})
},
有没有人知道我可能做错了什么,或者我可以阅读一些文档/教程?
提前致谢。
【问题讨论】:
-
你的插件在ssr上工作吗?我想问题是 auth.onAuthStateChanged 在服务器端不起作用
-
是的,我正在使用 SSR,顺便说一句:插件也在 nuxt.config.js 中定义。是否有另一种方法可以与 SSR 一起使用?或者我应该看看 Firebase 的其他身份验证方式?
-
我的意思是我不知道 firebase 是否会在 ssr 上正常工作,尤其是 onAuthStateChanged。您应该检查该调用是否在 ssr 上执行
标签: firebase vuejs2 firebase-authentication nuxt.js