Source

services/auth-service.js

import { formatDatetimeWithSeconds } from '@/utils/dates.js'
import api from '@/api'
import { getNestedValue } from '@/utils/object'
import { getQueryStringValue } from '@/utils/querystring'
import APIUrls from '@/config/simpliciti-apis.js'
import localforageWrapper from '@/utils/cache'
const shouldLog =
  (getQueryStringValue('verbose') || '').includes('1') ||
  (getQueryStringValue('verbose') || '').includes('auth')

/**
 * Used by dev to login quicky into a view
 * @param {*} jwt
 * @param {String} viewPath ig diagnostics
 */
export function loginWithToken(jwt, viewPath = '') {
  localforageWrapper
    .setItem('user_infos', {
      token: jwt,
    })
    .then(() => {
      window.location.href = window.location.origin + '/#/' + viewPath
      window.location.reload()
    })
}

/**
 *
 * @param {*} jwt api jwt need to be supplied manually (i.g: nested login as)
 * @param {*} clientId
 * @param {*} userId
 * @returns
 */
export async function getClientLoginAsToken(jwt, clientId, userId = null) {
  return (
    (
      (
        await api.v3.get(
          `${APIUrls.APIV3_USER_LOGIN_AS}?childClientId=${clientId}${
            userId ? '&userId=' + userId : ''
          }`,
          {},
          {
            jwt,
          }
        )
      ).data || {}
    ).token || ''
  )
}

export async function getClientUsers(clientId) {
  return (
    await api.v3.get(`${APIUrls.APIV3_USER_ACTIVITY}?clientId=${clientId}`)
  ).data.map((apiItem) => ({
    id: apiItem.userId,
    name: apiItem.userName,
    login: apiItem.login,
    lastActivityAt: formatDatetimeWithSeconds(new Date(apiItem.lastActivityAt)),
    lastConnectionAt: formatDatetimeWithSeconds(
      new Date(apiItem.lastConnectionAt)
    ),
  }))
}

/**
 * @todo Replace with getAPIV3Pooling
 * Fetch client childs (clients) from current user progressively
 * @param {Function} callback Called each time a response is finish. Return false to abort operation.
 * @param {Object} options axios wrapper get options
 * @returns
 */
export function getClientChildsClientsProgressively(callback, options = {}) {
  callback =
    callback ||
    ((data) => console.log(`getClientChildsClientsProgressively`, { data }))
  return new Promise((resolve, reject) => {
    let items = []
    async function fetchClientChilds(uri) {
      let data = (
        await api.v3.get(
          uri,
          {},
          {
            headers: {
              Accept: 'application/hal+json',
            },
            ...options,
          }
        )
      ).data
      let newItems = getNestedValue(data, '_embedded.item', [])
        .map((apiItem) => {
          return {
            id: apiItem.clientId2,
            name: apiItem.clientName2,
          }
        })
        .filter((item) => item.name.toLowerCase() !== 'sabatier')
      items = items.concat(newItems)
      let shouldAbort = callback(newItems) === false
      let isLastPage =
        !data?._links?.next?.href ||
        (data?._links?.self?.href || '') == (data?._links?.last?.href || '')

      shouldLog &&
        console.log('getClientChildsProgressively', {
          isLastPage,
          shouldAbort,
        })

      if (isLastPage || shouldAbort) {
        shouldLog &&
          console.log('getClientChildsProgressively:resolved', {
            items,
          })
        resolve(items)
      } else {
        fetchClientChilds(data._links.next.href).catch(reject)
      }
    }
    fetchClientChilds(
      `${APIUrls.APIV3_CLIENT_HIRERARCHIES}?page=1&itemsPerPage=100`
    ).catch(reject)
  })
}

/**
 * Used by settings store to cache settings parameters
 * @param {*} loginName
 * @param {*} clientId
 * @returns {String} encoded string
 */
export function encodeLoginNameClientId(loginName, clientId) {
  return window.btoa(loginName + '_' + clientId)
}

/**
 * @todo Refactor/Move into client-service
 * @param {*} key
 * @param {*} getOptions
 * @returns
 */
export async function getClientParameter(key, getOptions = {}) {
  let query = `parameter=${key}`
  return await api.v3
    .get(`${APIUrls.APIV3_CLIENT_PARAMETERS}?${query}`, {}, getOptions)
    .then((response) => {
      return (
        response.data && response.data.length >= 1 && response.data[0].value
      )
    })
}

/**
 * Grab logo client from APIV3
 * @param {Object} getOptions AXIOS options (Optional)
 * @returns {String} base64 or defaultValue
 */
export async function getClientLogoAsBase64(
  defaultValue = '',
  getOptions = {}
) {
  try {
    let response = await api.v3.get(
      APIUrls.APIV3_CLIENT_LOGOS,
      {
        page: 1,
        itemsPerPage: 1,
        'order[id]': 'desc',
      },
      getOptions
    )
    return (
      (response.data &&
        response.data.length >= 1 &&
        response.data[response.data.length - 1].content) ||
      defaultValue
    )
  } catch (err) {
    return defaultValue
  }
}