我正在尝试使用Firebase Auth在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;
// ...
})
})
},
有人知道我可能做错了什么吗,或者我可以阅读一些文档/教程?
先谢谢了。
答案 0 :(得分:3)
您需要在nuxtServerInit中的服务器上初始化用户。有关示例实现https://github.com/davidroyer/nuxt-ssr-firebase-auth.v2
,请参见此仓库