代码之家  ›  专栏  ›  技术社区  ›  Guy

使用Firebase Javascript SDK持久登录

  •  0
  • Guy  · 技术社区  · 8 年前

    我使用Firebase npm包(版本5.2.0)进行客户端身份验证和数据库。

    出于某种原因,即使我将persistence设置为 本地的 ,每次刷新 当前用户为空 .

    登录:

    export const login = (email, password) => {
        return firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
            .then(() => {
                return firebase.auth().signInWithEmailAndPassword(email, password);
            })
    }
    

    获取当前用户:

    export const currentUser = () => {
         return firebase.auth().currentUser;
    }
    

    另一个奇怪的地方是我在使用持久性时应用数据库规则我得到一个许可错误如果规则设置为公共读/写,则错误消失持久性机制需要访问数据库吗?

    Firebase error

    我做错什么了吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   mark922    8 年前

    使用以下代码:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
      } else {
        // No user is signed in.
      }
    });
    

    而不是通过 firebase.auth().currentUser .

    这是firebase文档中的注释,用于 firebase.auth().currentUser版本

    注意:currentUser也可能为空,因为auth对象尚未完成初始化如果使用观察者跟踪用户的登录状态,则不需要处理此情况。

    参考: link