如何以应用用户身份保存Google登录?

时间:2015-07-10 18:19:18

标签: angularjs firebase

所以我有一些代码使用google对我的应用程序的用户进行身份验证,效果很好。我想要做的是然后将该用户信息保存到firebase,然后让该用户能够在他们的帐户下专门添加数据,然后在他们下次登录时重新加载。有什么最好的方法呢?我迷路了。

(function() {
  'use strict';

  angular.module('life-of-a-story')
    .controller('UserController', function($scope, $firebaseAuth) {
      var ref = new Firebase('https://life-of-a-story.firebaseio.com/');
      // create an instance of the authentication service
      var auth = $firebaseAuth(ref);
      // login with Google
      this.login = function() {
        auth.$authWithOAuthPopup("google").then(function(authData) {
          console.log(authData);
          console.log("Logged in as:", authData.uid);
          var user = {
            'name': authData.google.displayName,
            'image': authData.google.profileImageURL,
            'uid': authData.uid
          }
          console.log(user);
        }).catch(function(error) {
          console.log("Authentication failed:", error);
        });
      };
    });
})();

1 个答案:

答案 0 :(得分:1)

AngularFire是一个(相对)瘦的UI绑定库,位于Firebase的常规JavaScript SDK之上。因此,当AngularFire文档中没有明确记录某些内容时,您有时可以在documentation for the regular Firebase JavaScript SDK中找到答案。

大多数Firebase身份验证开发人员将每个用户的数据存储在/users节点下。如果您正在尝试这样做,您可以在名为Storing user data in the Firebase documentation for JavaScript的部分中阅读如何完成它。

来自那里的相关代码:

// we would probably save a profile when we register new users on our site
// we could also read the profile to see if it's null
// here we will just simulate this with an isNewUser boolean
var isNewUser = true;
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
  if (authData && isNewUser) {
    // save the user's profile into the database so we can list users,
    // use them in Security and Firebase Rules, and show profiles
    ref.child("users").child(authData.uid).set({
      provider: authData.provider,
      name: getName(authData)
    });
  }
});
// find a suitable name based on the meta info given by each provider
function getName(authData) {
  switch(authData.provider) {
     case 'password':
       return authData.password.email.replace(/@.*/, '');
     case 'twitter':
       return authData.twitter.displayName;
     case 'facebook':
       return authData.facebook.displayName;
  }
}