AngularJS 路由和使用新的 Firebase 身份验证解决

Mit*_*ans 5 javascript angularjs firebase angularfire firebase-authentication

我正在尝试将新的 Firebase 与 Auth 系统一起使用,并在我的$routeProvidervia 中限制路由resolves

不过,我不是很了解。

这就是我所拥有的。在我的 .config 函数中,我正在定义路由并初始化 firebase。以下是我的配置块。

$routeProvider
   .when('/', {
      templateUrl: 'templates/dashboard.ejs',
      //resolve. this needs restricted
   })
   .when('/login', {
      templateUrl: 'templates/login.ejs'
   })

firebase.initializeApp(config);
Run Code Online (Sandbox Code Playgroud)

我在新的文档站点上发现,这些函数在我的.run()块中为 angular列出。

.run(function($rootScope, $location) {

    $rootScope.authentication = firebase.auth();

    /*firebase.auth().onAuthStateChanged(function(user) {
        if(user) {
            $rootScope.user = user;
        } else {
            $rootScope.user = false;
            $location.path('/login')
        }
    })*/

    var user = firebase.auth().currentUser;

    if (user) {
        $rootScope.user = user;
    } else {
        $rootScope.user = false;
        console.log('No User!');
        $location.path('/login');
    }
})
Run Code Online (Sandbox Code Playgroud)

现在,我上面所拥有的只是触发every other time我访问我网站上的任何网址。

所以我的问题是,我如何获取 .run() 函数中的内容并将其转化为我的 routeProvider 的解析,以便我能够再次限制路由。

使用旧的 firebase,您只需像下面一样调用 $firebaseAuth() 并具有如下调用的 routeChangeError 函数。

// In config block. **old way**
$routeProvider
        .when('/', {
            templateUrl: 'templates/dashboard.ejs',
            resolve: {
                "currentAuth": ["$firebaseAuth", function($firebaseAuth) {
                    var ref = new Firebase(fbUrl);
                    var authObj = $firebaseAuth(ref);

                    return authObj.$requireAuth();
                }]
            }
        })
Run Code Online (Sandbox Code Playgroud)

然后是 .run() 块中的 routechangeerror。

 // .run block **old way**
 .run(function($rootScope, $location) {
    $rootScope.$on("$routeChangeError", function(event, current, previous, eventObj) {
        if (eventObj === 'AUTH_REQUIRED') {
            console.log('auth required!');
            $location.path("/login");
        }
    });
})
Run Code Online (Sandbox Code Playgroud)

这不再起作用,因为您不再使用$firebaseAuth()了。或者new Firebase(fbUrl);就此而言。

更新

我觉得它有点乱,但更多地研究路线,我想出了这个。

在我的路线解决:

.when('/', {
            templateUrl: 'templates/dashboard.ejs',
            resolve: {
                userAuthenticated: ["$http", "$q", function($http, $q) {
                    var deferred = $q;
                    if(firebase.auth().currentUser) {
                        deferred.resolve();
                    } else {
                        deferred.reject();
                        console.log('Really!?');
                    }
                    return deferred.promise;
                }]
            }
        })  
Run Code Online (Sandbox Code Playgroud)

然后是一个简单的 routeChangeError。

$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
        alert("Not authorised");
})
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,似乎 deferred.promise 返回未定义。它没有激活 routeChangeError 函数。即使我的console.log()被召唤。

这可能是因为firebase.auth().currentUser在没有用户通过身份验证时返回 null 吗?

Dav*_*ast 4

这些方法已重命名为$waitForSignIn()$requireSignIn

您还可以使用该$firebaseRefProvider服务来配置数据库 URL,以便它自动配置$firebaseAuthService.

angular.module('app', ['firebase'])
  .constant('FirebaseDatabaseUrl', '<my-firebase-url>')
  .controller('HomeCtrl', HomeController)
  .config(function($firebaseRefProvider, FirebaseDatabaseUrl, $routeProvider) {
     $firebaseRefProvider.registerUrl(FirebaseDatabaseUrl);
     $routeProvider.when("/home", {
        controller: "HomeCtrl",
        templateUrl: "views/home.html",
        resolve: {
          // controller will not be loaded until $waitForSignIn resolves
          "firebaseUser": function($firebaseAuthService) {
            return $firebaseAuthService.$waitForSignIn();
          }
        }
      }).when("/account", {
        controller: "AccountCtrl",
        templateUrl: "views/account.html",
        resolve: {
          // controller will not be loaded until $requireSignIn resolves
          "firebaseUser": function(Auth) {
            // If the promise is rejected, it will throw a $stateChangeError
            return $firebaseAuthService.$requireSignIn();
          }
        }
      });
  });

function HomeController($scope, $firebaseRef, firebaseUser) {

} 
Run Code Online (Sandbox Code Playgroud)