Firebase 从身份验证数据创建用户对象 [英] Firebase make user object from auth data

查看:26
本文介绍了Firebase 从身份验证数据创建用户对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在 ionic 应用程序中使用 Angularfire,并试图弄清楚如何创建与来自 Auth $createUser 调用的 auth 数据相关联的用户对象.我的第一次尝试进行了 auth 调用并且用户通过了身份验证,然后创建了一个用户对象并将其推送到 $firebaseArray 中,它工作正常,但我不知道如何在他们之后获取当前用户登录以更新、销毁或对该用户数据执行任何操作.我已经通过循环遍历用户数组并匹配来自用户数组项和 auth.uid 项的 uid,该项在用户数组对象创建中设置为相同.如果用户数组很大并且需要在多个页面上完成,那么循环似乎效率很低.

我目前的尝试是使用不同的方法,如下所示:

angular.module('haulya.main').controller('RegisterController', ['Auth', '$scope', 'User', '$ionicPlatform', '$cordovaCamera','CurrentUserService',功能(身份验证,$scope,用户,$ionicPlatform,$cordovaCamera,CurrentUserService){//控制器的作用域变量$scope.user = {};控制台日志(用户);$scope.createUser = 函数(isValid){变量用户模型;$scope.submitted = true;//用户创建成功或失败的消息$scope.user.message = null;$scope.user.error = null;//如果表单填写有效如果(有效){//使用电子邮件和密码firebase Auth方法创建用户Auth.$createUser({电子邮件:$scope.user.email,密码:$scope.user.password}).then(函数(用户数据){用户模型 = {uid:userData.uid,照片:$scope.user.photo ||空值,名字:$scope.user.firstName,姓氏:$scope.user.lastName,电子邮件:$scope.user.email,单元格:$scope.user.cell,dob: $scope.user.dob.toString(),城市:$scope.user.city,状态:$scope.user.state,邮编:$scope.user.zip}//将新用户添加到配置文件数组User.create(userModel).then(function(user) {$scope.sharedUser = User.get(user.path.o[1]);});$scope.user.message = "为电子邮件创建的用户:" + $scope.user.email;}).catch(函数(错误){//根据上下文设置错误消息if(error.code == 'INVALID_EMAIL') {$scope.user.error = "无效邮箱";}else if(error.code == 'EMAIL_TAKEN'){$scope.user.error = "电子邮件已被使用,如果您认为这是一个错误,请联系管理员";}别的 {$scope.user.error = "填写所有必填字段";}});}};//从相机或照片库中获取个人资料图片$scope.getPhoto = 函数(类型){$ionicPlatform.ready(function() {//图像质量/类型/大小/尺寸的选项变量选项 = {质量:65,目的地类型:Camera.DestinationType.DATA_URL,sourceType: Camera.PictureSourceType[type.toUpperCase()],允许真的,编码类型:Camera.EncodingType.JPEG,目标宽度:100,目标高度:100,popoverOptions:CameraPopoverOptions,saveToPhotoAlbum: 假};//使用cordova-plugin-camera获取图像函数$cordovaCamera.getPicture(选项).then(功能(照片){$scope.user.photo = 照片;}, 函数(错误){控制台日志(错误);});});};}]);

这是控制器正在使用的服务:

角度.module('haulya.main').factory('User', function($firebaseArray) {var ref = new Firebase('https://haulya.firebaseio.com');var users = $firebaseArray(ref.child('profiles'));变量用户 = {全部用户,创建:功能(用户){返回 users.$add(user);},获取:函数(用户 ID){返回 $firebaseArray(ref.child('profiles').child(userId));},删除:功能(用户){返回 users.$remove(user);}};返回用户;});

这也有效,但我再次没有对数组中当前登录的用户对象数据的可靠引用.对象 ID 仅存储在控制器范围内.

我浏览了其他帖子,但他们都使用旧版本的 firebase 和已弃用的方法.

解决方案

如果您要存储具有自然键"的项目,最好将它们存储在该键下.对于用户,这将是 uid.

所以不要用 $add() 存储它们,而是用 child().set() 存储它们.

create: function(user) {var userRef = users.$ref().child(user.uid);userRef.set(user);返回 $firebaseObject(userRef);}

您会注意到我使用的是非 AngularFire 方法 child()set().AngularFire 建立在 Firebase 的常规 JavaScript SDK 之上,因此它们可以很好地互操作.这样做的好处是您可以使用 Firebase JavaScript SDK 的所有功能,并且只将 AngularFire 用于它最擅长的地方:将事物绑定到 Angular 的 $scope.

Firebase 的 JavaScript 指南中解释了存储用户数据.我们也将它们存储在他们的 uid 下,而不是使用 push(),这是 $add() 在幕后调用的内容.>

So I'm using Angularfire in an ionic app and trying to figure out how to make a user object that is associated with the auth data from an Auth $createUser call. My first try had the auth call and the user got authenticated, then a user object was made and pushed into a $firebaseArray which works fine, but I don't know how to grab the current user after they are logged in to update, destory, or do anything with that users data. I have made it work with looping through the users array and matching the uid from the user array item and the auth.uid item which was set to be the same in the user array object creation. This seems really ineffecient to loop over if there is a large user array and it needs to be done on multiple pages.

My current attempt is using a different method like so:

angular.module('haulya.main')
.controller('RegisterController', ['Auth', '$scope', 'User', '$ionicPlatform', '$cordovaCamera','CurrentUserService',
  function(Auth, $scope, User, $ionicPlatform, $cordovaCamera, CurrentUserService) {

  //scope variable for controller
  $scope.user = {};
  console.log(User); 

  $scope.createUser = function(isValid) {

    var userModel;
    $scope.submitted = true;

    //messages for successful or failed user creation
    $scope.user.message = null;
    $scope.user.error = null;

    //if form is filled out valid
    if(isValid) {

      //Create user with email and password firebase Auth method
      Auth.$createUser({
        email: $scope.user.email,
        password: $scope.user.password
      })
      .then(function(userData) {

        userModel = {
          uid: userData.uid,
          photo: $scope.user.photo || null,
          firstName: $scope.user.firstName,
          lastName: $scope.user.lastName,
          email: $scope.user.email,
          cell: $scope.user.cell,
          dob: $scope.user.dob.toString(),
          city: $scope.user.city,
          state: $scope.user.state,
          zip: $scope.user.zip
        }

        // add new user to profiles array
        User.create(userModel).then(function(user) {
          $scope.sharedUser = User.get(user.path.o[1]);
        });


        $scope.user.message = "User created for email: " +  $scope.user.email;
      })
      .catch(function(error) {
        //set error messages contextually
        if(error.code == 'INVALID_EMAIL') {
          $scope.user.error = "Invalid Email";
        }
        else if(error.code == 'EMAIL_TAKEN'){
          $scope.user.error = "Email already in use, if you think this is an error contact an administrator";
        }
        else {
          $scope.user.error = "Fill in all required fields";
        }
      });
    }


  };


  //Get profile pic from camera, or photo library
  $scope.getPhoto = function(type) {
    $ionicPlatform.ready(function() {
      //options for images quality/type/size/dimensions
      var options = {
        quality: 65,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType[type.toUpperCase()],
        allowEdit: true,
        encodingType: Camera.EncodingType.JPEG,
        targetWidth: 100,
        targetHeight: 100,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: false
      };

      //get image function using cordova-plugin-camera 
      $cordovaCamera.getPicture(options)
      .then(function(photo) {
        $scope.user.photo = photo;
      }, function(err) {
        console.log(err);
      });
    });

  };

}]);

And here's the service the controller is using:

angular
  .module('haulya.main')
  .factory('User', function($firebaseArray) {
    var ref = new Firebase('https://haulya.firebaseio.com');
    var users = $firebaseArray(ref.child('profiles'));

    var User = {
      all: users,
      create: function(user) {
        return users.$add(user);
      },
      get: function(userId) {
        return $firebaseArray(ref.child('profiles').child(userId));
      },
      delete: function(user) {
        return users.$remove(user);
      } 
    };

    return User;
});

This also works, but again I don't have a solid reference to the currently logged in users object data from the array. The objects id is only stored on the controllers scope.

I looked through other posts, but they were all using older versions of firebase with deprecated methods.

解决方案

If you're storing items that have a "natural key", it is best to store them under that key. For users this would be the uid.

So instead of storing them with $add(), store them with child().set().

create: function(user) {
  var userRef = users.$ref().child(user.uid);
  userRef.set(user);
  return $firebaseObject(userRef);
}

You'll note that I'm using non-AngularFire methods child() and set(). AngularFire is built on top of Firebase's regular JavaScript SDK, so they interoperate nicely. The advantage of this is that you can use all the power of the Firebase JavaScript SDK and only use AngularFire for what it's best at: binding things to Angular's $scope.

Storing user data is explained in Firebase's guide for JavaScript. We store them under their uid there too instead of using push(), which is what $add() calls behind the scenes.

这篇关于Firebase 从身份验证数据创建用户对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