Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 1 addition & 107 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
},
"dependencies": {
"dotenv": "^17.2.0",
"express": "^5.1.0",
"simple-oauth2": "^5.1.0"
"express": "^5.1.0"
},
"devDependencies": {
"eslint": "^9.31.0",
Expand Down
47 changes: 28 additions & 19 deletions src/oauth2.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,43 @@
import { ClientCredentials } from 'simple-oauth2';
import services from './vcap-services.js';

const credentials = services.getCredentials('p.config-server');

const client = new ClientCredentials({
client: {
id: credentials.client_id,
secret: credentials.client_secret,
},
auth: {
tokenHost: credentials.access_token_uri.replace('/oauth/token', ''),
tokenPath: '/oauth/token',
},
});

let token = null;

// Checks if token is expired or will be expired in given window.
const expired = (token, expirationWindowSeconds = 0) => {
return (
!token ||
token.expires_at - (Date.now() + expirationWindowSeconds * 1000) <= 0
);
};

// Requests an access token from the UAA server using client credentials.
const getAccessToken = async () => {
// If token is not set or expired, request a new one.
if (!token || token.expired(10)) {
try {
token = await client.getToken();
} catch (error) {
console.error('Failed to get access token', error.message);
throw error;
if (!token || expired(token, 10)) {
const response = await fetch(credentials.access_token_uri, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${Buffer.from(`${credentials.client_id}:${credentials.client_secret}`).toString('base64')}`,
},
body: new URLSearchParams({ grant_type: 'client_credentials' }),
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();

token = {
access_token: data.access_token,
expires_at: Date.now() + data.expires_in * 1000,
};
}

return token.token.access_token;
return token.access_token;
};

export default {
Expand Down