首页 > 解决方案 > Firebase - 在 localStorage 对象有效时保持用户登录

问题描述

我有一个使用 Ionic、Angular2 和 Firebase 构建的应用程序。

我目前正在做的是,当用户登录或注册时,他们的auth.currentUser信息将保存在localStorage. 我的代码当前假设如果用户user在 set 中设置了该用户也已登录的变量localStorage。但是,我刚刚意识到事实并非如此。

我的localStorage变量user如下所示:

在此处输入图像描述

我得到它是这样的:

ngOnInit() {
  Promise.all([ //data storage get all..
    this.storage.get('user')
  ])
  .then(([user]) => {
    this.userData = user; //set the user storage to this.userData
    console.log(this.userData)
  })
  .catch(error => {
    console.log("Storage Error.");
  });
}

所以我拥有所有用户信息,除了他们实际上没有登录的事实......所以当我这样做时:

this.afAuth.auth.onAuthStateChanged((user) => {
  if (user) {
    console.log(user)
  } else {
    console.log("Not logged in")
  }
});

它显示用户未登录。当我拥有 localStorage 信息时,我是否可以让用户保持登录状态?

或者,除非用户退出,否则可能只是让登录状态始终处于登录状态?与它永不过期?

此时我该怎么办?任何建议都会很棒!谢谢你。

标签: javascriptangulartypescriptfirebasefirebase-authentication

解决方案


Firebase 经理用户以不同的方式。您不应该依赖 localstorage 来检测用户是否登录它。您应该依靠 firebase 来检查用户是否已登录。由于 firebase 是建立在 web 套接字上的,因此它应该非常快。所以让我们重写ngOnInit如下:

ngOnInit() {
    const user = this.afAuth.auth.currentUser;

    if (user) {
      this.userData = user;
    } else {
      // force them to reauthenticate
      user.reauthenticateWithCredential(credential)
        .then(function() {
          // User re-authenticated.
          this.userData = this.afAuth.auth.currentUser;
        }).catch(function(error) {
         // An error happened.
        });
    }
}

在此处阅读有关在 Firebase 中管理用户的更多信息:https ://firebase.google.com/docs/auth/web/manage-users 。希望这可以帮助。


推荐阅读