diff --git a/floriday.js b/floriday.js index 90c2856..67362c7 100644 --- a/floriday.js +++ b/floriday.js @@ -10,6 +10,7 @@ class Floriday { async start() { try { this.tokenExpirationDate = await utils.requestToken(models); + if (!env.API_KEY) throw new Error(`You haven't provided the API key`) if (JSON.parse(env.SYNC_SEQUENCE)) await utils.syncSequence(); if (JSON.parse(env.SYNC_SUPPLIER)) await utils.syncSuppliers(); if (JSON.parse(env.SYNC_CONN)) await utils.syncConn(); diff --git a/models/conf/clientConfig.js b/models/conf/clientConfig.js index f81ad31..8349cb0 100644 --- a/models/conf/clientConfig.js +++ b/models/conf/clientConfig.js @@ -12,14 +12,11 @@ const clientConfig = { clientSecret: { type: Sequelize.STRING, }, - requestLimit: { - type: Sequelize.INTEGER, - }, currentToken: { type: Sequelize.STRING(2000), }, tokenExpiration: { - type: Sequelize.STRING, + type: Sequelize.DATE, }, }; diff --git a/models/index.js b/models/index.js index f8cc8f1..304d6fa 100644 --- a/models/index.js +++ b/models/index.js @@ -2,9 +2,11 @@ import { Sequelize } from 'sequelize'; import dotenv from 'dotenv'; import chalk from 'chalk'; import ora from 'ora'; -import { criticalError } from './../utils.js'; +import { criticalError, updateClientConfig } from './../utils.js'; dotenv.config(); +const env = process.env; + console.clear() console.log(chalk.hex('#06c581')( ` @@ -178,17 +180,6 @@ if (JSON.parse(process.env.FORCE_SYNC)) { const modSpinner = ora(`${action} models...`).start(); try { await sequelize.sync({ force: isForce }); - if (process.env.SECRETS) { - await models.clientConfig.findOrCreate({ - where: { - id: 1, - }, - defaults: { - clientId: process.env.CLIENT_ID, - clientSecret: process.env.CLIENT_SECRET, - }, - }); - } modSpinner.succeed(); } catch (err) { diff --git a/utils.js b/utils.js index c2b0cc8..cb71606 100644 --- a/utils.js +++ b/utils.js @@ -13,61 +13,76 @@ const env = process.env; * @returns {Date} tokenExpirationDate formated as YYYY-MM-DD HH:mm:ss */ export async function requestToken() { - const clientConfigData = await models.clientConfig.findOne(); + let spinner; + try { + spinner = ora(`Requesting new token...`).start(); + + if (!env.CLIENT_ID || !env.CLIENT_SECRET) + throw new Error(`You haven't provided the credentials`) - if (!clientConfigData) - throw new Error('No data found in the client config table') - - const spinner = ora(`Requesting new token...`).start(); - const tokenExpirationDate = clientConfigData.tokenExpiration; - - if (clientConfigData.tokenExpiration == null || moment().isAfter(tokenExpirationDate)) { - let clientId = clientConfigData.clientId; - let clientSecret = clientConfigData.clientSecret; - - const data = { - grant_type: 'client_credentials', - client_id: clientId, - client_secret: clientSecret, - scope: 'role:app catalog:read supply:read organization:read network:write network:read' - }; - - const body = Object.keys(data) - .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`) - .join('&'); - - const response = await fetch(env.API_ENDPOINT, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - body, - }); - - const responseData = await response.json(); - - if (response.ok) { - spinner.succeed(); + const clientConfigData = await models.clientConfig.findOne(); + + let tokenExpirationDate; + if (clientConfigData) + tokenExpirationDate = clientConfigData.tokenExpiration; + + if (!tokenExpirationDate || moment().isAfter(tokenExpirationDate)) { + let clientId, clientSecret + if (JSON.parse(env.USE_SECRETS_DB)) { + clientId = clientConfigData.clientId; + clientSecret = clientConfigData.clientSecret; + } else { + clientId = env.CLIENT_ID + clientSecret = env.CLIENT_SECRET + }; + + const data = { + grant_type: 'client_credentials', + client_id: clientId, + client_secret: clientSecret, + scope: 'role:app catalog:read supply:read organization:read network:write network:read' + }; + + const body = Object.keys(data) + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`) + .join('&'); + + const response = await fetch(env.API_ENDPOINT, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body, + }); + + const responseData = await response.json(); + + if (response.ok) + spinner.succeed(); + else { + spinner.fail(); + criticalError(new Error(`Token request failed with status: ${response.status} - ${response.statusText}`)); + } + let tokenExpirationDate = moment() + .add(responseData.expires_in, 's') + .format('YYYY-MM-DD HH:mm:ss'); + + await updateClientConfig( + clientId, + clientSecret, + responseData.access_token, + tokenExpirationDate + ); + + return tokenExpirationDate; } else { - spinner.fail(); - criticalError(new Error(`Token request failed with status: ${response.status} - ${response.statusText}`)); + spinner.text = 'Using stored token...' + spinner.succeed(); + return tokenExpirationDate; } - let tokenExpirationDate = moment() - .add(responseData.expires_in, 's') - .format('YYYY-MM-DD HH:mm:ss'); - - await updateClientConfig( - clientId, - clientSecret, - responseData.access_token, - tokenExpirationDate - ); - - return tokenExpirationDate; - } else { - spinner.text = 'Using stored token...' - spinner.succeed(); - return tokenExpirationDate; + } catch (err) { + spinner.fail(); + throw err; } } @@ -94,29 +109,30 @@ export async function getCurrentTokenExpiration() { /** * Updates the Access Token in the client config table * - * @param {sequelize.models} models * @param {String} clientId * @param {String} clientSecret * @param {String} accessToken * @param {String} tokenExpirationDate */ export async function updateClientConfig(clientId, clientSecret, accessToken, tokenExpirationDate) { - try { - const spinner = ora(`Updating token...`).start(); - await models.clientConfig.upsert({ - id: 1, - clientId: clientId, - clientSecret: clientSecret, - currentToken: accessToken, - tokenExpiration: tokenExpirationDate, - requestLimit: 500, - }); - spinner.succeed(); - } catch (error) { - spinner.fail(); - console.log('There was a error while updating the client config'); - console.log(error); - } + try { + const spinner = ora(`Updating token...`).start(); + if (!JSON.parse(process.env.USE_SECRETS_DB)) + clientId = clientSecret = null + + await models.clientConfig.upsert({ + id: 1, + clientId: clientId, + clientSecret: clientSecret, + currentToken: accessToken, + tokenExpiration: tokenExpirationDate + }); + spinner.succeed(); + } catch (error) { + spinner.fail(); + console.log('There was a error while updating the client config'); + console.log(error); + } } /** @@ -325,9 +341,8 @@ export async function syncConn(){ let i = 1; for (let connection of connections){ spinner.text = `Syncing ${i++} connections...` - if (connection.isConnected == false){ + if (connection.isConnected == false) continue; - } let remoteConnection = remoteConnections.find(remoteConnection => remoteConnection == connection.organizationId); if (remoteConnection == undefined){ @@ -710,6 +725,6 @@ export async function insertItem(tradeItem, supplier) { * @param {err} **/ export async function criticalError(err) { - console.log(chalk.red.bold(`[ERROR]`), chalk.red(`${err.name}: ${err.message}`)); + console.log(chalk.red.bold(`[CRITICAL]`), chalk.red(`${err.message}`)); process.exit(); } \ No newline at end of file