【问题标题】:angularjs with firebase auth share service带有firebase auth共享服务的angularjs
【发布时间】:2013-05-22 20:16:31
【问题描述】:

光环,

我想将 angularjs 与 firebase 简单登录(facebook)一起使用。但我不知道如何 创建身份验证共享服务。

我想做的是

  • 创建身份验证服务
  • 使用此身份验证服务检查用户是否登录每个控制器
  • 如果用户登录/未登录,控制器将执行$location

我也是 angularjs 的新手,但我不知道在这种情况下应该使用哪些服务。 servicefactory?

如何将以下代码放入角度服务中,然后告诉每个控制器用户是否登录?

var firebaseRef = new Firebase("https://test.firebaseio.com");
var auth = new FirebaseAuthClient(firebaseRef, function(error, user) {
   if (user) {
      console.log(user);
   } else if (error) {
      console.log(error);
   } else {
      console.log('user not login');
   }
});

这就是我的猜测,从authService 返回user 值,所以在控制器中如果authService.user 存在则重定向到登录页面,否则显示登录对话框 登录按钮调用如下代码

authService.login('facebook');

如果我可以这样做,或者有更好的方法,请告诉我?

【问题讨论】:

    标签: angularjs firebase angularjs-service firebase-security


    【解决方案1】:

    这是我目前使用的...

    我还没有实现重定向,但其余的工作。

    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;
        });
    });
    };
    

    【讨论】:

    • 哇,你成就了我的一天。我在想如何返回值和 auth 对象。现在我明白了,把它们分开。非常感谢
    【解决方案2】:

    关于工厂与服务,有一篇很好的博客文章解释了如何处理我推荐阅读的选择:http://iffycan.blogspot.com/2013/05/angular-service-or-factory.html

    在进行身份验证方面,您将登录状态分配给服务中的变量的一般方法似乎没问题。我们正在考虑与 Angular 进行更深入的集成以进行身份​​验证,但目前这似乎是一种合理的方法。

    【讨论】:

      猜你喜欢
      • 2014-11-07
      • 1970-01-01
      • 2020-03-17
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 2019-05-03
      • 1970-01-01
      相关资源
      最近更新 更多