Firebase requireAuth无法正常工作

时间:2015-08-18 11:58:23

标签: firebase-authentication

我很难让requireAuth工作。我尝试了ngroute和uirouter,如果用户没有登录,我只想将他重定向回主页。

在我的应用程序中,我有1个页面,其中有多个控制器,我想设置上述规则。

这是工厂和运行方法:

app.factory("AuthFactory", ["$firebaseAuth", function($firebaseAuth) {
  var ref = new Firebase("https://torrid-heat-237.firebaseio.com");
  return $firebaseAuth(ref);
  }
]);

// for ui-router
app.run(["$rootScope", "$state", function($rootScope, $state) {
$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
  // We can catch the error thrown when the $requireAuth promise is rejected
  // and redirect the user back to the home page
  if (error === "AUTH_REQUIRED") {
    $state.go("/");
  }
});
}]);

我写了一个.state方法:

app.config(["$stateProvider", function ($stateProvider) {
$stateProvider
    .state('geniuses', {
      url: '/geniuses',
      abstract: true,
      controller: 'GetAllGeniuses',
      templateUrl: "views/listAllgeniuses",
      resolve: {
        "currentAuth": ["AuthFactory", function(AuthFactory) {
          return AuthFactory.$requireAuth();
        }]
      }
    }).state('geniuses', {
      url: '/geniuses',
      abstract: true,
      controller: 'SearchAGenius',
      templateUrl: "views/listAllgeniuses",
      resolve: {
        "currentAuth": ["AuthFactory", function(AuthFactory) {
          return AuthFactory.$requireAuth();
        }]
      }
    })
}]);

最后,在两个控制器中,我正在等待AuthFactory.requireAuth解决。但是,当我点击没有登录的网址时会发生什么,它会自动停留在那里,即使我登录时也会显示相同类型的页面。

我到底错误地做了什么?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题

最后可以解决它。

请确保在注销时调用$ unauth()。你第一次登录它会没事的。在没有$ unauth()的情况下关闭会话时会出现真正的问题。

所以,如果你有注销功能,请使用:

AuthFactory.$unauth();

这是我的代码中的一个例子:

app.factory('Auth', ["$firebaseAuth","settings",
function($firebaseAuth,settings){

return {
    oauth: function() {

      var ref = new Firebase(settings.firebaseBaseUrl);

      return $firebaseAuth(ref);
    }
}]);



.state("votes",{
  url:"/restaurant/poll",
  views:{
    "main":{
      templateUrl:"views/restaurant/poll/main.html",
      controller: "pollsController"
    }
  },
  data: {pageTitle:'Encuesta'},
  resolve: {
    "currentAuth": ["Auth", function(Auth) {
      return Auth.oauth().$requireAuth();
    }]
  }
});


app.run(function($rootScope,settings, $state, $location, $localStorage, Auth) {

  $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
    if (error === "AUTH_REQUIRED") {
      $state.go('home');
    }
});

最后:

MetronicApp.controller('HeaderController', ['$scope', "$rootScope", "Auth", "$state", "$localStorage", "toaster",
function($scope, $rootScope, Auth, $state, $localStorage) {


  $rootScope.logout = function(to){
    to = to == undefined ? 'home' : to;
    Auth.oauth().$unauth();
    $state.go(to);
  };


}]);
相关问题