【问题标题】:How to handle Firebase auth in single page app如何在单页应用程序中处理 Firebase 身份验证
【发布时间】:2013-06-04 11:57:16
【问题描述】:

我正在使用带有 angularjs 的 firebase 简单登录身份验证,我想创建一个单页应用程序。 在此之前,我曾尝试使用servicemain controller 来处理它,但我认为这还不够好,因为每次有路由时我都必须调用 FirebaseAuthClient()。 我还尝试将 FirebaseAuthClient() 放入 angularjs .run() 中,它会在应用程序启动时进行初始化。 但是当有路由的时候就不行了,我想是因为没有完整的页面加载。

好的, 这就是我想要的,

  • 除登录页面外,每个路由(页面)都需要登录。
  • 全局 FirebaseAuthClient() 检查每条路由,因此我不需要再次调用它。
  • 从 FirebaseAuthClient() 返回的全局 user

【问题讨论】:

    标签: angularjs firebase firebase-security


    【解决方案1】:

    我不确定我是否理解。您只需在整个应用程序中初始化 FirebaseAuthClient 和所有 login() 一次。这是一个单例,您的身份验证凭据适用于您执行的任何 Firebase 操作。

    是什么让您认为情况并非如此?您看到了哪些类型的错误?

    【讨论】:

    • 嗨,我终于弄清楚了我的问题所在。在这里,我让它变得简单。由于单页应用程序不是整页加载。如何在每条路线中处理“用户是否登录”?每次路由更改时调用 FirebaseAuthClient()?我不确定这是否与 angularjs 或 firebase 有关。
    • 您应该只记得 FirebaseAuthClient 返回给您的最后一个结果。您无需再次调用它。
    • 我应该在哪里存储身份验证信息以备后用? angularjs 中的 Cookie 或 $rootScope?无论如何我可以在用户认证后直接调用 auth.id (user id) 吗?
    • 我对 Angular 的了解不够,无法在这里给出一个好的答案。绝对不是 cookie(那些仅用于在页面加载时存储数据,我们已经为您完成了)。也许更熟悉 Angular 的方式可以在这里为您提供帮助。全局变量可以正常工作,但可能不是最佳做法。
    【解决方案2】:

    这是我在将身份验证转移到 Singly 之前使用的内容。也许有帮助?

    p4pApp.factory('firebaseAuth', function($rootScope) {
    var auth = {},
    FBref = new Firebase(p4pApp.FIREBASEPATH);
    
    auth.broadcastAuthEvent = function() {
        $rootScope.$broadcast('authEvent');
    };
    
    auth.client = new FirebaseAuthClient(FBref, function(error, user) {
        if (error) {
        } else if (user) {
            auth.user = user;
            auth.broadcastAuthEvent();
        } else {
            auth.user = null;
            auth.broadcastAuthEvent();
        }
    });
    
    auth.login = function() {
        this.client.login('facebook');
    };
    
    auth.logout = function() {
        this.client.logout();
    };
    
    return auth;
    });
    

    AuthCtrl 对我的所有/大部分页面都是通用的。

    var AuthCtrl = function($scope, firebaseAuth) {
    $scope.login = function() {
        firebaseAuth.login();
    };
    
    $scope.logout = function() {
        firebaseAuth.logout();
    };
    
    $scope.isLoggedIn = function() {
        return !!$scope.user;   
    };
    
    // src: Alex Vanston (https://coderwall.com/p/ngisma)
    $scope.safeApply = function(fn) {
        var phase = this.$root.$$phase;
        if (phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) {
                fn();
            }
        } else {
            this.$apply(fn);
        }
    };
    
    $scope.$on('authEvent', function() {
        $scope.safeApply(function() {
            $scope.user = firebaseAuth.user;
        });
    });
    };
    

    您可以在 AuthCtrl 中调用 isLoggedIn() 来查看用户是否已登录。

    【讨论】:

      猜你喜欢
      • 2013-03-13
      • 1970-01-01
      • 2013-08-19
      • 2021-06-02
      • 2013-11-25
      • 2018-12-29
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      相关资源
      最近更新 更多