All files / 2factor.in index.js

76.12% Statements 102/134
76.92% Branches 60/78
82.61% Functions 19/23
76.12% Lines 102/134

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 2841x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                     1x 2x 2x                             1x 17x 17x 2x   17x 1x 1x   16x 16x 3x         3x 3x 3x 3x 3x 3x 3x                   3x 13x 7x 6x 3x 3x 3x       13x     13x       13x 13x 13x                                 1x 4x 4x 1x   3x 3x   3x         3x     3x       3x       3x 3x 3x                                 1x 4x 4x 1x   3x     3x 3x   3x         3x 1x 2x     3x       3x       3x 3x 3x                                   1x 10x 10x 4x 4x   6x 2x 2x   4x 4x   1x 3x     3x         3x   4x     4x       4x 4x 4x 3x   1x                               1x 2x 2x 1x 1x   1x 1x 1x                                                 1x
const request = require('request')
const baseURL = "https://2factor.in/API/V1/"
const EP_SMS_BAL = "/BAL/SMS"
const EP_SMS = "/SMS/"
const EP_SMS_VERIFY = "/SMS/VERIFY/"
const EP_TSMS_BAL = "/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS"
const EP_TSMS_SEND = "/ADDON_SERVICES/SEND/TSMS"
const EP_TSMS_RPT = "/ADDON_SERVICES/RPT/TSMS/"
const EP_PSMS_BAL = "/ADDON_SERVICES/BAL/PROMOTIONAL_SMS"
const EP_PSMS_SEND = "/BAL/SMS"
const EP_PSMS_RPT = "/ADDON_SERVICES/RPT/PSMS/"
 
/**
* Constructor function that takes an API key and
* an optional default senderid as parameters and returns
* a new TwoFactor api client.
*
* @param {string} APIKEY - The apikey to be used while making requests.
* @param {string} [SENDERID=TFCTOR] - default senderid to be used if no sender id
* is specified in send().
*/
const TwoFactor = function (APIKEY, SENDERID) {
  this.apikey = APIKEY
  this.defaultSID = SENDERID || "TFCTOR"
}
 
/**
* Method to retrieve balance for this client. It expects a type parameter which
* is a string defining the type of balance to return.
<<<<<<< HEAD
* Type can be either 'SMS', 'TRANSACTIONAL_SMS' or 'PROMOTIONAL_SMS'.
=======
* Type can be either 'ALL', SMS', 'TRANSACTIONAL_SMS' or 'PROMOTIONAL_SMS'.
>>>>>>> d70cbc000cc24378c2ea1f0bc98d792d0cb693db
*
* @param {string} type - The type of balance to return
* @return {Promise} A promise object that resolves after the api call has completed
*/
TwoFactor.prototype.balance = function(type) {
  return new Promise((resolve, reject) => {
    if (!type) {
      type = 'ALL'
    }
    if (['ALL', 'SMS', 'TRANSACTIONAL_SMS', 'PROMOTIONAL_SMS'].indexOf(type) === -1) {
      reject(new Error("Invalid value of `type` parameter"))
      return
    }
    let url = ''
    if (type === 'ALL') {
      let balances = {
        sms: undefined,
        transactional: undefined,
        promotional: undefined
      }
      this.balance('SMS').then(response => {
        balances.sms = response.Details
        this.balance('TRANSACTIONAL_SMS').then(response => {
          balances.transactional = response.Details
          this.balance('PROMOTIONAL_SMS').then(response => {
            balances.promotional = response.Details
            resolve(balances)
          }).catch(error => {
            reject(error)
          })
        }).catch(error => {
          reject(error)
        })
      }).catch(error => {
        reject(error)
      })
      return
    } else if (type === 'SMS') {
      url = `${baseURL}${this.apikey}${EP_SMS_BAL}`
    } else if (type === 'TRANSACTIONAL_SMS') {
      url = `${baseURL}${this.apikey}${EP_TSMS_BAL}`
    } else Eif (type === 'PROMOTIONAL_SMS') {
      url = `${baseURL}${this.apikey}${EP_PSMS_BAL}`
    } else {
      throw new Error('Invalid `type` field. Valid values are SMS, TRANSACTIONAL_SMS and PROMOTIONAL_SMS')
    }
    var req = request.get({
      url: url
    }, function(err, res, body) {
      Iif (err) {
        reject(err)
        return
      }
      try {
        let parsedBody = JSON.parse(body)
        resolve(parsedBody)
      } catch(e) {
        reject(e)
      }
    })
  })
}
 
 
/**
* Send a transactional, open template SMS
* @param  {array} phoneNumbers - An array of phone numbers without country codes
* @param  {string} message - The message to be sent
* @param  {string} [senderId] - A senderId to be used while sending this message otherwise the defaultSID is used
* @param  {date} [sendAt] - time to schedule this SMS for
* @return {Promise} A promise object that resolves after the api call has completed
*/
TwoFactor.prototype.sendTransactional = function(phoneNumbers, message, senderId, sendAt) {
  return new Promise((resolve, reject) => {
    if (typeof phoneNumbers === 'undefined' || typeof message === 'undefined') {
      reject(new Error('sendTransactional() expects phoneNumbers and message to be specified'))
    } else {
      Eif(!Array.isArray(phoneNumbers)) {
        phoneNumbers = [phoneNumbers]
      }
      let payload = {
        From: senderId || this.defaultSID,
        To: phoneNumbers.join(","),
        Msg: message
      }
      Iif (sendAt) {
        payload.SendAt = sendAt
      }
      var req = request.post({
        url: `${baseURL}${this.apikey}${EP_TSMS_SEND}`,
        form: payload
      }, function(err, res, body) {
        Iif (err) {
          reject(err)
          return
        }
        try {
          let parsedBody = JSON.parse(body)
          resolve(parsedBody)
        } catch(e) {
          reject(e)
        }
      })
    }
  })
}
 
