持久性Firebase OAuth身份验证

lee*_*oek 0 javascript angularjs firebase firebase-security angularfire

我正在尝试跨多个页面保持Firebase用户身份验证状态.

    $scope.loginGoogle = function() {
        console.log("Got into google login");
        ref.authWithOAuthPopup("google", function(error, authData) { 
           $scope.loggedIn = true;
           $scope.uniqueid = authData.google.displayName;
                 }, {
           remember: "sessionOnly",
           scope: "email"
        });
    };


        function checkLogin() {
           ref.onAuth(function(authData) {
             if (authData) {
                // user authenticated with Firebase
                console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
             } else {
               console.log("Nope, user is not logged in.");
             }
           });
        };
Run Code Online (Sandbox Code Playgroud)

但是,当在另一个页面中调用checkLogin函数时,即使用户已登录登录页面,也未定义authData.似乎是什么问题?

Dav*_*ast 6

这里有两件事要知道.

首先,您将JS Client auth方法与AngularFire结合使用.虽然这不是一件坏事,但你需要注意一些问题.

其次,您可以使用$firebaseAuth AngularFire 0.9中模块来处理下面的所有疯狂内容.

使用Firebase JS客户端级别函数时,由于其摘要循环,Angular不会总是接收它们.对于任何外部JS库都是如此.解决这个问题的方法是使用该$timeout服务.

CodePen

// inject the $timeout service
app.controller("fluttrCtrl", function($scope, $firebase, $timeout) {

  var url = "https://crowdfluttr.firebaseio.com/";
  var ref = new Firebase(url);
  $scope.loginGoogle = function() {
    console.log("Got into google login");

    ref.authWithOAuthPopup("google", function(error, authData) {

    // wrap this in a timeout to allow angular to display it on the next digest loop
    $timeout(function() {
      $scope.loggedIn = true;
      $scope.uniqueid = authData.google.displayName;
    });

    }, {
      remember: "sessionOnly",
      scope: "email"
    });

  });

});
Run Code Online (Sandbox Code Playgroud)

通过将$scope属性包装在$timeout另一个循环中,将运行它并将显示在页面上.

理想情况下,您不想自己处理这个问题.使用$firebaseAuthAngularFire内置的模块.您需要升级到0.9版本才能使用该模块.