5

创建用户时尝试更新实时数据库中的用户数据。这是我的代码:

const functions = require('firebase-functions');
const promise = require('request-promise');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

var omitBy = require('lodash.omitby');
var isNil = require('lodash.isnil');

'use strict';

exports.userCreated = functions.auth.user().onCreate(event => {

  let request = admin.auth().getUser(event.data.uid)
  .then(function(user) {
    console.log("Successfully fetched user data: ", user.toJSON());

    var email, firstName, lastName, photoURL;

    for (var provider of user.providerData) {

      if (provider.email) {
        email = provider.email;
      }

      if (provider.photoURL) {
        photoURL = provider.photoURL;
      }

      if (provider.displayName) {
        const names = provider.displayName.split(' ');
        firstName = names[0];

        if (names.length > 1) {
          lastName = names[names.length - 1];
        }
      }
    }

    var values = omitBy({
      email: email,
      first_name: firstName,
      last_name: lastName,
      license_agreement_version: '1.1',
      image_url: photoURL
    }, isNil);

    admin.database().ref('users/' + user.uid).set(values);
  })
  .catch(function(error) {
    console.error("Error Fetching User: ", error);
  });

  return request;
});

但是,当通过创建用户时。Facebook,未提供提供商数据。这是控制台日志:

Successfully fetched user data: { uid: 'exampleUID',
  email: undefined,
  emailVerified: false,
  displayName: undefined,
  photoURL: undefined,
  disabled: false,
  metadata: 
   { lastSignedInAt: 2017-03-16T19:40:59.000Z,
     createdAt: 2017-03-16T19:40:59.000Z },
  providerData: [] }

我做错了什么,还是不会在创建时提供这些数据?

4

1 回答 1

2

您无需再次调用admin.auth().getUser(...). 方便的是event.data,您在此功能中收到的 已经是UserRecord

这是我打印身份验证事件的非常简单的代码:

var functions = require('firebase-functions');

exports.helloAuth = functions.auth.user().onCreate(event => {
  console.log("User created: " + JSON.stringify(event));
});

以下是我通过 Facebook 登录时的输出:

{
  "displayName": "Robert-Jan Huijsman",
  "email": "REDACTED@gmail.com",
  "metadata": {
    "createdAt": "2017-03-17T01:34:03.000Z",
    "lastSignedInAt": "2017-03-17T01:34:03.000Z"
  },
  "photoURL": "https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100/REDACTED",
  "providerData": [
    {
      "displayName": "Robert-Jan Huijsman",
      "email": "REDACTED@gmail.com",
      "photoURL": "https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100/REDACTED",
      "providerId": "facebook.com",
      "uid": "http://facebook.com/1234567890"
    }
  ],
  "uid": "AaBbCcDdEeFf"
}
于 2017-03-17T01:46:42.887 回答