/**
* Send a template based SMS with pre approved senderid
* @param  {array} phoneNumbers - An array of phone numbers without country codes
* @param  {string} templateName - Name of the template to be used
* @param  {string} values - An array holding maximum of 5 values to be used in the template. 
* @param  {string} [senderId] - Optional parameter to specify a different senderid for this request
* @return {Promise} A promise object that resolves after the api call has completed
*/
TwoFactor.prototype.sendTemplate = function(phoneNumbers, templateName, values, senderId) {
  return new Promise((resolve, reject) => {
    if (typeof phoneNumbers === 'undefined' || typeof templateName === 'undefined') {
      return reject(new Error('sendTemplate() expects phoneNumbers and template name to be specified'))
    }
    Iif (values && values.length > 5) {
      return reject(new Error("values field must be an array with a maximum of 5 values."))
    }
    Eif(!Array.isArray(phoneNumbers)) {
      phoneNumbers = [phoneNumbers]
    }
    let payload = {
      From: senderId || this.defaultSID,
      To: phoneNumbers.join(","),
      TemplateName: templateName
    }
    if(Array.isArray(values)) {
      values.forEach((element, index) => {
        payload['VAR' + (index + 1)] = element
      })
    }
    var req = request.post({
      url: `${baseURL}${this.apikey}${EP_TSMS_SEND}`,
      form: payload
    }, function(err, res, body) {
      Iif (err) {
        reject(err)
        return
      }
      try {
        let parsedBody = JSON.parse(body)
        resolve(parsedBody)
      } catch(e) {
        reject(e)
      }
    })
  })
}
 
/**
* Send an OTP to a given phone number. Accepts a phone number parameter along with an
* optional `options` parameter. Options object has the following attributes - 
* 1. {number} otp - The otp you want to send to the phone number
* 2. {string} template - A string containing the template name to use for sending the otp
*
* @param  {string} phoneNumber - An string containig a 10 digit phone number
* @param  {object} options - An object containing configuration options for the request
* @return {Promise} A promise object that resolves after the api call has completed
*/
TwoFactor.prototype.sendOTP = function (phoneNumber, options) {
  return new Promise((resolve, reject) => {
    if (!phoneNumber) {
      reject(new Error('invalid or missing phoneNumber field'))
      return
    }
    if (phoneNumber.length !== 10) {
      reject(new Error('phone number must be exactly 10 digits'))
      return
    }
    let url = ''
    if (!options || (!options.otp && !options.template)) {
      // No otp or template specified
      url = `${baseURL}${this.apikey}${EP_SMS}${phoneNumber}/AUTOGEN`
    } else  Iif (options.template && !options.otp) {
      // Custom template, No otp specified
      url = `${baseURL}${this.apikey}${EP_SMS}${phoneNumber}/AUTOGEN/${options.template}`
    } else Iif (options.otp && !options.template) {
      // Custom otp, No template specified
      url = `${baseURL}${this.apikey}${EP_SMS}${phoneNumber}/${options.otp}`
    } else {
      // Custom otp and template
      url = `${baseURL}${this.apikey}${EP_SMS}${phoneNumber}/${options.otp}/${options.template}`
    }
    let req = request.post({
      url: url
    }, function(err, res, body) {
      Iif (err) {
        reject(err)
        return
      }
      try {
        let parsedBody = JSON.parse(body)
        if (parsedBody.Status === 'Error') {
          reject(parsedBody.Details)
        } else {
          resolve(parsedBody.Details)
        }
      } catch(e) {
        reject(e)
      }
    })
  })
}
 
/**
* Verify an OTP sent to a given phone number
*
* @param  {string} sessionId - A string containig the session id returned while sending the otp
* @param  {object} otp - A string containing the otp code to verify 
* @return {Promise} A promise object that resolves after the api call has completed
*/
TwoFactor.prototype.verifyOTP = function (sessionId, otp) {
  return new Promise((resolve, reject) => {
    if (!sessionId || sessionId === '') {
      reject(new Error('invalid or missing sessionId parameter'))
      return
    }
    Eif (!otp || otp.length < 4 || otp.length > 6) {
      reject(new Error('invalid or missing otp parameter'))
      return
    }
    let url = `${baseURL}${this.apikey}/SMS/VERIFY/${sessionId}/${otp}`
    console.log(url)
    let req = request.post({
      url: url
    }, function(err, res, body) {
      if (err) {
        reject(err)
        return
      }
      try {
        let parsedBody = JSON.parse(body)
        if (parsedBody.Status === 'Error') {
          reject(parsedBody.Details)
        } else {
          resolve(parsedBody.Details)
        }
      } catch(e) {
        reject(e)
      }
    })
  })
}
 
module.exports = TwoFactor