[英]How to get currentUser on first load in firebase-auth without requesting
I'm using firebase authentication, and my navbar is depend on if user is logged in or not.我正在使用 firebase 身份验证,我的导航栏取决于用户是否登录。 When i load the website, if user not logged out before, he should still stay as logged in.But, Firebase onAuthStateChanged listener returns user after 100-300ms, so my navbar can't decide if user is logged in or not.So, navbar shows login and signup button for 300ms, then firebase returns user, and navbar shows dashboard and logout button.
当我加载网站时,如果用户之前没有注销,他应该仍然保持登录状态。但是,Firebase onAuthStateChanged 监听器在 100-300 毫秒后返回用户,所以我的导航栏无法确定用户是否登录。所以,导航栏显示登录和注册按钮 300 毫秒,然后 firebase 返回用户,导航栏显示仪表板和注销按钮。
I'm using vue, I've tried saving UID and username on localstorage, but i'm concerning about security.我正在使用 vue,我尝试在本地存储上保存 UID 和用户名,但我担心安全性。 what if someone manually changed localstorage data?
如果有人手动更改本地存储数据怎么办? Also, user may logged out, but stay logged in my manually setting localStorage.setItem('user', ....)
此外,用户可以注销,但保持登录状态,我手动设置 localStorage.setItem('user', ....)
Navbar.vue导航栏.vue
<div v-if="user.uid" class="flex row space-b">
// userpic, photo, logout button
</div>
<div v-else>
// login and signup button
</div>
vuex Vuex
state: {
user: {
uid: null,
photoURL: null,
username: null,
},
},
I tried not to mount Vue instance until onAuthStateChanged listener returns something, but this can't be a good solution, hence i'm rendering website nearly 300ms late.我尝试在 onAuthStateChanged 侦听器返回某些内容之前不挂载 Vue 实例,但这不是一个好的解决方案,因此我将网站渲染延迟了近 300 毫秒。
Anyway, i saved it in cookie. 无论如何,我将其保存在cookie中。 when website loads, if cookie is exists i render navbar as if user logged in, and then double check after firebase listener returns
当网站加载时,如果存在cookie,则呈现navbar就像用户登录一样,然后在firebase侦听器返回后再次检查
This is caused because beforeEach is getting executed before firebase has fully finished initialization.这是因为 beforeEach 在 firebase 完全完成初始化之前被执行。
You can use onAuthStateChanged observer to make sure the vue app is initialized only after the firebase is fully initialized.您可以使用 onAuthStateChanged 观察者确保仅在 firebase 完全初始化后才初始化 vue 应用程序。
One way to fix it is to wrap the vue initialization code in main.js(new Vue(... )) with onAuthStateChanged like this:解决它的一种方法是将 vue 初始化代码包装在 main.js(new Vue(... )) 中,使用 onAuthStateChanged 如下所示:
let app;
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
console.log("user", user);
if (!app) {
new Vue({
router,
vuetify: new Vuetify(options.Vuetify),
render: (h) => h(App),
}).$mount("#app");
}
});
for version 7 firebase you can check this repo file https://github.com/ErikCH/FirebaseTokenFrontend/blob/master/src/main.js对于版本 7 firebase,您可以查看此 repo 文件https://github.com/ErikCH/FirebaseTokenFrontend/blob/master/src/main.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.