Skip to content

Commit

Permalink
Merge branch 'feature/436478-vocabularios' into 'develop'
Browse files Browse the repository at this point in the history
Feature/436478 vocabularios

See merge request upm-inesdata/inesdata-public-portal-backend!5
  • Loading branch information
Pablo Pérez López committed Jul 29, 2024
2 parents 8cb41a0 + d9caacd commit 26f4e4e
Show file tree
Hide file tree
Showing 5 changed files with 147 additions and 86 deletions.
3 changes: 2 additions & 1 deletion config/inesdata.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ module.exports = ({ env }) => ({
tokenUsername: env('TOKEN_USERNAME', 'user-c1'),
tokenPassword: env('TOKEN_PASSWORD', 'user-c1'),
keycloakBaseUrl: env('KEYCLOAK_BASE_URL', 'http://keycloak:8080'),
catalogBaseUrl: env('CATALOG_BASE_URL', 'http://connector-c1:19193')
catalogBaseUrl: env('CATALOG_BASE_URL', 'http://connector-c1:19193'),
vocabulariesBaseUrl: env('VOCABULARIES_BASE_URL', 'http://connector-c1:19196')
})
94 changes: 9 additions & 85 deletions src/api/get-federated-catalog/controllers/get-federated-catalog.js
Original file line number Diff line number Diff line change
@@ -1,95 +1,13 @@
'use strict';

const axios = require('axios');
const tokenService = require('../../services/token-service');

const tokenData = {
accessToken: null,
refreshToken: null,
expiresIn: null,
refreshExpiresIn: null,
obtainedAt: null,
refreshObtainedAt: null
};

const getTokenFromAuthServer = async () => {
try {
const params = new URLSearchParams();
params.append('grant_type', 'password');
params.append('client_id', process.env.TOKEN_CLIENT_ID);
params.append('username', process.env.TOKEN_USERNAME);
params.append('password', process.env.TOKEN_PASSWORD);

const tokenUrl = `${process.env.KEYCLOAK_BASE_URL}/realms/dataspace/protocol/openid-connect/token`;

const response = await axios.post(tokenUrl, params);
const data = response.data;

tokenData.accessToken = data.access_token;
tokenData.refreshToken = data.refresh_token;
tokenData.expiresIn = data.expires_in; // expires_in is in seconds
tokenData.refreshExpiresIn = data.refresh_expires_in; // refresh_expires_in is in seconds
tokenData.obtainedAt = Date.now(); // store the time the token was obtained
tokenData.refreshObtainedAt = Date.now(); // store the time the refresh token was obtained

return data;
} catch (error) {
console.error('Error obtaining token from auth server:', error);
throw new Error('Failed to obtain token from auth server');
}
};

const refreshToken = async () => {
try {
const params = new URLSearchParams();
params.append('grant_type', 'refresh_token');
params.append('client_id', process.env.TOKEN_CLIENT_ID);
params.append('refresh_token', tokenData.refreshToken);

const tokenUrl = `${process.env.KEYCLOAK_BASE_URL}/realms/dataspace/protocol/openid-connect/token`;

const response = await axios.post(tokenUrl, params);
const data = response.data;

tokenData.accessToken = data.access_token;
tokenData.refreshToken = data.refresh_token;
tokenData.expiresIn = data.expires_in;
tokenData.refreshExpiresIn = data.refresh_expires_in;
tokenData.obtainedAt = Date.now();

return data;
} catch (error) {
console.error('Error refreshing token:', error);
throw new Error('Failed to refresh token');
}
};

const getAccessToken = async () => {
try {
if (!tokenData.accessToken || !tokenData.refreshToken) {
await getTokenFromAuthServer();
} else {
const currentTime = Date.now();
const accessTokenExpired = (currentTime - tokenData.obtainedAt) / 1000 > tokenData.expiresIn;
const refreshTokenExpired = (currentTime - tokenData.refreshObtainedAt) / 1000 > tokenData.refreshExpiresIn;

if (refreshTokenExpired) {
await getTokenFromAuthServer();
} else if (accessTokenExpired) {
await refreshToken();
}
}

return tokenData.accessToken;
} catch (error) {
console.error('Error getting access token:', error);
throw new Error('Failed to get access token');
}
};

