Skip to content
Snippets Groups Projects
onDeleteAccount.js 8.09 MiB
Newer Older
    next(error);
  };
}

// TODO (v8 / #5257): Remove this
// eslint-disable-next-line deprecation/deprecation
;


//# sourceMappingURL=handlers.js.map


/***/ }),
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "extractRequestData": () => (/* binding */ extractRequestData),
/* harmony export */   "parseRequest": () => (/* binding */ parseRequest)
/* harmony export */ });
/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1705);


/**
 * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead.
 */

/**
 * Normalizes data from the request object, accounting for framework differences.
 *
 * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead.
 *
 * @param req The request object from which to extract data
 * @param keys An optional array of keys to include in the normalized data.
 * @returns An object containing normalized request data
 */
function extractRequestData(req, keys) {
  return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.extractRequestData)(req, { include: keys });
}

/**
 * Options deciding what parts of the request to use when enhancing an event
 *
 * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use
 * `AddRequestDataToEventOptions` in `@sentry/utils` instead.
 */

/**
 * Enriches passed event with request data.
 *
 * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead.
 *
 * @param event Will be mutated and enriched with req data
 * @param req Request object
 * @param options object containing flags to enable functionality
 * @hidden
 */
function parseRequest(event, req, options = {}) {
  return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent)(event, req, { include: options });
}


//# sourceMappingURL=requestDataDeprecated.js.map


/***/ }),
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "TRACEPARENT_REGEXP": () => (/* binding */ TRACEPARENT_REGEXP),
/* harmony export */   "extractTraceparentData": () => (/* binding */ extractTraceparentData)
/* harmony export */ });
const TRACEPARENT_REGEXP = new RegExp(
  '^[ \\t]*' + // whitespace
    '([0-9a-f]{32})?' + // trace_id
    '-?([0-9a-f]{16})?' + // span_id
    '-?([01])?' + // sampled
    '[ \\t]*$', // whitespace
);

/**
 * Extract transaction context data from a `sentry-trace` header.
 *
 * @param traceparent Traceparent string
 *
 * @returns Object containing data from the header, or undefined if traceparent string is malformed
 */
function extractTraceparentData(traceparent) {
  const matches = traceparent.match(TRACEPARENT_REGEXP);

  if (!traceparent || !matches) {
    // empty string or no matches is invalid traceparent data
    return undefined;
  }

  let parentSampled;
  if (matches[3] === '1') {
    parentSampled = true;
  } else if (matches[3] === '0') {
    parentSampled = false;
  }

  return {
    traceId: matches[1],
    parentSampled,
    parentSpanId: matches[2],
  };
}


//# sourceMappingURL=tracing.js.map


/***/ }),
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "FunctionToString": () => (/* reexport safe */ _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__.FunctionToString),
/* harmony export */   "InboundFilters": () => (/* reexport safe */ _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__.InboundFilters)
/* harmony export */ });
/* harmony import */ var _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1712);
/* harmony import */ var _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1711);


//# sourceMappingURL=index.js.map


/***/ }),
Hugo SUBTIL's avatar
Hugo SUBTIL committed
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

// @ts-check
const { log, errors } = __webpack_require__(1)
const soapRequest = __webpack_require__(1375)
const { parseTags, parseValue } = __webpack_require__(1599)
const { commanderArretServiceSouscritMesures } = __webpack_require__(1600)
const xml2js = __webpack_require__(1557)
const Sentry = __webpack_require__(1639)
Hugo SUBTIL's avatar
Hugo SUBTIL committed

/**
 * @param {string} url
 * @param {string} apiAuthKey
 * @param {string} appLogin
 * @param {number} pointId
 * @param {number} serviceId
 * @return {Promise<string>} User contractId
 */
async function terminateContract(
  url,
  apiAuthKey,
  appLogin,
  contractId,
  pointId,
  serviceId
) {
  log('info', 'terminateContract')
  const sgeHeaders = {
    'Content-Type': 'text/xml;charset=UTF-8',
    apikey: apiAuthKey,
  }

  const { response } = await soapRequest({
    url: `${url}/enedis_SGE_CommandeArretServiceSouscritMesures/1.0`,
    headers: sgeHeaders,
    xml: commanderArretServiceSouscritMesures(
      appLogin,
      contractId,
      pointId,
      serviceId
    ),
  }).catch(err => {
    log('error', 'commanderArretServiceSouscritMesures')
    log('error', err)
    Sentry.captureException('commanderArretServiceSouscritMesures', err)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
    throw errors.VENDOR_DOWN
  })

  const parsedReply = await xml2js.parseStringPromise(response.body, {
    tagNameProcessors: [parseTags],
    valueProcessors: [parseValue],
    explicitArray: false,
  })

  try {
    // We don't need any action on reply for now
    if (parsedReply.Envelope.Body.Fault) {
      log(
        'error',
        `Enedis issue ${parsedReply.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${parsedReply.Envelope.Body.Fault.faultstring}`
      )
    }
    return parsedReply
  } catch (error) {
    const errorMessage =
      'Error while parsing user contract termination: ' + error
    log('error', errorMessage)
    log('error', `Enedis issue ${JSON.stringify(parsedReply.Envelope.Body)}`)
    Sentry.captureException(errorMessage)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
    throw errors.VENDOR_DOWN
  }
}

