diff --git a/integrationos-oauth/.eslintignore b/integrationos-oauth/.eslintignore new file mode 100644 index 00000000..7f4ccfe3 --- /dev/null +++ b/integrationos-oauth/.eslintignore @@ -0,0 +1,6 @@ +# don't ever lint node_modules +node_modules +# don't lint build output (make sure it's set to your correct build folder name) +build +# don't lint nyc coverage output +coverage diff --git a/integrationos-oauth/.eslintrc b/integrationos-oauth/.eslintrc new file mode 100644 index 00000000..5c639222 --- /dev/null +++ b/integrationos-oauth/.eslintrc @@ -0,0 +1,33 @@ +{ + "root": true, + "parser": "@typescript-eslint/parser", + "plugins": [ + "@typescript-eslint", + "prettier", + "jest" + ], + "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + "prettier" + ], + "rules": { + "no-console": [ + "error", + { + "allow": [ + "log", + "warn", + "error" + ] + } + ], + "@typescript-eslint/no-var-requires": "warn", + "prettier/prettier": 2 + }, + "env": { + "browser": true, + "node": true, + "jest/globals": true + } +} diff --git a/integrationos-oauth/.prettierrc b/integrationos-oauth/.prettierrc new file mode 100644 index 00000000..7de212b1 --- /dev/null +++ b/integrationos-oauth/.prettierrc @@ -0,0 +1,6 @@ +{ + "trailingComma": "all", + "singleQuote": true, + "printWidth": 80, + "tabWidth": 4 +} diff --git a/integrationos-oauth/package.json b/integrationos-oauth/package.json index 792dd146..18371c84 100644 --- a/integrationos-oauth/package.json +++ b/integrationos-oauth/package.json @@ -1,25 +1,42 @@ { - "name": "platform-oauth", - "version": "1.0.0", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "start": "ts-node src/index.ts", - "build": "tsc" - }, - "author": "@integrationos", - "license": "ISC", - "description": "", - "dependencies": { - "axios": "^1.7.2", - "dotenv": "^16.4.5", - "express": "^4.19.2", - "jsonwebtoken": "^9.0.2" - }, - "devDependencies": { - "@types/express": "^4.17.21", - "@types/jsonwebtoken": "^9.0.6", - "ts-node": "^10.9.2", - "typescript": "^5.4.5" - } + "name": "platform-oauth", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "ts-node src/index.ts", + "build": "tsc", + "lint": "eslint . --ext .ts", + "lint-fix": "eslint . --ext .ts --fix", + "prettier-format": "run-script-os", + "prettier-format:win32": "prettier --config .prettierrc \"./src/**/*.ts\" --write", + "prettier-format:darwin:linux": "prettier --config .prettierrc 'src/**/*.ts' --write", + "prettier-format:default": "prettier --config .prettierrc 'src/**/*.ts' --write", + "prettier-watch": "run-script-os", + "prettier-watch:win32": "onchange \"src/**/*.ts\" -- prettier --write {{changed}}", + "prettier-watch:darwin:linux": "onchange 'src/**/*.ts' -- prettier --write {{changed}}", + "prettier-watch:default": "onchange 'src/**/*.ts' -- prettier --write {{changed}}" + }, + "author": "@integrationos", + "license": "ISC", + "description": "", + "dependencies": { + "axios": "^1.7.2", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "jsonwebtoken": "^9.0.2" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/jsonwebtoken": "^9.0.6", + "ts-node": "^10.9.2", + "typescript": "^5.4.5", + "@typescript-eslint/eslint-plugin": "^5.31.0", + "@typescript-eslint/parser": "^5.31.0", + "eslint": "^8.20.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-jest": "^26.6.0", + "eslint-plugin-prettier": "^4.2.1", + "prettier": "^2.7.1" + } } diff --git a/integrationos-oauth/src/connections/attio/init.ts b/integrationos-oauth/src/connections/attio/init.ts index c255c13c..fdac47ac 100644 --- a/integrationos-oauth/src/connections/attio/init.ts +++ b/integrationos-oauth/src/connections/attio/init.ts @@ -1,46 +1,46 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const init = async ({ body }: DataObject): Promise => { - try { - const { - clientId, - clientSecret, - metadata: { code }, - } = body; + try { + const { + clientId, + clientSecret, + metadata: { code }, + } = body; - const baseUrl = `https://app.attio.com/oauth`; + const baseUrl = `https://app.attio.com/oauth`; - const requestBody = { - grant_type: "authorization_code", - code: code, - client_id: clientId, - client_secret: clientSecret, - }; + const requestBody = { + grant_type: 'authorization_code', + code: code, + client_id: clientId, + client_secret: clientSecret, + }; - const response = await axios({ - url: `${baseUrl}/token`, - method: "POST", - headers: { - "Content-Type": "application/x-www-form-urlencoded", - Accept: "application/json", - }, - data: qs.stringify(requestBody), - }); + const response = await axios({ + url: `${baseUrl}/token`, + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json', + }, + data: qs.stringify(requestBody), + }); - const { - data: { access_token: accessToken, token_type: tokenType }, - } = response; + const { + data: { access_token: accessToken, token_type: tokenType }, + } = response; - return { - accessToken, - refreshToken: accessToken, - expiresIn: 2147483647, - tokenType, - meta: {}, - }; - } catch (error) { - throw new Error(`Error fetching access token for Attio: ${error}`); - } + return { + accessToken, + refreshToken: accessToken, + expiresIn: 2147483647, + tokenType, + meta: {}, + }; + } catch (error) { + throw new Error(`Error fetching access token for Attio: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/attio/refresh.ts b/integrationos-oauth/src/connections/attio/refresh.ts index cc3c852c..1adeb479 100644 --- a/integrationos-oauth/src/connections/attio/refresh.ts +++ b/integrationos-oauth/src/connections/attio/refresh.ts @@ -1,18 +1,18 @@ -import { DataObject, OAuthResponse } from "../../lib/types"; +import { DataObject, OAuthResponse } from '../../lib/types'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_METADATA: { accessToken, refreshToken, tokenType, meta }, - } = body; - return { - accessToken, - refreshToken, - expiresIn: 2147483647, - tokenType, - meta, - }; - } catch (error) { - throw new Error(`Error fetching refresh token for Attio: ${error}`); - } + try { + const { + OAUTH_METADATA: { accessToken, refreshToken, tokenType, meta }, + } = body; + return { + accessToken, + refreshToken, + expiresIn: 2147483647, + tokenType, + meta, + }; + } catch (error) { + throw new Error(`Error fetching refresh token for Attio: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/clover/init.ts b/integrationos-oauth/src/connections/clover/init.ts index 17f94137..cf408cdb 100644 --- a/integrationos-oauth/src/connections/clover/init.ts +++ b/integrationos-oauth/src/connections/clover/init.ts @@ -1,19 +1,25 @@ -import axios from "axios"; +import axios from 'axios'; -import { DataObject, OAuthResponse } from "../../lib/types"; +import { DataObject, OAuthResponse } from '../../lib/types'; export const init = async ({ body }: DataObject): Promise => { try { const requestBody = { - grant_type: "authorization_code", + grant_type: 'authorization_code', code: body.metadata?.code, client_id: body.clientId, client_secret: body.clientSecret, }; - const baseUrl = body.metadata?.environment === "live" ? "https://api.clover.com" : "https://sandbox.dev.clover.com"; + const baseUrl = + body.metadata?.environment === 'live' + ? 'https://api.clover.com' + : 'https://sandbox.dev.clover.com'; - const response = await axios.post(`${baseUrl}/oauth/token`, requestBody); + const response = await axios.post( + `${baseUrl}/oauth/token`, + requestBody, + ); const accessToken = response.data?.access_token; @@ -21,14 +27,14 @@ export const init = async ({ body }: DataObject): Promise => { accessToken, refreshToken: accessToken, expiresIn: 2147483647, - tokenType: "Bearer", + tokenType: 'Bearer', meta: { merchantId: body.metadata?.additionalData?.merchant_id, employeeId: body.metadata?.additionalData?.employee_id, - baseUrl - } + baseUrl, + }, }; } catch (error) { throw new Error(`Error fetching access token for Clover: ${error}`); } -}; \ No newline at end of file +}; diff --git a/integrationos-oauth/src/connections/clover/refresh.ts b/integrationos-oauth/src/connections/clover/refresh.ts index 37cd3fd7..f6db9843 100644 --- a/integrationos-oauth/src/connections/clover/refresh.ts +++ b/integrationos-oauth/src/connections/clover/refresh.ts @@ -1,4 +1,4 @@ -import { OAuthResponse } from "../../lib/types"; +import { OAuthResponse } from '../../lib/types'; export const refresh = async (payload: any): Promise => { return { @@ -6,6 +6,6 @@ export const refresh = async (payload: any): Promise => { refreshToken: payload.refreshToken, expiresIn: payload.expiresIn, tokenType: payload.tokenType, - meta: payload.meta + meta: payload.meta, }; }; diff --git a/integrationos-oauth/src/connections/freshbooks/init.ts b/integrationos-oauth/src/connections/freshbooks/init.ts index 194a33c6..ee43de69 100644 --- a/integrationos-oauth/src/connections/freshbooks/init.ts +++ b/integrationos-oauth/src/connections/freshbooks/init.ts @@ -1,58 +1,58 @@ -import axios from "axios"; +import axios from 'axios'; -import { DataObject, OAuthResponse } from "../../lib/types"; +import { DataObject, OAuthResponse } from '../../lib/types'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - grant_type: "authorization_code", - code: body.metadata?.code, - client_id: body.clientId, - client_secret: body.clientSecret, - redirect_uri: body.metadata?.redirectUri, - }; - - const response = await axios.post( - `https://api.freshbooks.com/auth/oauth/token`, - requestBody - ); - - const { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - } = response.data; - - // Get Additional Information required by hitting me URL - const additionalData = await axios.get( - "https://api.freshbooks.com/auth/api/v1/users/me", - { - headers: { - Authorization: `${tokenType} ${accessToken}`, - }, - } - ); - - if (!additionalData?.data) { - throw new Error(`Access token validation failed.`); + try { + const requestBody = { + grant_type: 'authorization_code', + code: body.metadata?.code, + client_id: body.clientId, + client_secret: body.clientSecret, + redirect_uri: body.metadata?.redirectUri, + }; + + const response = await axios.post( + `https://api.freshbooks.com/auth/oauth/token`, + requestBody, + ); + + const { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + } = response.data; + + // Get Additional Information required by hitting me URL + const additionalData = await axios.get( + 'https://api.freshbooks.com/auth/api/v1/users/me', + { + headers: { + Authorization: `${tokenType} ${accessToken}`, + }, + }, + ); + + if (!additionalData?.data) { + throw new Error(`Access token validation failed.`); + } + + const { + business: { business_uuid: businessId, account_id: accountId }, + } = additionalData.data.response.business_memberships[0]; + + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + businessId, + accountId, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Freshbooks: ${error}`); } - - const { - business: { business_uuid: businessId, account_id: accountId }, - } = additionalData.data.response.business_memberships[0]; - - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - businessId, - accountId, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Freshbooks: ${error}`); - } }; diff --git a/integrationos-oauth/src/connections/freshbooks/refresh.ts b/integrationos-oauth/src/connections/freshbooks/refresh.ts index 215299cd..b500996e 100644 --- a/integrationos-oauth/src/connections/freshbooks/refresh.ts +++ b/integrationos-oauth/src/connections/freshbooks/refresh.ts @@ -1,67 +1,65 @@ -import axios from "axios"; +import axios from 'axios'; -import { DataObject, OAuthResponse } from "../../lib/types"; +import { DataObject, OAuthResponse } from '../../lib/types'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token, - OAUTH_REQUEST_PAYLOAD: { redirectUri: redirect_uri }, - } = body; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + OAUTH_REQUEST_PAYLOAD: { redirectUri: redirect_uri }, + } = body; - const requestBody = { - grant_type: "refresh_token", - client_id, - refresh_token, - client_secret, - redirect_uri, - }; + const requestBody = { + grant_type: 'refresh_token', + client_id, + refresh_token, + client_secret, + redirect_uri, + }; - const response = await axios.post( - `https://api.freshbooks.com/auth/oauth/token`, - requestBody - ); + const response = await axios.post( + `https://api.freshbooks.com/auth/oauth/token`, + requestBody, + ); - const { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - } = response.data; + const { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + } = response.data; - // Get Additional Information required by hitting me URL - const additionalData = await axios.get( - "https://api.freshbooks.com/auth/api/v1/users/me", - { - headers: { - Authorization: `${tokenType} ${accessToken}`, - }, - } - ); + // Get Additional Information required by hitting me URL + const additionalData = await axios.get( + 'https://api.freshbooks.com/auth/api/v1/users/me', + { + headers: { + Authorization: `${tokenType} ${accessToken}`, + }, + }, + ); - if (!additionalData?.data) { - throw new Error(`Access token validation failed.`); - } + if (!additionalData?.data) { + throw new Error(`Access token validation failed.`); + } - const { - business: { business_uuid: businessId, account_id: accountId }, - } = additionalData.data.response.business_memberships[0]; + const { + business: { business_uuid: businessId, account_id: accountId }, + } = additionalData.data.response.business_memberships[0]; - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - businessId, - accountId, - }, - }; - } catch (error) { - throw new Error( - `Error fetching access token for Freshbooks: ${error}` - ); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + businessId, + accountId, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Freshbooks: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/front/init.ts b/integrationos-oauth/src/connections/front/init.ts index 9474e6c2..8b4f5dcb 100644 --- a/integrationos-oauth/src/connections/front/init.ts +++ b/integrationos-oauth/src/connections/front/init.ts @@ -1,39 +1,39 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { differenceInSeconds, generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { differenceInSeconds, generateBasicHeaders } from '../../lib/helpers'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - grant_type: "authorization_code", - code: body.metadata?.code, - redirect_uri: body.metadata?.redirectUri, - }; + try { + const requestBody = { + grant_type: 'authorization_code', + code: body.metadata?.code, + redirect_uri: body.metadata?.redirectUri, + }; - const response = await axios.post( - "https://app.frontapp.com/oauth/token", - requestBody, - { - headers: generateBasicHeaders(body.clientId, body.clientSecret), - } - ); + const response = await axios.post( + 'https://app.frontapp.com/oauth/token', + requestBody, + { + headers: generateBasicHeaders(body.clientId, body.clientSecret), + }, + ); - const { - access_token: accessToken, - refresh_token: refreshToken, - expires_at: expiresAt, - token_type: tokenType, - } = response.data; + const { + access_token: accessToken, + refresh_token: refreshToken, + expires_at: expiresAt, + token_type: tokenType, + } = response.data; - return { - accessToken, - refreshToken, - // Converting expiresAt to date object and getting difference in seconds - expiresIn: differenceInSeconds(new Date(expiresAt * 1000)), - tokenType, - meta: {}, - }; - } catch (error) { - throw new Error(`Error fetching access token for Front: ${error}`); - } + return { + accessToken, + refreshToken, + // Converting expiresAt to date object and getting difference in seconds + expiresIn: differenceInSeconds(new Date(expiresAt * 1000)), + tokenType, + meta: {}, + }; + } catch (error) { + throw new Error(`Error fetching access token for Front: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/front/refresh.ts b/integrationos-oauth/src/connections/front/refresh.ts index ddc80826..2f9af4e5 100644 --- a/integrationos-oauth/src/connections/front/refresh.ts +++ b/integrationos-oauth/src/connections/front/refresh.ts @@ -1,46 +1,46 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { differenceInSeconds, generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { differenceInSeconds, generateBasicHeaders } from '../../lib/helpers'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token, - } = body; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + } = body; - const requestBody = { - grant_type: "refresh_token", - refresh_token, - }; + const requestBody = { + grant_type: 'refresh_token', + refresh_token, + }; - const response = await axios.post( - "https://app.frontapp.com/oauth/token", - requestBody, - { - headers: generateBasicHeaders(client_id, client_secret), - } - ); + const response = await axios.post( + 'https://app.frontapp.com/oauth/token', + requestBody, + { + headers: generateBasicHeaders(client_id, client_secret), + }, + ); - const { - access_token: accessToken, - refresh_token: refreshToken, - expires_at: expiresAt, - token_type: tokenType, - } = response.data; + const { + access_token: accessToken, + refresh_token: refreshToken, + expires_at: expiresAt, + token_type: tokenType, + } = response.data; - return { - accessToken, - refreshToken, - // Converting expiresAt to date object and getting difference in seconds - expiresIn: differenceInSeconds(new Date(expiresAt * 1000)), - tokenType, - meta: { - ...body?.OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error(`Error fetching refresh token for Front: ${error}`); - } + return { + accessToken, + refreshToken, + // Converting expiresAt to date object and getting difference in seconds + expiresIn: differenceInSeconds(new Date(expiresAt * 1000)), + tokenType, + meta: { + ...body?.OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error(`Error fetching refresh token for Front: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/microsoftDynamics365BusinessCentral/init.ts b/integrationos-oauth/src/connections/microsoftDynamics365BusinessCentral/init.ts index 7745ac48..70541cf0 100644 --- a/integrationos-oauth/src/connections/microsoftDynamics365BusinessCentral/init.ts +++ b/integrationos-oauth/src/connections/microsoftDynamics365BusinessCentral/init.ts @@ -1,50 +1,50 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - grant_type: "client_credentials", - client_id: body.clientId, - client_secret: body.clientSecret, - scope: "https://api.businesscentral.dynamics.com/.default", - }; + try { + const requestBody = { + grant_type: 'client_credentials', + client_id: body.clientId, + client_secret: body.clientSecret, + scope: 'https://api.businesscentral.dynamics.com/.default', + }; - const response = await axios({ - url: `https://login.microsoftonline.com/${body.metadata?.formData?.BUSINESS_CENTRAL_TENANT_ID}/oauth2/v2.0/token`, - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - data: qs.stringify(requestBody), - }); + const response = await axios({ + url: `https://login.microsoftonline.com/${body.metadata?.formData?.BUSINESS_CENTRAL_TENANT_ID}/oauth2/v2.0/token`, + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(requestBody), + }); - const { - data: { access_token, expires_in, token_type }, - } = response; + const { + data: { access_token, expires_in, token_type }, + } = response; - const companiesURL = `https://api.businesscentral.dynamics.com/v2.0/${body.metadata?.formData?.ENVIRONMENT_NAME}/api/v2.0/companies`; + const companiesURL = `https://api.businesscentral.dynamics.com/v2.0/${body.metadata?.formData?.ENVIRONMENT_NAME}/api/v2.0/companies`; - const companies = await axios.get(companiesURL, { - headers: { - Authorization: `Bearer ${access_token}`, - }, - }); + const companies = await axios.get(companiesURL, { + headers: { + Authorization: `Bearer ${access_token}`, + }, + }); - const { - data: { value: companiesData }, - } = companies; - const companyId = companiesData[0].id; + const { + data: { value: companiesData }, + } = companies; + const companyId = companiesData[0].id; - return { - accessToken: access_token, - refreshToken: "", - expiresIn: +expires_in, - tokenType: token_type, - meta: { companyId }, - }; - } catch (error) { - throw new Error( - `Error fetching access token for Microsoft Dynamics 365 Business Central: ${error}` - ); - } + return { + accessToken: access_token, + refreshToken: '', + expiresIn: +expires_in, + tokenType: token_type, + meta: { companyId }, + }; + } catch (error) { + throw new Error( + `Error fetching access token for Microsoft Dynamics 365 Business Central: ${error}`, + ); + } }; diff --git a/integrationos-oauth/src/connections/microsoftDynamics365BusinessCentral/refresh.ts b/integrationos-oauth/src/connections/microsoftDynamics365BusinessCentral/refresh.ts index b2dca7e4..dddbf99e 100644 --- a/integrationos-oauth/src/connections/microsoftDynamics365BusinessCentral/refresh.ts +++ b/integrationos-oauth/src/connections/microsoftDynamics365BusinessCentral/refresh.ts @@ -1,45 +1,45 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REQUEST_PAYLOAD: { formData }, - OAUTH_METADATA, - } = body; - const requestBody = { - grant_type: "client_credentials", - client_id, - client_secret, - scope: "https://api.businesscentral.dynamics.com/.default", - }; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REQUEST_PAYLOAD: { formData }, + OAUTH_METADATA, + } = body; + const requestBody = { + grant_type: 'client_credentials', + client_id, + client_secret, + scope: 'https://api.businesscentral.dynamics.com/.default', + }; - const response = await axios({ - url: `https://login.microsoftonline.com/${formData?.BUSINESS_CENTRAL_TENANT_ID}/oauth2/v2.0/token`, - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - data: qs.stringify(requestBody), - }); + const response = await axios({ + url: `https://login.microsoftonline.com/${formData?.BUSINESS_CENTRAL_TENANT_ID}/oauth2/v2.0/token`, + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(requestBody), + }); - const { - data: { access_token, expires_in, token_type }, - } = response; + const { + data: { access_token, expires_in, token_type }, + } = response; - return { - accessToken: access_token, - refreshToken: "", - expiresIn: +expires_in, - tokenType: token_type, - meta: { - ...OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error( - `Error fetching refresh token for Microsoft Dynamics 365 Business Central: ${error}` - ); - } + return { + accessToken: access_token, + refreshToken: '', + expiresIn: +expires_in, + tokenType: token_type, + meta: { + ...OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error( + `Error fetching refresh token for Microsoft Dynamics 365 Business Central: ${error}`, + ); + } }; diff --git a/integrationos-oauth/src/connections/microsoftDynamics365Sales/init.ts b/integrationos-oauth/src/connections/microsoftDynamics365Sales/init.ts index 792e4403..723d6dbd 100644 --- a/integrationos-oauth/src/connections/microsoftDynamics365Sales/init.ts +++ b/integrationos-oauth/src/connections/microsoftDynamics365Sales/init.ts @@ -1,40 +1,41 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - grant_type: "client_credentials", - client_id: body.clientId, - client_secret: body.clientSecret, - resource: - body.metadata?.formData?.MICROSOFT_DYNAMICS_365_SALES_ORGANIZATION_URI, - }; + try { + const requestBody = { + grant_type: 'client_credentials', + client_id: body.clientId, + client_secret: body.clientSecret, + resource: + body.metadata?.formData + ?.MICROSOFT_DYNAMICS_365_SALES_ORGANIZATION_URI, + }; - const response = await axios({ - url: `https://login.windows.net/${body.metadata?.formData?.MICROSOFT_DYNAMICS_365_SALES_TENANT_ID}/oauth2/token`, - method: "POST", - headers: { "content-type": "application/x-www-form-urlencoded" }, - data: qs.stringify(requestBody), - }); + const response = await axios({ + url: `https://login.windows.net/${body.metadata?.formData?.MICROSOFT_DYNAMICS_365_SALES_TENANT_ID}/oauth2/token`, + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(requestBody), + }); - const { - data: { access_token, expires_in, token_type, resource }, - } = response; + const { + data: { access_token, expires_in, token_type, resource }, + } = response; - return { - accessToken: access_token, - refreshToken: "", - expiresIn: +expires_in, - tokenType: token_type, - meta: { - resource, - }, - }; - } catch (error) { - throw new Error( - `Error fetching access token for Microsoft Dynamics 365 Sales: ${error}` - ); - } + return { + accessToken: access_token, + refreshToken: '', + expiresIn: +expires_in, + tokenType: token_type, + meta: { + resource, + }, + }; + } catch (error) { + throw new Error( + `Error fetching access token for Microsoft Dynamics 365 Sales: ${error}`, + ); + } }; diff --git a/integrationos-oauth/src/connections/microsoftDynamics365Sales/refresh.ts b/integrationos-oauth/src/connections/microsoftDynamics365Sales/refresh.ts index edf48e57..50d69ed2 100644 --- a/integrationos-oauth/src/connections/microsoftDynamics365Sales/refresh.ts +++ b/integrationos-oauth/src/connections/microsoftDynamics365Sales/refresh.ts @@ -1,45 +1,45 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REQUEST_PAYLOAD: { formData }, - OAUTH_METADATA, - } = body; - const requestBody = { - grant_type: "client_credentials", - client_id, - client_secret, - resource: formData?.MICROSOFT_DYNAMICS_365_SALES_ORGANIZATION_URI, - }; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REQUEST_PAYLOAD: { formData }, + OAUTH_METADATA, + } = body; + const requestBody = { + grant_type: 'client_credentials', + client_id, + client_secret, + resource: formData?.MICROSOFT_DYNAMICS_365_SALES_ORGANIZATION_URI, + }; - const response = await axios({ - url: `https://login.windows.net/${formData?.MICROSOFT_DYNAMICS_365_SALES_TENANT_ID}/oauth2/token`, - method: "POST", - headers: { "content-type": "application/x-www-form-urlencoded" }, - data: qs.stringify(requestBody), - }); + const response = await axios({ + url: `https://login.windows.net/${formData?.MICROSOFT_DYNAMICS_365_SALES_TENANT_ID}/oauth2/token`, + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(requestBody), + }); - const { - data: { access_token, expires_in, token_type }, - } = response; + const { + data: { access_token, expires_in, token_type }, + } = response; - return { - accessToken: access_token, - refreshToken: "", - expiresIn: +expires_in, - tokenType: token_type, - meta: { - ...OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error( - `Error fetching refresh token for Microsoft Dynamics 365 Sales: ${error}` - ); - } + return { + accessToken: access_token, + refreshToken: '', + expiresIn: +expires_in, + tokenType: token_type, + meta: { + ...OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error( + `Error fetching refresh token for Microsoft Dynamics 365 Sales: ${error}`, + ); + } }; diff --git a/integrationos-oauth/src/connections/netsuite/init.ts b/integrationos-oauth/src/connections/netsuite/init.ts index 04ac7469..c8864e90 100644 --- a/integrationos-oauth/src/connections/netsuite/init.ts +++ b/integrationos-oauth/src/connections/netsuite/init.ts @@ -1,50 +1,50 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { generateBasicHeaders } from '../../lib/helpers'; export const init = async ({ body }: DataObject): Promise => { - try { - const { - clientId: client_id, - clientSecret: client_secret, - metadata: { - code, - formData: { NETSUITE_ACCOUNT_ID }, - redirectUri: redirect_uri, - }, - } = body; + try { + const { + clientId: client_id, + clientSecret: client_secret, + metadata: { + code, + formData: { NETSUITE_ACCOUNT_ID }, + redirectUri: redirect_uri, + }, + } = body; - const requestBody = { - grant_type: "authorization_code", - code, - redirect_uri, - }; + const requestBody = { + grant_type: 'authorization_code', + code, + redirect_uri, + }; - const response = await axios({ - url: `https://${NETSUITE_ACCOUNT_ID}.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token`, - method: "POST", - headers: generateBasicHeaders(client_id, client_secret), - data: qs.stringify(requestBody), - }); + const response = await axios({ + url: `https://${NETSUITE_ACCOUNT_ID}.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token`, + method: 'POST', + headers: generateBasicHeaders(client_id, client_secret), + data: qs.stringify(requestBody), + }); - const { - data: { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - }, - } = response; + const { + data: { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + }, + } = response; - return { - accessToken, - refreshToken, - expiresIn: +expiresIn, - tokenType, - meta: {}, - }; - } catch (error) { - throw new Error(`Error fetching access token for Netsuite: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn: +expiresIn, + tokenType, + meta: {}, + }; + } catch (error) { + throw new Error(`Error fetching access token for Netsuite: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/netsuite/refresh.ts b/integrationos-oauth/src/connections/netsuite/refresh.ts index a12d067d..6ce2df28 100644 --- a/integrationos-oauth/src/connections/netsuite/refresh.ts +++ b/integrationos-oauth/src/connections/netsuite/refresh.ts @@ -1,49 +1,49 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { generateBasicHeaders } from '../../lib/helpers'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token, - OAUTH_REQUEST_PAYLOAD: { - formData: { NETSUITE_ACCOUNT_ID }, - }, - } = body; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + OAUTH_REQUEST_PAYLOAD: { + formData: { NETSUITE_ACCOUNT_ID }, + }, + } = body; - const requestBody = { - grant_type: "refresh_token", - refresh_token, - }; + const requestBody = { + grant_type: 'refresh_token', + refresh_token, + }; - const response = await axios({ - url: `https://${NETSUITE_ACCOUNT_ID}.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token`, - method: "POST", - headers: generateBasicHeaders(client_id, client_secret), - data: qs.stringify(requestBody), - }); + const response = await axios({ + url: `https://${NETSUITE_ACCOUNT_ID}.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token`, + method: 'POST', + headers: generateBasicHeaders(client_id, client_secret), + data: qs.stringify(requestBody), + }); - const { - data: { - access_token: accessToken, - expires_in: expiresIn, - token_type: tokenType, - }, - } = response; + const { + data: { + access_token: accessToken, + expires_in: expiresIn, + token_type: tokenType, + }, + } = response; - return { - accessToken, - refreshToken: refresh_token, - expiresIn: +expiresIn, - tokenType, - meta: { - ...body?.OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Netsuite: ${error}`); - } + return { + accessToken, + refreshToken: refresh_token, + expiresIn: +expiresIn, + tokenType, + meta: { + ...body?.OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Netsuite: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/pipedrive/init.ts b/integrationos-oauth/src/connections/pipedrive/init.ts index 33e1e241..0fa675e1 100644 --- a/integrationos-oauth/src/connections/pipedrive/init.ts +++ b/integrationos-oauth/src/connections/pipedrive/init.ts @@ -1,41 +1,41 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { generateBasicHeaders } from '../../lib/helpers'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - grant_type: "authorization_code", - code: body.metadata?.code, - redirect_uri: body.metadata?.redirectUri, - }; + try { + const requestBody = { + grant_type: 'authorization_code', + code: body.metadata?.code, + redirect_uri: body.metadata?.redirectUri, + }; - const response = await axios.post( - "https://oauth.pipedrive.com/oauth/token", - requestBody, - { - headers: generateBasicHeaders(body.clientId, body.clientSecret), - } - ); + const response = await axios.post( + 'https://oauth.pipedrive.com/oauth/token', + requestBody, + { + headers: generateBasicHeaders(body.clientId, body.clientSecret), + }, + ); - const { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - api_domain: apiDomain, - } = response.data; + const { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + api_domain: apiDomain, + } = response.data; - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - apiDomain, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Pipedrive: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + apiDomain, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Pipedrive: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/pipedrive/refresh.ts b/integrationos-oauth/src/connections/pipedrive/refresh.ts index 2203d3d2..864954d5 100644 --- a/integrationos-oauth/src/connections/pipedrive/refresh.ts +++ b/integrationos-oauth/src/connections/pipedrive/refresh.ts @@ -1,45 +1,45 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { generateBasicHeaders } from '../../lib/helpers'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token, - } = body; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + } = body; - const requestBody = { - grant_type: "refresh_token", - refresh_token, - }; + const requestBody = { + grant_type: 'refresh_token', + refresh_token, + }; - const response = await axios.post( - "https://oauth.pipedrive.com/oauth/token", - requestBody, - { - headers: generateBasicHeaders(client_id, client_secret), - } - ); + const response = await axios.post( + 'https://oauth.pipedrive.com/oauth/token', + requestBody, + { + headers: generateBasicHeaders(client_id, client_secret), + }, + ); - const { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - } = response.data; + const { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + } = response.data; - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - ...body?.OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error(`Error fetching refresh token for Pipedrive: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + ...body?.OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error(`Error fetching refresh token for Pipedrive: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/quickbooks/init.ts b/integrationos-oauth/src/connections/quickbooks/init.ts index 27c1a30f..185e98e6 100644 --- a/integrationos-oauth/src/connections/quickbooks/init.ts +++ b/integrationos-oauth/src/connections/quickbooks/init.ts @@ -1,48 +1,51 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { generateBasicHeaders } from '../../lib/helpers'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - grant_type: "authorization_code", - code: body.metadata?.code, - redirect_uri: body.metadata?.redirectUri, - }; + try { + const requestBody = { + grant_type: 'authorization_code', + code: body.metadata?.code, + redirect_uri: body.metadata?.redirectUri, + }; - const response = await axios.post( - "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer", - requestBody, - { - headers: { - ...generateBasicHeaders(body.clientId, body.clientSecret), - Accept: "application/json", - }, - } - ); + const response = await axios.post( + 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer', + requestBody, + { + headers: { + ...generateBasicHeaders(body.clientId, body.clientSecret), + Accept: 'application/json', + }, + }, + ); - const { - data: { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - }, - } = response; + const { + data: { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + }, + } = response; - const baseUrl = body.metadata?.environment === "live" ? "https://quickbooks.api.intuit.com" : "https://sandbox-quickbooks.api.intuit.com"; + const baseUrl = + body.metadata?.environment === 'live' + ? 'https://quickbooks.api.intuit.com' + : 'https://sandbox-quickbooks.api.intuit.com'; - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - realmId: body.metadata?.additionalData?.realmId, - baseUrl - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Quickbooks: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + realmId: body.metadata?.additionalData?.realmId, + baseUrl, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Quickbooks: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/quickbooks/refresh.ts b/integrationos-oauth/src/connections/quickbooks/refresh.ts index 13c18ff1..854f17de 100644 --- a/integrationos-oauth/src/connections/quickbooks/refresh.ts +++ b/integrationos-oauth/src/connections/quickbooks/refresh.ts @@ -1,50 +1,50 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { generateBasicHeaders } from '../../lib/helpers'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token, - } = body; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + } = body; - const requestBody = { - grant_type: "refresh_token", - refresh_token, - }; + const requestBody = { + grant_type: 'refresh_token', + refresh_token, + }; - const response = await axios.post( - "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer", - requestBody, - { - headers: { - ...generateBasicHeaders(client_id, client_secret), - Accept: "application/json", - }, - } - ); + const response = await axios.post( + 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer', + requestBody, + { + headers: { + ...generateBasicHeaders(client_id, client_secret), + Accept: 'application/json', + }, + }, + ); - const { - data: { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - }, - } = response; + const { + data: { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + }, + } = response; - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - ...body?.OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Quickbooks: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + ...body?.OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Quickbooks: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/sageAccounting/init.ts b/integrationos-oauth/src/connections/sageAccounting/init.ts index f048a0eb..b7692af4 100644 --- a/integrationos-oauth/src/connections/sageAccounting/init.ts +++ b/integrationos-oauth/src/connections/sageAccounting/init.ts @@ -1,40 +1,42 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - grant_type: "authorization_code", - code: body.metadata?.code, - client_id: body.clientId, - client_secret: body.clientSecret, - redirect_uri: body.metadata?.redirectUri, - }; + try { + const requestBody = { + grant_type: 'authorization_code', + code: body.metadata?.code, + client_id: body.clientId, + client_secret: body.clientSecret, + redirect_uri: body.metadata?.redirectUri, + }; - const response = await axios.post( - `https://oauth.accounting.sage.com/token`, - requestBody - ); + const response = await axios.post( + `https://oauth.accounting.sage.com/token`, + requestBody, + ); - const { - data: { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - requested_by_id: requestedById, - }, - } = response; + const { + data: { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + requested_by_id: requestedById, + }, + } = response; - return { - accessToken, - refreshToken, - expiresIn, - tokenType: '', - meta: { - requestedById, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for SageAccounting: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType: '', + meta: { + requestedById, + }, + }; + } catch (error) { + throw new Error( + `Error fetching access token for SageAccounting: ${error}`, + ); + } }; diff --git a/integrationos-oauth/src/connections/sageAccounting/refresh.ts b/integrationos-oauth/src/connections/sageAccounting/refresh.ts index dcc12935..b5bf9417 100644 --- a/integrationos-oauth/src/connections/sageAccounting/refresh.ts +++ b/integrationos-oauth/src/connections/sageAccounting/refresh.ts @@ -1,45 +1,47 @@ -import axios from "axios"; +import axios from 'axios'; -import { DataObject, OAuthResponse } from "../../lib/types"; +import { DataObject, OAuthResponse } from '../../lib/types'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token, - } = body; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + } = body; - const requestBody = { - grant_type: "refresh_token", - client_id, - client_secret, - refresh_token, - }; + const requestBody = { + grant_type: 'refresh_token', + client_id, + client_secret, + refresh_token, + }; - const response = await axios.post( - `https://oauth.accounting.sage.com/token`, - requestBody - ); + const response = await axios.post( + `https://oauth.accounting.sage.com/token`, + requestBody, + ); - const { - data: { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - requested_by_id: requestedById, - }, - } = response; + const { + data: { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + requested_by_id: requestedById, + }, + } = response; - return { - accessToken, - refreshToken, - expiresIn, - tokenType: "", - meta: { - requestedById, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for SageAccounting: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType: '', + meta: { + requestedById, + }, + }; + } catch (error) { + throw new Error( + `Error fetching access token for SageAccounting: ${error}`, + ); + } }; diff --git a/integrationos-oauth/src/connections/salesforce/init.ts b/integrationos-oauth/src/connections/salesforce/init.ts index ae962b10..7438eae7 100644 --- a/integrationos-oauth/src/connections/salesforce/init.ts +++ b/integrationos-oauth/src/connections/salesforce/init.ts @@ -1,111 +1,111 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { differenceInSeconds } from "../../lib/helpers"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { differenceInSeconds } from '../../lib/helpers'; const getListAllId = async (accessToken: string, url: string) => { - const response = await axios.get(url, { - headers: { - Authorization: `Bearer ${accessToken}`, - }, - }); - const { - data: { listviews }, - } = response; + const response = await axios.get(url, { + headers: { + Authorization: `Bearer ${accessToken}`, + }, + }); + const { + data: { listviews }, + } = response; - if (listviews?.length) { - const filteredListviews = listviews.filter((lv: any) => - lv.label.startsWith("All") - ); - if (filteredListviews.length) { - return filteredListviews[0].id; + if (listviews?.length) { + const filteredListviews = listviews.filter((lv: any) => + lv.label.startsWith('All'), + ); + if (filteredListviews.length) { + return filteredListviews[0].id; + } } - } - return null; + return null; }; export const init = async ({ body }: DataObject): Promise => { - try { - const { - clientId, - clientSecret, - metadata: { - code, - formData: { SALESFORCE_DOMAIN }, // Example: https://flow-fun-2719.my.salesforce.com - redirectUri, - }, - } = body; - const baseUrl = `${SALESFORCE_DOMAIN}/services/oauth2`; + try { + const { + clientId, + clientSecret, + metadata: { + code, + formData: { SALESFORCE_DOMAIN }, // Example: https://flow-fun-2719.my.salesforce.com + redirectUri, + }, + } = body; + const baseUrl = `${SALESFORCE_DOMAIN}/services/oauth2`; - const requestBody = { - grant_type: "authorization_code", - code, - redirect_uri: redirectUri, - client_id: body.clientId, - client_secret: body.clientSecret, - }; - const response = await axios({ - url: `${baseUrl}/token`, - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - data: qs.stringify(requestBody), - }); + const requestBody = { + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + client_id: body.clientId, + client_secret: body.clientSecret, + }; + const response = await axios({ + url: `${baseUrl}/token`, + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(requestBody), + }); - const { - data: { - access_token: accessToken, - refresh_token: refreshToken, - token_type: tokenType, - }, - } = response; + const { + data: { + access_token: accessToken, + refresh_token: refreshToken, + token_type: tokenType, + }, + } = response; - // Get expiry time through introspection - const introspection = await axios({ - url: `${baseUrl}/introspect`, - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - data: qs.stringify({ - client_id: clientId, - client_secret: clientSecret, - token: accessToken, - token_type_hint: "access_token", - }), - }); - const { - data: { exp: expiresAt }, - } = introspection; - // Converting expiresAt to date object and getting difference in seconds - const expiresIn = differenceInSeconds(new Date(expiresAt * 1000)); + // Get expiry time through introspection + const introspection = await axios({ + url: `${baseUrl}/introspect`, + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + data: qs.stringify({ + client_id: clientId, + client_secret: clientSecret, + token: accessToken, + token_type_hint: 'access_token', + }), + }); + const { + data: { exp: expiresAt }, + } = introspection; + // Converting expiresAt to date object and getting difference in seconds + const expiresIn = differenceInSeconds(new Date(expiresAt * 1000)); - // Get all listview ids and save in meta for getMany - const listViewBaseUrl = `${SALESFORCE_DOMAIN}/services/data/v61.0/sobjects`; - const contactListView = `${listViewBaseUrl}/contact/listviews`; - const opportunityListView = `${listViewBaseUrl}/opportunity/listviews`; - const leadListView = `${listViewBaseUrl}/lead/listviews`; - const accountListView = `${listViewBaseUrl}/account/listviews`; + // Get all listview ids and save in meta for getMany + const listViewBaseUrl = `${SALESFORCE_DOMAIN}/services/data/v61.0/sobjects`; + const contactListView = `${listViewBaseUrl}/contact/listviews`; + const opportunityListView = `${listViewBaseUrl}/opportunity/listviews`; + const leadListView = `${listViewBaseUrl}/lead/listviews`; + const accountListView = `${listViewBaseUrl}/account/listviews`; - const contactListId = await getListAllId(accessToken, contactListView); - const opportunityListId = await getListAllId( - accessToken, - opportunityListView - ); - const leadListId = await getListAllId(accessToken, leadListView); - const accountListId = await getListAllId(accessToken, accountListView); + const contactListId = await getListAllId(accessToken, contactListView); + const opportunityListId = await getListAllId( + accessToken, + opportunityListView, + ); + const leadListId = await getListAllId(accessToken, leadListView); + const accountListId = await getListAllId(accessToken, accountListView); - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - contactListId, - opportunityListId, - leadListId, - accountListId, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Salesforce: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + contactListId, + opportunityListId, + leadListId, + accountListId, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Salesforce: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/salesforce/refresh.ts b/integrationos-oauth/src/connections/salesforce/refresh.ts index 69df76a5..54883ad3 100644 --- a/integrationos-oauth/src/connections/salesforce/refresh.ts +++ b/integrationos-oauth/src/connections/salesforce/refresh.ts @@ -1,69 +1,71 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { differenceInSeconds, generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { differenceInSeconds, generateBasicHeaders } from '../../lib/helpers'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: clientId, - OAUTH_CLIENT_SECRET: clientSecret, - OAUTH_REFRESH_TOKEN: refresh_token, - OAUTH_REQUEST_PAYLOAD: { - formData: { SALESFORCE_DOMAIN }, - }, - OAUTH_METADATA, - } = body; - const baseUrl = `${SALESFORCE_DOMAIN}/services/oauth2`; + try { + const { + OAUTH_CLIENT_ID: clientId, + OAUTH_CLIENT_SECRET: clientSecret, + OAUTH_REFRESH_TOKEN: refresh_token, + OAUTH_REQUEST_PAYLOAD: { + formData: { SALESFORCE_DOMAIN }, + }, + OAUTH_METADATA, + } = body; + const baseUrl = `${SALESFORCE_DOMAIN}/services/oauth2`; - const requestBody = { - grant_type: "refresh_token", - refresh_token, - }; - const response = await axios({ - url: `${baseUrl}/token`, - method: "POST", - headers: generateBasicHeaders(clientId, clientSecret), - data: qs.stringify(requestBody), - }); + const requestBody = { + grant_type: 'refresh_token', + refresh_token, + }; + const response = await axios({ + url: `${baseUrl}/token`, + method: 'POST', + headers: generateBasicHeaders(clientId, clientSecret), + data: qs.stringify(requestBody), + }); - const { - data: { access_token: accessToken, token_type: tokenType }, - } = response; + const { + data: { access_token: accessToken, token_type: tokenType }, + } = response; - let refreshToken = refresh_token; - if (response.data.refresh_token) { - refreshToken = response.data.refresh_token; - } + let refreshToken = refresh_token; + if (response.data.refresh_token) { + refreshToken = response.data.refresh_token; + } - // Get expiry time through introspection - const introspection = await axios({ - url: `${baseUrl}/introspect`, - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - data: qs.stringify({ - client_id: clientId, - client_secret: clientSecret, - token: accessToken, - token_type_hint: "access_token", - }), - }); - const { - data: { exp: expiresAt }, - } = introspection; - // Converting expiresAt to date object and getting difference in seconds - const expiresIn = differenceInSeconds(new Date(expiresAt * 1000)); + // Get expiry time through introspection + const introspection = await axios({ + url: `${baseUrl}/introspect`, + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + data: qs.stringify({ + client_id: clientId, + client_secret: clientSecret, + token: accessToken, + token_type_hint: 'access_token', + }), + }); + const { + data: { exp: expiresAt }, + } = introspection; + // Converting expiresAt to date object and getting difference in seconds + const expiresIn = differenceInSeconds(new Date(expiresAt * 1000)); - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - ...OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error(`Error fetching refresh token for Salesforce: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + ...OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error( + `Error fetching refresh token for Salesforce: ${error}`, + ); + } }; diff --git a/integrationos-oauth/src/connections/slack/init.ts b/integrationos-oauth/src/connections/slack/init.ts index 9dcc8a2f..2248bbf7 100644 --- a/integrationos-oauth/src/connections/slack/init.ts +++ b/integrationos-oauth/src/connections/slack/init.ts @@ -1,48 +1,48 @@ -import axios from "axios"; -import qs from "qs"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import qs from 'qs'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - code: body.metadata?.code, - client_id: body.clientId, - client_secret: body.clientSecret, - redirect_uri: body.metadata?.redirectUri, - }; + try { + const requestBody = { + code: body.metadata?.code, + client_id: body.clientId, + client_secret: body.clientSecret, + redirect_uri: body.metadata?.redirectUri, + }; - const response = await axios({ - url: `https://slack.com/api/oauth.v2.access`, - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - data: qs.stringify(requestBody), - }); + const response = await axios({ + url: `https://slack.com/api/oauth.v2.access`, + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(requestBody), + }); - const { - data: { - access_token, - app_id: appId, - bot_user_id: botUserId, - team: { id: teamId, name: teamName }, - incoming_webhook: { channel, channel_id: channelId }, - }, - } = response; + const { + data: { + access_token, + app_id: appId, + bot_user_id: botUserId, + team: { id: teamId, name: teamName }, + incoming_webhook: { channel, channel_id: channelId }, + }, + } = response; - return { - accessToken: access_token, - refreshToken: access_token, - expiresIn: 2147483647, - tokenType: "Bearer", - meta: { - appId, - botUserId, - teamId, - teamName, - channel, - channelId, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Slack: ${error}`); - } + return { + accessToken: access_token, + refreshToken: access_token, + expiresIn: 2147483647, + tokenType: 'Bearer', + meta: { + appId, + botUserId, + teamId, + teamName, + channel, + channelId, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Slack: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/slack/refresh.ts b/integrationos-oauth/src/connections/slack/refresh.ts index e3b3d80b..9d91d207 100644 --- a/integrationos-oauth/src/connections/slack/refresh.ts +++ b/integrationos-oauth/src/connections/slack/refresh.ts @@ -1,15 +1,15 @@ -import { DataObject, OAuthResponse } from "../../lib/types"; +import { DataObject, OAuthResponse } from '../../lib/types'; export const refresh = async ({ body }: DataObject): Promise => { - try { - return { - accessToken: body?.OAUTH_METADATA?.accessToken, - refreshToken: body?.OAUTH_METADATA?.refreshToken, - expiresIn: body?.OAUTH_METADATA?.expiresIn, - tokenType: "Bearer", - meta: body?.OAUTH_METADATA?.meta, - }; - } catch (error) { - throw new Error(`Error fetching refresh token for Slack: ${error}`); - } + try { + return { + accessToken: body?.OAUTH_METADATA?.accessToken, + refreshToken: body?.OAUTH_METADATA?.refreshToken, + expiresIn: body?.OAUTH_METADATA?.expiresIn, + tokenType: 'Bearer', + meta: body?.OAUTH_METADATA?.meta, + }; + } catch (error) { + throw new Error(`Error fetching refresh token for Slack: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/square/init.ts b/integrationos-oauth/src/connections/square/init.ts index ff9569d1..47a31bee 100644 --- a/integrationos-oauth/src/connections/square/init.ts +++ b/integrationos-oauth/src/connections/square/init.ts @@ -1,12 +1,12 @@ -import axios from "axios"; +import axios from 'axios'; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { convertToTimestamp } from "../../lib/helpers"; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { convertToTimestamp } from '../../lib/helpers'; export const init = async ({ body }: DataObject): Promise => { try { const requestBody = { - grant_type: "authorization_code", + grant_type: 'authorization_code', code: body.metadata?.code, client_id: body.clientId, client_secret: body.clientSecret, @@ -14,9 +14,14 @@ export const init = async ({ body }: DataObject): Promise => { }; const isSandbox = body.clientId.startsWith('sandbox-'); - const baseURL = isSandbox ? 'https://connect.squareupsandbox.com' : 'https://connect.squareup.com'; + const baseURL = isSandbox + ? 'https://connect.squareupsandbox.com' + : 'https://connect.squareup.com'; - const response = await axios.post(`${baseURL}/oauth2/token`, requestBody); + const response = await axios.post( + `${baseURL}/oauth2/token`, + requestBody, + ); const { data: { @@ -25,22 +30,26 @@ export const init = async ({ body }: DataObject): Promise => { expires_at, token_type, merchant_id, - short_lived - } + short_lived, + }, } = response; return { accessToken: access_token, refreshToken: refresh_token, - expiresIn: Math.floor((await convertToTimestamp(expires_at) - (new Date().getTime())) / 1000), - tokenType: token_type === "bearer" ? "Bearer" : token_type, + expiresIn: Math.floor( + ((await convertToTimestamp(expires_at)) - + new Date().getTime()) / + 1000, + ), + tokenType: token_type === 'bearer' ? 'Bearer' : token_type, meta: { baseURL, merchantId: merchant_id, - shortLived: short_lived - } + shortLived: short_lived, + }, }; } catch (error) { throw new Error(`Error fetching access token for Square: ${error}`); } -}; \ No newline at end of file +}; diff --git a/integrationos-oauth/src/connections/square/refresh.ts b/integrationos-oauth/src/connections/square/refresh.ts index ee24b6ed..b9e4b9fa 100644 --- a/integrationos-oauth/src/connections/square/refresh.ts +++ b/integrationos-oauth/src/connections/square/refresh.ts @@ -1,27 +1,32 @@ -import axios from "axios"; +import axios from 'axios'; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { convertToTimestamp } from "../../lib/helpers"; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { convertToTimestamp } from '../../lib/helpers'; export const refresh = async ({ body }: DataObject): Promise => { try { const { OAUTH_CLIENT_ID: client_id, OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token + OAUTH_REFRESH_TOKEN: refresh_token, } = body; const requestBody = { - grant_type: "refresh_token", + grant_type: 'refresh_token', client_id, client_secret, refresh_token, }; const isSandbox = client_id.startsWith('sandbox-'); - const baseURL = isSandbox ? 'https://connect.squareupsandbox.com' : 'https://connect.squareup.com'; + const baseURL = isSandbox + ? 'https://connect.squareupsandbox.com' + : 'https://connect.squareup.com'; - const response = await axios.post(`${baseURL}/oauth2/token`, requestBody); + const response = await axios.post( + `${baseURL}/oauth2/token`, + requestBody, + ); const { data: { @@ -30,22 +35,25 @@ export const refresh = async ({ body }: DataObject): Promise => { expires_at: expiresAt, token_type: tokenType, merchant_id: merchantId, - short_lived: shortLived - } + short_lived: shortLived, + }, } = response; return { accessToken, refreshToken, - expiresIn: Math.floor((await convertToTimestamp(expiresAt) - new Date().getTime()) / 1000), - tokenType: tokenType === "bearer" ? "Bearer" : tokenType, + expiresIn: Math.floor( + ((await convertToTimestamp(expiresAt)) - new Date().getTime()) / + 1000, + ), + tokenType: tokenType === 'bearer' ? 'Bearer' : tokenType, meta: { baseURL, merchantId, - shortLived - } + shortLived, + }, }; } catch (error) { throw new Error(`Error fetching access token for Square: ${error}`); } -}; \ No newline at end of file +}; diff --git a/integrationos-oauth/src/connections/xero/init.ts b/integrationos-oauth/src/connections/xero/init.ts index d121ee4f..59be5b7d 100644 --- a/integrationos-oauth/src/connections/xero/init.ts +++ b/integrationos-oauth/src/connections/xero/init.ts @@ -1,71 +1,73 @@ -import axios from "axios"; -import jwt from "jsonwebtoken"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import jwt from 'jsonwebtoken'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { generateBasicHeaders } from '../../lib/helpers'; export const init = async ({ body }: DataObject): Promise => { - try { - const requestBody = { - grant_type: "authorization_code", - code: body.metadata?.code, - redirect_uri: body.metadata?.redirectUri, - }; + try { + const requestBody = { + grant_type: 'authorization_code', + code: body.metadata?.code, + redirect_uri: body.metadata?.redirectUri, + }; - const response = await axios.post( - `https://identity.xero.com/connect/token`, - requestBody, - { - headers: generateBasicHeaders(body.clientId, body.clientSecret), - } - ); + const response = await axios.post( + `https://identity.xero.com/connect/token`, + requestBody, + { + headers: generateBasicHeaders(body.clientId, body.clientSecret), + }, + ); - const { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - } = response.data; + const { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + } = response.data; - // Get tenant id details - const decodedToken = jwt.decode(accessToken) as { - authentication_event_id: string; - }; + // Get tenant id details + const decodedToken = jwt.decode(accessToken) as { + authentication_event_id: string; + }; - const tenantId = await axios.get("https://api.xero.com/connections", { - headers: { - authorization: "Bearer " + accessToken, - "Content-Type": "application/json", - }, - }); + const tenantId = await axios.get('https://api.xero.com/connections', { + headers: { + authorization: 'Bearer ' + accessToken, + 'Content-Type': 'application/json', + }, + }); - if (!tenantId.data.length) { - throw new Error(`Failed to fetch tenantId from Xero API`); - } + if (!tenantId.data.length) { + throw new Error(`Failed to fetch tenantId from Xero API`); + } - const extractedTenantId = tenantId.data.find( - (tenant: any) => - tenant.authEventId === decodedToken.authentication_event_id - )?.tenantId; + const extractedTenantId = tenantId.data.find( + (tenant: any) => + tenant.authEventId === decodedToken.authentication_event_id, + )?.tenantId; - if (!extractedTenantId) { - throw new Error(`Failed to extract tenantId from Xero API response`); - } + if (!extractedTenantId) { + throw new Error( + `Failed to extract tenantId from Xero API response`, + ); + } - const newMetadata = { - ...body?.metadata, - tenantId: extractedTenantId, - }; + const newMetadata = { + ...body?.metadata, + tenantId: extractedTenantId, + }; - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - ...newMetadata, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Xero: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + ...newMetadata, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Xero: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/xero/refresh.ts b/integrationos-oauth/src/connections/xero/refresh.ts index 5a69e688..52a48aff 100644 --- a/integrationos-oauth/src/connections/xero/refresh.ts +++ b/integrationos-oauth/src/connections/xero/refresh.ts @@ -1,46 +1,46 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; -import { generateBasicHeaders } from "../../lib/helpers"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; +import { generateBasicHeaders } from '../../lib/helpers'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token, - } = body; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + } = body; - const requestBody = { - grant_type: "refresh_token", - client_id, - refresh_token, - }; + const requestBody = { + grant_type: 'refresh_token', + client_id, + refresh_token, + }; - const response = await axios.post( - "https://identity.xero.com/connect/token", - requestBody, - { - headers: generateBasicHeaders(client_id, client_secret), - } - ); + const response = await axios.post( + 'https://identity.xero.com/connect/token', + requestBody, + { + headers: generateBasicHeaders(client_id, client_secret), + }, + ); - const { - access_token: accessToken, - refresh_token: refreshToken, - expires_in: expiresIn, - token_type: tokenType, - } = response.data; + const { + access_token: accessToken, + refresh_token: refreshToken, + expires_in: expiresIn, + token_type: tokenType, + } = response.data; - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - ...body?.OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error(`Error fetching refresh token for Xero: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + ...body?.OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error(`Error fetching refresh token for Xero: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/zoho/init.ts b/integrationos-oauth/src/connections/zoho/init.ts index 0db49f21..cca910b0 100644 --- a/integrationos-oauth/src/connections/zoho/init.ts +++ b/integrationos-oauth/src/connections/zoho/init.ts @@ -1,44 +1,44 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const init = async ({ body }: DataObject): Promise => { - try { - const { - clientId, - clientSecret, - metadata: { - additionalData, - code, - formData: { ZOHO_ACCOUNTS_DOMAIN }, - redirectUri, - }, - } = body; - let url = `${ZOHO_ACCOUNTS_DOMAIN}/oauth/v2/token?grant_type=authorization_code`; - url += `&client_id=${clientId}&client_secret=${clientSecret}&code=${code}&redirect_uri=${redirectUri}`; + try { + const { + clientId, + clientSecret, + metadata: { + additionalData, + code, + formData: { ZOHO_ACCOUNTS_DOMAIN }, + redirectUri, + }, + } = body; + let url = `${ZOHO_ACCOUNTS_DOMAIN}/oauth/v2/token?grant_type=authorization_code`; + url += `&client_id=${clientId}&client_secret=${clientSecret}&code=${code}&redirect_uri=${redirectUri}`; - const response = await axios.post(url); + const response = await axios.post(url); - const { - data: { - access_token: accessToken, - refresh_token: refreshToken, - api_domain: apiDomain, - token_type: tokenType, - expires_in: expiresIn, - }, - } = response; + const { + data: { + access_token: accessToken, + refresh_token: refreshToken, + api_domain: apiDomain, + token_type: tokenType, + expires_in: expiresIn, + }, + } = response; - return { - accessToken, - refreshToken, - expiresIn, - tokenType, - meta: { - apiDomain, - ...additionalData, - }, - }; - } catch (error) { - throw new Error(`Error fetching access token for Zoho: ${error}`); - } + return { + accessToken, + refreshToken, + expiresIn, + tokenType, + meta: { + apiDomain, + ...additionalData, + }, + }; + } catch (error) { + throw new Error(`Error fetching access token for Zoho: ${error}`); + } }; diff --git a/integrationos-oauth/src/connections/zoho/refresh.ts b/integrationos-oauth/src/connections/zoho/refresh.ts index d73f2318..56cf1eff 100644 --- a/integrationos-oauth/src/connections/zoho/refresh.ts +++ b/integrationos-oauth/src/connections/zoho/refresh.ts @@ -1,42 +1,42 @@ -import axios from "axios"; -import { DataObject, OAuthResponse } from "../../lib/types"; +import axios from 'axios'; +import { DataObject, OAuthResponse } from '../../lib/types'; export const refresh = async ({ body }: DataObject): Promise => { - try { - const { - OAUTH_CLIENT_ID: client_id, - OAUTH_CLIENT_SECRET: client_secret, - OAUTH_REFRESH_TOKEN: refresh_token, - OAUTH_REQUEST_PAYLOAD: { - formData: { ZOHO_ACCOUNTS_DOMAIN }, - }, - OAUTH_METADATA, - } = body; + try { + const { + OAUTH_CLIENT_ID: client_id, + OAUTH_CLIENT_SECRET: client_secret, + OAUTH_REFRESH_TOKEN: refresh_token, + OAUTH_REQUEST_PAYLOAD: { + formData: { ZOHO_ACCOUNTS_DOMAIN }, + }, + OAUTH_METADATA, + } = body; - let url = `${ZOHO_ACCOUNTS_DOMAIN}/oauth/v2/token?grant_type=refresh_token`; - url += `&client_id=${client_id}&client_secret=${client_secret}&refresh_token=${refresh_token}`; + let url = `${ZOHO_ACCOUNTS_DOMAIN}/oauth/v2/token?grant_type=refresh_token`; + url += `&client_id=${client_id}&client_secret=${client_secret}&refresh_token=${refresh_token}`; - const response = await axios.post(url); + const response = await axios.post(url); - const { - data: { - access_token: accessToken, - token_type: tokenType, - expires_in: expiresIn, - }, - } = response; + const { + data: { + access_token: accessToken, + token_type: tokenType, + expires_in: expiresIn, + }, + } = response; - return { - accessToken, - // Refresh token does not expire and stays the same for every request - refreshToken: refresh_token, - expiresIn, - tokenType, - meta: { - ...OAUTH_METADATA?.meta, - }, - }; - } catch (error) { - throw new Error(`Error fetching refresh token for Zoho: ${error}`); - } + return { + accessToken, + // Refresh token does not expire and stays the same for every request + refreshToken: refresh_token, + expiresIn, + tokenType, + meta: { + ...OAUTH_METADATA?.meta, + }, + }; + } catch (error) { + throw new Error(`Error fetching refresh token for Zoho: ${error}`); + } }; diff --git a/integrationos-oauth/src/index.ts b/integrationos-oauth/src/index.ts index eadab2d6..a720b1bf 100644 --- a/integrationos-oauth/src/index.ts +++ b/integrationos-oauth/src/index.ts @@ -1,8 +1,8 @@ -import "dotenv/config"; -import path from "path"; -import express, { Express, Response } from "express"; +import 'dotenv/config'; +import path from 'path'; +import express, { Express, Response } from 'express'; -import { checkExistence, getProjectPath, toCamelCase } from "./lib/helpers"; +import { checkExistence, getProjectPath, toCamelCase } from './lib/helpers'; const app: Express = express(); @@ -10,57 +10,71 @@ app.use(express.json()); app.use(express.urlencoded({ extended: true })); const port = Number(process.env.EXPRESS_SERVER_PORT || 3000); -const hostname = process.env.EXPRESS_SERVER_HOSTNAME || "0.0.0.0"; +const hostname = process.env.EXPRESS_SERVER_HOSTNAME || '0.0.0.0'; -const SERVER_OAUTH_PATH = "./connections"; +const SERVER_OAUTH_PATH = './connections'; -app.get("/", (_, res: Response) => { - res.send("IntegrationOS"); +app.get('/', (_, res: Response) => { + res.send('IntegrationOS'); }); app.listen(port, hostname, () => { - console.log(`IntegrationOS Oauth Server is running on http://${hostname}:${port}`); + console.log( + `IntegrationOS Oauth Server is running on http://${hostname}:${port}`, + ); }); -app.route("/oauth/:platform/init") +app.route('/oauth/:platform/init') .get(async (req, res) => { - res.send(`To Init OAuth for Platform: ${await toCamelCase(req.params.platform)}, perform a POST request!`); + res.send( + `To Init OAuth for Platform: ${await toCamelCase( + req.params.platform, + )}, perform a POST request!`, + ); }) .post(async (req, res) => { try { const { platform } = req.params; const platformOAuthPath = path.join( await getProjectPath(), - ...SERVER_OAUTH_PATH.split("/"), - await toCamelCase(platform) + ...SERVER_OAUTH_PATH.split('/'), + await toCamelCase(platform), ); if (!(await checkExistence(platformOAuthPath))) { - return res.status(404).send({ message: `Error: OAuth does not exist for ${platform}!` }); + return res.status(404).send({ + message: `Error: OAuth does not exist for ${platform}!`, + }); } const { init } = require(`${platformOAuthPath}/init`); - if (typeof init !== "function") { - return res.status(500).send({ message: `Error: Missing init function for ${platform}!` }); + if (typeof init !== 'function') { + return res.status(500).send({ + message: `Error: Missing init function for ${platform}!`, + }); } const response = await init({ headers: req.headers, params: req.params, - body: req.body + body: req.body, }); res.send(response); } catch (error) { - console.error("Error during OAuth initialization:", error); - res.status(500).send({ message: "Internal Server Error" }); + console.error('Error during OAuth initialization:', error); + res.status(500).send({ message: 'Internal Server Error' }); } }); -app.route("/oauth/:platform/refresh") +app.route('/oauth/:platform/refresh') .get(async (req, res) => { - res.send(`To Refresh OAuth for Platform: ${await toCamelCase(req.params.platform)}, perform a POST request!`); + res.send( + `To Refresh OAuth for Platform: ${await toCamelCase( + req.params.platform, + )}, perform a POST request!`, + ); }) .post(async (req, res) => { try { @@ -68,29 +82,33 @@ app.route("/oauth/:platform/refresh") const platformOAuthPath = path.join( await getProjectPath(), - ...SERVER_OAUTH_PATH.split("/"), - await toCamelCase(platform) + ...SERVER_OAUTH_PATH.split('/'), + await toCamelCase(platform), ); if (!(await checkExistence(platformOAuthPath))) { - return res.status(404).send({ message: `Error: OAuth does not exist for ${platform}!` }); + return res.status(404).send({ + message: `Error: OAuth does not exist for ${platform}!`, + }); } const { refresh } = require(`${platformOAuthPath}/refresh`); - if (typeof refresh !== "function") { - return res.status(500).send({ message: `Error: Missing refresh function for ${platform}!` }); + if (typeof refresh !== 'function') { + return res.status(500).send({ + message: `Error: Missing refresh function for ${platform}!`, + }); } const response = await refresh({ headers: req.headers, params: req.params, - body: req.body + body: req.body, }); res.send(response); } catch (error) { - console.error("Error during OAuth refresh:", error); - res.status(500).send({ message: "Internal Server Error" }); + console.error('Error during OAuth refresh:', error); + res.status(500).send({ message: 'Internal Server Error' }); } }); diff --git a/integrationos-oauth/src/lib/helpers.ts b/integrationos-oauth/src/lib/helpers.ts index bbe49630..dc1549dc 100644 --- a/integrationos-oauth/src/lib/helpers.ts +++ b/integrationos-oauth/src/lib/helpers.ts @@ -1,57 +1,58 @@ -import { promises } from "node:fs"; -import path from "path"; +import { promises } from 'node:fs'; +import path from 'path'; export const checkExistence = async (path: string) => { - try { - await promises.access(path); + try { + await promises.access(path); - return true; - } catch (error) { - return false; - } + return true; + } catch (error) { + return false; + } }; -export const getProjectPath = async () => path.join(__dirname, ".."); +export const getProjectPath = async () => path.join(__dirname, '..'); export const toCamelCase = async (input: string) => { - let words = input.split(/[^a-zA-Z0-9]+/).filter((word) => word.length); + const words = input.split(/[^a-zA-Z0-9]+/).filter((word) => word.length); - for (let i = 1; i < words.length; i++) { - words[i] = words[i][0].toUpperCase() + words[i].substring(1).toLowerCase(); - } + for (let i = 1; i < words.length; i++) { + words[i] = + words[i][0].toUpperCase() + words[i].substring(1).toLowerCase(); + } - const result = words.join(""); + const result = words.join(''); - return result[0].toLowerCase() + result.substring(1); + return result[0].toLowerCase() + result.substring(1); }; export const convertToTimestamp = async (dateString: string): Promise => - new Date(dateString).getTime(); + new Date(dateString).getTime(); export const base64encode = (val: string) => btoa(val); export const differenceInSeconds = (argDate: Date) => { - const currentDate = new Date().getTime(); - const dateArg = new Date(argDate).getTime(); + const currentDate = new Date().getTime(); + const dateArg = new Date(argDate).getTime(); - // Calculate the difference in milliseconds - const differenceInMillis = dateArg - currentDate; + // Calculate the difference in milliseconds + const differenceInMillis = dateArg - currentDate; - // Convert milliseconds to seconds - const differenceInSeconds = differenceInMillis / 1000; + // Convert milliseconds to seconds + const differenceInSeconds = differenceInMillis / 1000; - return Math.floor(differenceInSeconds); + return Math.floor(differenceInSeconds); }; export const generateBasicHeaders = ( - clientId: string, - clientSecret: string + clientId: string, + clientSecret: string, ) => { - const credentials = clientId + ":" + clientSecret; - const encodedCredentials = Buffer.from(credentials).toString("base64"); + const credentials = clientId + ':' + clientSecret; + const encodedCredentials = Buffer.from(credentials).toString('base64'); - return { - Authorization: "Basic " + encodedCredentials, - "Content-Type": "application/x-www-form-urlencoded", - }; + return { + Authorization: 'Basic ' + encodedCredentials, + 'Content-Type': 'application/x-www-form-urlencoded', + }; }; diff --git a/integrationos-oauth/src/lib/types.ts b/integrationos-oauth/src/lib/types.ts index c5ed3ab0..ba87ae1c 100644 --- a/integrationos-oauth/src/lib/types.ts +++ b/integrationos-oauth/src/lib/types.ts @@ -1,12 +1,12 @@ export interface DataObject { - [key: string]: any; + [key: string]: any; } export interface OAuthResponse { - accessToken: string; - refreshToken: string; - // expiresIn will be in seconds - expiresIn: number; - tokenType: string; - meta: DataObject; + accessToken: string; + refreshToken: string; + // expiresIn will be in seconds + expiresIn: number; + tokenType: string; + meta: DataObject; }