module.exports = {
getFederatedCatalog: async (ctx, next) => {
try {
const accessToken = await getAccessToken();
const accessToken = await tokenService.getAccessToken();
if (!accessToken) {
ctx.body = { message: 'Access token not available. Please authenticate first.' };
ctx.status = 401;
Expand All @@ -99,7 +17,13 @@ module.exports = {
// URL for fetching the federated catalog
const countCatalogUrl = `${process.env.CATALOG_BASE_URL}/management/pagination/count?type=federatedCatalog`;

const countResponse = await axios.get(countCatalogUrl, {
const body = ctx.request.body
delete body.offset
delete body.limit
delete body.sortOrder
delete body.sortField

const countResponse = await axios.post(countCatalogUrl, body,{
headers: {
Authorization: `Bearer ${accessToken}`
}
Expand Down
36 changes: 36 additions & 0 deletions src/api/get-vocabularies/controllers/get-vocabularies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const axios = require('axios');
const tokenService = require('../../services/token-service');


module.exports = {
getVocabularies: async (ctx, next) => {
try {
const accessToken = await tokenService.getAccessToken();
if (!accessToken) {
ctx.body = { message: 'Access token not available. Please authenticate first.' };
ctx.status = 401;
return;
}


// URL for fetching the vocabularies
const vocabulariesBaseUrl = `${process.env.VOCABULARIES_BASE_URL}/shared/connector-vocabularies/request`;

// Fetch the vocabularies using the access token
const vocabulariesResponse = await axios.post(vocabulariesBaseUrl, {}, {
headers: {
Authorization: `Bearer ${accessToken}`
}
});

// Respond with the fetched data
ctx.body = vocabulariesResponse.data;
} catch (err) {
console.error('Error:', err);
ctx.body = { message: 'Error fetching vocabularies!', details: err.message };
ctx.status = 500;
}
}
};
9 changes: 9 additions & 0 deletions src/api/get-vocabularies/routes/get-vocabularies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
"routes": [
{
"method": "POST",
"path": "/get-vocabularies",
"handler": "get-vocabularies.getVocabularies"
}
]
};
91 changes: 91 additions & 0 deletions src/api/services/token-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
const axios = require('axios');

const tokenData = {
accessToken: null,
refreshToken: null,
expiresIn: null,
refreshExpiresIn: null,
obtainedAt: null,
refreshObtainedAt: null
};

const getTokenFromAuthServer = async () => {
try {
const params = new URLSearchParams();
params.append('grant_type', 'password');
params.append('client_id', process.env.TOKEN_CLIENT_ID);
params.append('username', process.env.TOKEN_USERNAME);
params.append('password', process.env.TOKEN_PASSWORD);

const tokenUrl = `${process.env.KEYCLOAK_BASE_URL}/realms/dataspace/protocol/openid-connect/token`;

const response = await axios.post(tokenUrl, params);
const data = response.data;

tokenData.accessToken = data.access_token;
tokenData.refreshToken = data.refresh_token;
tokenData.expiresIn = data.expires_in; // expires_in is in seconds
tokenData.refreshExpiresIn = data.refresh_expires_in; // refresh_expires_in is in seconds
tokenData.obtainedAt = Date.now(); // store the time the token was obtained
tokenData.refreshObtainedAt = Date.now(); // store the time the refresh token was obtained

return data;
} catch (error) {
console.error('Error obtaining token from auth server:', error);
throw new Error('Failed to obtain token from auth server');
}
};

const refreshToken = async () => {
try {
const params = new URLSearchParams();
params.append('grant_type', 'refresh_token');
params.append('client_id', process.env.TOKEN_CLIENT_ID);
params.append('refresh_token', tokenData.refreshToken);

const tokenUrl = `${process.env.KEYCLOAK_BASE_URL}/realms/dataspace/protocol/openid-connect/token`;

const response = await axios.post(tokenUrl, params);
const data = response.data;

tokenData.accessToken = data.access_token;
tokenData.refreshToken = data.refresh_token;
tokenData.expiresIn = data.expires_in;
tokenData.refreshExpiresIn = data.refresh_expires_in;
tokenData.obtainedAt = Date.now();

return data;
} catch (error) {
console.error('Error refreshing token:', error);
throw new Error('Failed to refresh token');
}
};

const getAccessToken = async () => {
try {
if (!tokenData.accessToken || !tokenData.refreshToken) {
await getTokenFromAuthServer();
} else {
const currentTime = Date.now();
const accessTokenExpired = (currentTime - tokenData.obtainedAt) / 1000 > tokenData.expiresIn;
const refreshTokenExpired = (currentTime - tokenData.refreshObtainedAt) / 1000 > tokenData.refreshExpiresIn;

if (refreshTokenExpired) {
await getTokenFromAuthServer();
} else if (accessTokenExpired) {
await refreshToken();
}
}

return tokenData.accessToken;
} catch (error) {
console.error('Error getting access token:', error);
throw new Error('Failed to get access token');
}
};

module.exports = {
getTokenFromAuthServer,
refreshToken,
getAccessToken
};

0 comments on commit 26f4e4e

Please sign in to comment.