Попытка запустить authy-клиент с помощью Firebase Cloud Functions

Я пытался заставить authy-client работать с облачными функциями Firebase, но продолжаю сталкиваться с ошибкой ValidationFailedError. Я безуспешно тестирую примеры, предоставленные автором на https://www.npmjs.com/package/authy-client.

Для моей функции Firebase я пробовал это:

const Client = require('authy-client').Client;
const client = new Client({ key: 'my API key here' });

exports.sendVerificationCode = functions.database.ref('users/{userId}/verify/status')
.onCreate(event => {
  const sender = client.registerUser({
    countryCode: 'US',
    email: 'test@tester.com',
    phone: '4035555555'
  }).then( response => {
    return response.user.id;
  }).then( authyId => {
    return client.requestSms({ authyId: authyId });
  }).then( response => {
    console.log(`SMS requested to ${response.cellphone}`);
    throw Promise;
  });

  return Promise.all([sender]);
});

Но я получаю эту ошибку:

ValidationFailedError: Validation Failed
    at validate (/user_code/node_modules/authy-client/dist/src/validator.js:74:11)
    at _bluebird2.default.try (/user_code/node_modules/authy-client/dist/src/client.js:632:31)
    at tryCatcher (/user_code/node_modules/authy-client/node_modules/bluebird/js/release/util.js:16:23)
    at Function.Promise.attempt.Promise.try (/user_code/node_modules/authy-client/node_modules/bluebird/js/release/method.js:39:29)
    at Client.registerUser (/user_code/node_modules/authy-client/dist/src/client.js:617:34)
    at exports.sendVerificationCode.functions.database.ref.onCreate.event (/user_code/index.js:24:25)
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
    at /var/tmp/worker/worker.js:695:26
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Я новичок в облачных функциях Firebase, поэтому я могу пропустить что-то очевидное, но из того, что я прочитал, операторы then() и сама функция должны возвращать / выдавать Promise, поэтому я взломал это вместе.

Я также позаботился о том, чтобы authy-client был включен в зависимости в файле package.json.

Первоначально я подписался на пробную версию Twilio, которая дала мне возможность создать приложение с Authy. Чтобы быть уверенным, я также вошел в Authy, чтобы проверить, является ли ключ API тем же, и они есть. Поэтому я не думаю, что ошибка проверки связана с ключом API.

Любая помощь будет оценена. Спасибо.

3 ответа

Спасибо всем за ваши ответы. Я наконец смог найти решение. Это не имеет ничего общего с кодом, ну throw Promise Это была ошибка, но, очевидно, это была проблема с разрешениями DNS, которая была решена, когда я настроил биллинг на Firebase.

Что касается моего окончательного кода, так как я изначально хотел использовать authy-client для проверки телефона, он выглядит примерно так:

exports.sendVerificationCode = functions.database.ref('users/{userId}/verify')
.onCreate(event => {
  const status = event.data.child('status').val();
  const phoneNum = event.data.child('phone').val();
  const countryCode = event.data.child('countryCode').val();
  var method;

  if(status === 'pendingSMS')
    method = 'sms';
  else
    method = 'call';

  // send code to phone
  const sender = authy.startPhoneVerification({ countryCode: countryCode, phone: phoneNum, via: method })
  .then( response => {
    return response;
  }).catch( error => {
    throw error;
  });

  return Promise.all([sender]);
});

throw Promise на самом деле ничего не значит. Если вы хотите зафиксировать проблемы, которые могут возникнуть в любом месте вашей последовательности обещаний, у вас должен быть раздел catch. Общая форма такова:

return someAsyncFunction()
    .then(...)
    .then(...)
    .catch(error => { console.error(error) })

Это не обязательно исправит вашу ошибку, хотя. Это может исходить от API, который вы вызывали.

Twilio разработчик евангелист здесь.

Даг прав насчет throw Promise, что определенно нужно будет изменить.

Тем не менее, ошибка, кажется, приходит до этого и от API. В частности, трассировка стека говорит нам:

    at Client.registerUser (/user_code/node_modules/authy-client/dist/src/client.js:617:34)

Так что проблема в registerUser функция. Лучше всего попытаться раскрыть больше ошибок, которые генерируются из API. Это должно дать вам необходимую информацию.

Примерно так должно помочь:

const Client = require('authy-client').Client;
const client = new Client({ key: 'my API key here' });

exports.sendVerificationCode = functions.database.ref('users/{userId}/verify/status')
.onCreate(event => {
  const sender = client.registerUser({
    countryCode: 'US',
    email: 'test@tester.com',
    phone: '4035555555'
  }).then( response => {
    return response.user.id;
  }).then( authyId => {
    return client.requestSms({ authyId: authyId });
  }).then( response => {
    console.log(`SMS requested to ${response.cellphone}`);
  }).catch( error => {
    console.error(error.code);
    console.error(error.message);
    throw error;
  });    
});

Дайте мне знать, если это поможет.

Другие вопросы по тегам