刷新后如何让用户登录firebase应用程序?

Jus*_*ock 12 javascript authentication angularjs firebase

我有一个内置firebase和angular的应用程序,我希望能够在刷新页面后让用户登录.现在我有一个登录屏幕,其中包含两个绑定到控制器的基本输入字段

    this.email = "";
    this.pass = "";
    this.emessage = "";

    this.loginUser = function() {
        ref.authWithPassword({
            email: this.email,
            password: this.pass
        }, function(error, authData) {
            if (error) {
                console.log("Login Failed!", error);
                this.emessage = error.message;
                $scope.$apply();
            } else {
                dataStorage.uid = authData.uid;
                $location.path('/projects');
                $scope.$apply(); 
            }
        }.bind(this));
    }
Run Code Online (Sandbox Code Playgroud)

这一切都很好,花花公子它可以工作,但是当用户刷新页面时,它们会被退回.有没有办法在控制器加载时查看用户是否已登录并自动重定向?谢谢!

Fra*_*len 18

您现在拥有的代码处理用户登录的情况.要处理用户已记录的情况,请监视身份验证状态.从有关监控身份验证状态Firebase文档中:

// Create a callback which logs the current auth state
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
  if (authData) {
    console.log("User " + authData.uid + " is logged in with " + authData.provider);
  } else {
    console.log("User is logged out");
  }
});
Run Code Online (Sandbox Code Playgroud)

通常,您只想在else此函数中显示登录按钮.

  • 似乎已弃用了onAuth。请参阅https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged (3认同)

mfl*_*din 9

正如评论中提到的,接受的答案不再有效。当前检查用户是否登录的方法是

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  }
});
Run Code Online (Sandbox Code Playgroud)

(来自https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged