UNPKG

@bitblit/ratchet-common

Version:

Common tools for general use

60 lines 3.19 kB
import fetch from 'cross-fetch'; import { RequireRatchet } from '../../lang/require-ratchet.js'; import { Logger } from '../../logger/logger.js'; import { TwilioRatchet } from './twilio-ratchet.js'; export class TwilioVerifyRatchet { accountSid; authToken; serviceSid; static TWILLIO_BASE_VERIFY_URL = 'https://verify.twilio.com/v2/Services/'; constructor(accountSid, authToken, serviceSid) { this.accountSid = accountSid; this.authToken = authToken; this.serviceSid = serviceSid; RequireRatchet.notNullUndefinedOrOnlyWhitespaceString(accountSid, 'accountSid'); RequireRatchet.notNullUndefinedOrOnlyWhitespaceString(authToken, 'authToken'); RequireRatchet.notNullUndefinedOrOnlyWhitespaceString(serviceSid, 'serviceSid'); } async sendVerificationTokenUsingTwilioVerify(recipientPhoneNumber) { RequireRatchet.notNullUndefinedOrOnlyWhitespaceString(recipientPhoneNumber, 'recipientPhoneNumber'); RequireRatchet.true(TwilioRatchet.isValidE164Number(recipientPhoneNumber), 'recipientPhoneNumber must be E164'); const phone = recipientPhoneNumber.startsWith('+1') ? recipientPhoneNumber : '+1' + recipientPhoneNumber; const body = 'Channel=sms&To=' + encodeURIComponent(phone); const post = { method: 'post', headers: { authorization: TwilioRatchet.generateTwilioBasicAuth(this.accountSid, this.authToken), 'Content-Type': 'application/x-www-form-urlencoded', }, body: body, }; const url = TwilioVerifyRatchet.TWILLIO_BASE_VERIFY_URL + this.serviceSid + '/Verifications'; const res = await fetch(url, post); const respBody = await res.text(); return respBody; } async simpleCheckVerificationTokenUsingTwilioVerify(recipientPhoneNumber, code) { const val = await this.checkVerificationTokenUsingTwilioVerify(recipientPhoneNumber, code); return val && val.status === 'approved'; } async checkVerificationTokenUsingTwilioVerify(recipientPhoneNumber, code) { RequireRatchet.notNullUndefinedOrOnlyWhitespaceString(recipientPhoneNumber, 'recipientPhoneNumber'); RequireRatchet.true(TwilioRatchet.isValidE164Number(recipientPhoneNumber), 'recipientPhoneNumber must be E164'); const phone = recipientPhoneNumber.startsWith('+1') ? recipientPhoneNumber : '+1' + recipientPhoneNumber; const body = 'To=' + encodeURIComponent(phone) + '&Code=' + encodeURIComponent(code); const post = { method: 'post', headers: { authorization: TwilioRatchet.generateTwilioBasicAuth(this.accountSid, this.authToken), 'Content-Type': 'application/x-www-form-urlencoded', }, body: body, }; const url = TwilioVerifyRatchet.TWILLIO_BASE_VERIFY_URL + this.serviceSid + '/VerificationCheck'; Logger.info('Using %s / %j', url, post); const res = await fetch(url, post); const parsedResponse = await res.json(); return parsedResponse; } } //# sourceMappingURL=twilio-verify-ratchet.js.map