| Current Path : /home/deltalab/PMS/pim-connector/logic/akeneo/ |
| Current File : //home/deltalab/PMS/pim-connector/logic/akeneo/auth.js |
const axios = require('axios');
let authToken;
// This should come from a config file with secret protection
const authConfig=process.env.AUTH_CONFIG;
/*{
headers:{
'Authorization': 'Basic MV8zc3ZrZ2d4dDZjNmMwd2cwOGtjMGNjdzBjZzgwMGNvazA0MG93OGtzY2NjNDg4ODhjczo2YnM3c29kd2ZyYzQwb2trd3NrMHNrZ2NzbzBzb3c4b2trNDh3YzBvNHdvdzR3NGNjOA==',
'Content-Type': 'application/json'
}
}*/
// Credentials
const endPointLogin=process.env.AKENEO_CREDENTIALS
/*{
"grant_type": "password",
"username" : "pimconnector_8308",
"password" : "853da716b"
}*/
// FUNCTIONS ============================================
/**
* Generates a new token with the given configuration
* @param {*} config
* @returns "result: success, authToken" or "result: error, message"
*/
async function requestAuthToken(config) {
let toReturn;
console.log('requesting new auth token');
await axios.post(process.env.AKENEO_URL + '/api/oauth/v1/token', endPointLogin, config)
.then(success=>{
authToken = success.data;
authToken.issueTime = Date.now()/1000;
toReturn = {result: "success", authToken: authToken.access_token};
}, reject =>{
toReturn = {result: "error", message: reject};
});
return toReturn;
}
/**
* Verifies if the given token is expired
* @param {*} token
* @returns true if the token issueTime is past
*/
function isExpired(token) {
return ((Date.now()/1000)-token.issueTime)>token.expires_in;
}
/**
* Returns a valid authToken for akeneo
* to be used for further queries
* @returns result (success|error), authToken
*/
async function authToAkeneo() {
let toReturn;
// Create a new auth token if none is available
if (!authToken){
toReturn = await requestAuthToken(authConfig);
}
// Refresh the access token if expired
else {
if ( isExpired(authToken) ){
console.log('token expired');
let refreshBody={
refresh_token: authToken.refresh_token,
grant_type: "refresh_token"
}
toReturn = await requestAuthToken(refreshBody);
}
// Otherwise, just return the current token
else {
console.log('token is here');
toReturn = {result: "success", authToken: authToken.access_token};
}
}
return toReturn;
}
// EXPORTS ===============================================
exports.authToAkeneo = authToAkeneo;