All files / lib/client/strategies index.js

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                                                                                                                                                                 
/**
 * @name Strategies
 * @description This module is responsible for the
 *              authentication method strategies.
 * @module strategies
 * @private
 */
 
import {
  allPass,
  and,
  both,
  has,
  cond,
  T,
  isNil,
} from 'ramda'
 
import encryption from './encryption'
import login from './login'
import api from './api'
import sessionId from './sessionId'
import jwt from './jwt'
 
const isBrowserEnvironment = typeof global === 'undefined'
 
function rejectInvalidAuthObject () {
  return Promise.reject(new Error('You must supply a valid authentication object'))
}
 
function rejectAPIKeyOnBrowser () {
  return Promise.reject(new Error('You cannot use an api key in the browser!'))
}
 
/**
 * Defines the correct authentication
 * method according to the supplied
 * object's properties and returns
 * the builder function.
 *
 * @param {Object} options The object containing
 *                         the authentication data
 * @return {?Function} The builder function for
 *                     the Authentication method
 * @private
 */
const strategyBuilder = cond([
  [both(has('email'), has('password')), login.build],
  [has('api_key'), api.build],
  [has('encryption_key'), encryption.build],
  [has('session_id'), sessionId.build],
  [allPass([has('account_id'), has('jwt'), has('merchant_id')]), jwt.build],
  [allPass([has('jwt'), has('company_id')]), jwt.build],
  [T, rejectInvalidAuthObject],
])
 
/**
 * Finds and resolves to a builder
 * function for authentication
 * according to the supplied object.
 *
 * @param {Object} options The object containing
 *                         the authentication data
 * @returns {Promise} Resolves to either the
 *                    correct builder function
 *                    or rejects with an Error.
 */
function find (options) {
  if (isNil(options)) {
    return rejectInvalidAuthObject()
  }
 
  if (and(has('api_key', options), isBrowserEnvironment)) {
    return rejectAPIKeyOnBrowser()
  }
 
  return Promise.resolve(strategyBuilder(options))
}
 
export default { find }