All files / src auth.js

69.23% Statements 18/26
62.5% Branches 10/16
100% Functions 3/3
69.23% Lines 18/26

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      1x 1x 1x     1x 1x   1x   1x 1x                     1x 1x 1x 1x                                                 7x 1x     7x       7x 1x     6x            
import moment from 'moment'
import axios from 'axios'
 
let token = null
let tokenType = null
let expiresAt = null
 
async function auth (options) {
  try {
    const authorization = `Basic ${ Buffer.from(`${ options.clientId }:${ options.clientSecret }`).toString('base64') }`
    
    const endpoint = `${ options.authUri }?grant_type=${ options.authGrantType }`
    
    try {
      const response = await axios.request({
        url: endpoint,
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json',
          'Authorization': authorization
        },
        data:{}
      })
      
      Eif (!!response && response.status === 200 && response.data) {
        token = response.data.access_token
        tokenType = response.data.token_type
        expiresAt = moment(new Date()).add(response.data.expires_in, 'seconds')
        
      } else {
        
        throw new Exception('Unable to connect to Nequi, please check the information sent.')
      }
    } catch (error) {
      let msgError = ''
      
      if (error.isAxiosError) {
        const { status = 'Undefined', statusText = 'Undefined' } = error.response
        
        msgError = `Axios error ${ status } -> ${ statusText }`
      } else {
        msgError = `Error -> ${ error }`
      }
      
      throw new Error(msgError)
    }
  } catch (e) {
    throw new Error('Unable to auth to Nequi, please check the information sent.')
  }
}
 
async function getToken (options, full = true) {
  if (!isValidToken()) {
    await auth(options)
  }
  
  return full ? `${ tokenType } ${ token }` : token
}
 
function isValidToken () {
  if (!expiresAt) {
    return false
  }
  
  return moment().isBefore(expiresAt)
}
 
export default {
  getToken
}