move the API token related funcions to another file

This commit is contained in:
Pau 2023-01-09 12:58:34 +01:00
parent 45d819c47b
commit 0eed231dce
2 changed files with 94 additions and 89 deletions

View File

@ -1,16 +1,13 @@
import fetch from 'node-fetch';
import moment from 'moment';
import { getClientToken } from './utils.js';
// Check the existence of the .env file
import dotenv from 'dotenv';
dotenv.config();
const _accessTokenEndpoint =
'https://idm.staging.floriday.io/oauth2/ausmw6b47z1BnlHkw0h7/v1/token';
import models from './models/index.js';
let AccessToken = await getClientToken();
let AccessToken = await getClientToken(models);
// eslint-disable-next-line no-unused-vars
let tokenValue = AccessToken[0];
@ -24,7 +21,7 @@ try {
if (moment().isAfter(tokenExpirationDate)) {
console.log('Token expired, getting a new one...');
AccessToken = await getClientToken();
AccessToken = await getClientToken(models);
tokenValue = AccessToken[0];
tokenExpirationDate = AccessToken[1];
}
@ -34,89 +31,6 @@ try {
console.error('Unable to connect to the database:', error);
}
async function getClientToken() {
const clientConfigData = await models.clientConfig.findAll();
const now = moment().format('YYYY-MM-DD HH:mm:ss');
const tokenExpirationDate = clientConfigData[0].tokenExpiration;
if (
clientConfigData[0].tokenExpiration == null ||
moment(now).isAfter(tokenExpirationDate)
) {
let clientId = clientConfigData[0].clientId;
let clientSecret = clientConfigData[0].clientSecret;
const tokenRequest = await fetch(_accessTokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}&scope=role:app catalog:read supply:read organization:read network:read`,
});
const tokenResponse = await tokenRequest.json();
// If the token request is successful, show a message in the console
if (tokenRequest.status === 200) {
console.log('Token request successful');
} else {
throw new Error(
`Token request failed with status ${tokenRequest.status}`
);
}
const accessToken = tokenResponse.access_token;
let now = moment().format('YYYY-MM-DD HH:mm:ss');
let tokenExpirationDate = moment(now)
.add(tokenResponse.expires_in, 's')
.format('YYYY-MM-DD HH:mm:ss');
updateClientConfig(
clientId,
clientSecret,
accessToken,
tokenExpirationDate
);
return [accessToken, tokenExpirationDate];
} else {
console.log('Using the current token...');
return [clientConfigData[0].currentToken, tokenExpirationDate];
}
}
async function updateClientConfig(
clientId,
clientSecret,
accessToken,
tokenExpirationDate
) {
try {
console.log('Updating the client config with the new token...');
await models.clientConfig.update(
{
clientId: clientId,
clientSecret: clientSecret,
currentToken: accessToken,
tokenExpiration: tokenExpirationDate,
},
{
where: {
id: 1,
},
}
);
console.log('Client config updated, new Token set');
console.log('New token expiration date: ', tokenExpirationDate);
} catch (error) {
console.log('There was a error while updating the client config');
console.log(error);
}
}
console.log = function () {
let args = Array.prototype.slice.call(arguments);
args.unshift(new moment().format('HH:mm:ss') + ' -');

91
utils.js Normal file
View File

@ -0,0 +1,91 @@
import moment from 'moment';
import fetch from 'node-fetch';
const _accessTokenEndpoint =
'https://idm.staging.floriday.io/oauth2/ausmw6b47z1BnlHkw0h7/v1/token';
async function getClientToken(models) {
const clientConfigData = await models.clientConfig.findAll();
const now = moment().format('YYYY-MM-DD HH:mm:ss');
const tokenExpirationDate = clientConfigData[0].tokenExpiration;
if (
clientConfigData[0].tokenExpiration == null ||
moment(now).isAfter(tokenExpirationDate)
) {
let clientId = clientConfigData[0].clientId;
let clientSecret = clientConfigData[0].clientSecret;
const tokenRequest = await fetch(_accessTokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}&scope=role:app catalog:read supply:read organization:read network:read`,
});
const tokenResponse = await tokenRequest.json();
// If the token request is successful, show a message in the console
if (tokenRequest.status === 200) {
console.log('Token request successful');
} else {
throw new Error(
`Token request failed with status ${tokenRequest.status}`
);
}
const accessToken = tokenResponse.access_token;
let now = moment().format('YYYY-MM-DD HH:mm:ss');
let tokenExpirationDate = moment(now)
.add(tokenResponse.expires_in, 's')
.format('YYYY-MM-DD HH:mm:ss');
updateClientConfig(
models,
clientId,
clientSecret,
accessToken,
tokenExpirationDate
);
return [accessToken, tokenExpirationDate];
} else {
console.log('Using the current token...');
return [clientConfigData[0].currentToken, tokenExpirationDate];
}
}
async function updateClientConfig(
models,
clientId,
clientSecret,
accessToken,
tokenExpirationDate
) {
try {
console.log('Updating the client config with the new token...');
await models.clientConfig.update(
{
clientId: clientId,
clientSecret: clientSecret,
currentToken: accessToken,
tokenExpiration: tokenExpirationDate,
},
{
where: {
id: 1,
},
}
);
console.log('Client config updated, new Token set');
console.log('New token expiration date: ', tokenExpirationDate);
} catch (error) {
console.log('There was a error while updating the client config');
console.log(error);
}
}
export { getClientToken };