module.exports = { terminateContract }


/***/ }),
/* 1723 */,
/* 1724 */,
/* 1725 */,
/* 1726 */,
/* 1727 */,
/* 1728 */,
/* 1729 */
Hugo SUBTIL's avatar
Hugo SUBTIL committed
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { log, updateOrCreate } = __webpack_require__(1)
const { isLocal } = __webpack_require__(1730)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
const cozyClient = __webpack_require__(485)

async function saveAccountData(accountId, accountData) {
  log('info', `saveAccountData: ${accountId}`)

  let account = await getAccount(accountId)
  log('info', `saveAccountData account: ${JSON.stringify(account)}`)
  log(
    'info',
    `saveAccountData account: ${JSON.stringify({
      ...account,
      data: accountData,
    })}`
  )
  log(
    'info',
    `saveAccountData account after id: ${JSON.stringify({
      ...account,
      data: accountData,
    })}`
  )
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  account = await updateOrCreate(
    [{ ...account, data: accountData }],
    'io.cozy.accounts',
    ['account_type']
  log('info', `saveAccountData account reply: ${JSON.stringify(account)}`)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  return account
}

/**
 * Return account
 * @param {string} accountId
 * @returns {Account}
 */
Hugo SUBTIL's avatar
Hugo SUBTIL committed
async function getAccount(accountId) {
  log('info', `getAccount: ${accountId}`)
  const accounts = await cozyClient.data.findAll('io.cozy.accounts')
  return accounts.filter(account =>
    isLocal() ? account._id === accountId : account.account_type === accountId
async function getAccountForDelete(accountId, accountRev) {
  log('info', `getAccountForDelete: ${accountId} ${accountRev}`)
  const body = await cozyClient.fetchJSON(
    'GET',
    `/data/io.cozy.accounts/${accountId}?rev=${accountRev}`
  )

  log('debug', `getAccountForDelete: ${body}`)
  return body
}

module.exports = { getAccount, saveAccountData, getAccountForDelete }
Hugo SUBTIL's avatar
Hugo SUBTIL committed
/***/ ((module) => {

function isLocal() {
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  return (
    process.env.NODE_ENV === 'development' ||
    process.env.NODE_ENV === 'local' ||
    process.env.NODE_ENV === 'standalone'
  )
}

/**
 * Verify if it's an alpha URL
 * @returns {boolean}
 */
function isDev() {
  return (
    process.env.COZY_URL.includes('alpha') ||
    process.env.COZY_URL.includes('cozy.tools')
  )
}

module.exports = { isLocal, isDev }
/* 1731 */,
/* 1732 */,
/* 1733 */,
/* 1734 */,
/* 1735 */,
/* 1736 */,
/* 1737 */,
/* 1738 */,
/* 1739 */,
/* 1740 */,
/* 1741 */,
/* 1742 */,
/* 1743 */,
/* 1744 */,
/* 1745 */,
/* 1746 */,
/* 1747 */,
/* 1748 */,
/* 1749 */,
/* 1750 */,
/* 1751 */,
/* 1752 */,
/* 1753 */,
/* 1754 */,
/* 1755 */,
/* 1756 */,
/* 1757 */,
/* 1758 */,
/* 1759 */,
/* 1760 */,
/* 1761 */,
/* 1762 */,
/* 1763 */,
/* 1764 */,
/* 1765 */,
/* 1766 */,
/* 1767 */,
/* 1768 */,
/* 1769 */
Hugo SUBTIL's avatar
Hugo SUBTIL committed
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

// @ts-check
const { log, errors } = __webpack_require__(1)
const {
  getAccountRev,
  getAccountSecret,
  getAccountId,
} = __webpack_require__(1770)
const { getBoConsent, deleteBoConsent } = __webpack_require__(1601)
const { terminateContract } = __webpack_require__(1722)
const { getAccountForDelete } = __webpack_require__(1729)
const moment = __webpack_require__(1417)
__webpack_require__(1554)
const { isLocal, isDev } = __webpack_require__(1730)
const Sentry = __webpack_require__(1639)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
moment.locale('fr') // set the language
moment.tz.setDefault('Europe/Paris') // set the timezone

async function onDeleteAccount() {
  try {
    log('info', 'Deleting account ...')
    log('info', 'Getting secrets ...')
    const ACCOUNT_ID = getAccountId()
    const accountRev = getAccountRev()

    if (accountRev) {
      log('info', 'Account rev exist')
      const accountData = await getAccountForDelete(ACCOUNT_ID, accountRev)
      // Parse local info for deletion test
      if (isLocal()) {
        log('warn', 'Local run')
        const fields = JSON.parse(
          process.env.COZY_FIELDS ? process.env.COZY_FIELDS : '{}'
        )
        process.env.COZY_FIELDS = JSON.stringify({
          ...fields,
          ...accountData.auth,
        })
      }
      const secrets = getAccountSecret()
      const userConsent = await getBoConsent(
        secrets.boBaseUrl,
        secrets.boToken,
        accountData.data.consentId
      )
      log('info', `isAlpha: ${isDev()}`)
      log('info', `userConsent: ${JSON.stringify(userConsent)}`)
      if (userConsent.ID && userConsent.pointID) {
        log('log', `Consent ${userConsent.ID} found for user`)
        if (userConsent.serviceID) {
          await deleteBoConsent(
            secrets.boBaseUrl,
            secrets.boToken,
            userConsent.ID
          // Verify if it's dev env to prevent delete of real data
          if (!isDev()) {
            await terminateContract(
              secrets.wso2BaseUrl,
              secrets.apiToken,
              secrets.sgeLogin,
              secrets.contractId,
              userConsent.pointID,
              userConsent.serviceID
            )
          }
        } else {
          const errorMessage = `No service id retrieved from BO`
          log('error', errorMessage)
          Sentry.captureException(errorMessage)
          throw errors.VENDOR_DOWN
      log('info', 'Deleting account succeed')
    } else {
      const errorMessage =
        'No account revision was found, something went wrong during the deletion of said account'
      log('error', errorMessage)
      Sentry.captureException(errorMessage)
      throw errors.VENDOR_DOWN
    }
  } catch (error) {
    log('debug', 'error catched in onDeleteAccount()', error)
    await Sentry.flush()
    throw error
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  }
}

onDeleteAccount().then(
  () => {
    log('info', `onDeleteAccount: Successfully delete consent and account.`)
  },
  err => {
    const errorMessage = `onDeleteAccount: An error occurred during script: ${err.message}`
    log('error', errorMessage)
    Sentry.captureException(errorMessage)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
    throw errors.VENDOR_DOWN
  }
)

module.exports = { onDeleteAccount }


/***/ }),
Hugo SUBTIL's avatar
Hugo SUBTIL committed
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { log } = __webpack_require__(1)
const { isLocal } = __webpack_require__(1730)
const Sentry = __webpack_require__(1639)
Hugo SUBTIL's avatar
Hugo SUBTIL committed

function getAccountId() {
  log('info', `getAccountId`)
  try {
    return JSON.parse(process.env.COZY_FIELDS).account
  } catch (err) {
    const errorMessage = `You must provide 'account' in COZY_FIELDS: ${err.message}`
    Sentry.captureException(errorMessage)
    throw new Error(errorMessage)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  }
}

function getAccountRev() {
  log('info', `getAccountRev`)
  log('info', `getAccountRev: ${JSON.stringify(process.env.COZY_FIELDS)}`)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  try {
    return isLocal()
Hugo SUBTIL's avatar
Hugo SUBTIL committed
      ? 'fakeAccountRev'
      : JSON.parse(process.env.COZY_FIELDS).account_rev
  } catch (err) {
    const errorMessage = `You must provide 'account' in COZY_FIELDS: ${err.message}`
    Sentry.captureException(errorMessage)
    throw new Error(errorMessage)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  }
}

/**
 * Return account secrets.
 * For local testing, change value with values from your konnector-dev-config.json
Hugo SUBTIL's avatar
Hugo SUBTIL committed
 */
function getAccountSecret() {
  log('info', `getAccountSecret`)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  try {
    return isLocal()
      ? JSON.parse(process.env.COZY_FIELDS)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
      : JSON.parse(process.env.COZY_PARAMETERS).secret
  } catch (err) {
    const errorMessage = `You must provide 'account-types' in COZY_PARAMETERS: ${err.message}`
    Sentry.captureException(errorMessage)
    throw new Error(errorMessage)
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  }
}
module.exports = { getAccountId, getAccountRev, getAccountSecret }


/***/ })
/******/ 	]);
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			id: moduleId,
/******/ 			loaded: false,
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = __webpack_module_cache__;
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/harmony module decorator */
/******/ 	(() => {
/******/ 		__webpack_require__.hmd = (module) => {
/******/ 			module = Object.create(module);
/******/ 			if (!module.children) module.children = [];
/******/ 			Object.defineProperty(module, 'exports', {
/******/ 				enumerable: true,
/******/ 				set: () => {
/******/ 					throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);
/******/ 				}
/******/ 			});
/******/ 			return module;
/******/ 		};
/******/ 	})();
/******/ 	
Hugo SUBTIL's avatar
Hugo SUBTIL committed
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/node module decorator */
/******/ 	(() => {
/******/ 		__webpack_require__.nmd = (module) => {
/******/ 			module.paths = [];
/******/ 			if (!module.children) module.children = [];
/******/ 			return module;
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// module cache are used so entry inlining is disabled
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	var __webpack_exports__ = __webpack_require__(__webpack_require__.s = 1769);
Hugo SUBTIL's avatar
Hugo SUBTIL committed
/******/ 	
/******/ })()
;