@sap/xssec
Version:
XS Advanced Container Security API for node.js
107 lines (98 loc) • 3.41 kB
JavaScript
const fs = require('fs');
const path = require('path');
const yargs = require('yargs');
const createServiceFromCredentials = require('../v3/createService');
const XsuaaService = require('../service/XsuaaService');
// Define the CLI options
const argv = yargs
.option('a', {
alias: 'api',
describe: 'API names for fetching the token',
type: 'array'
})
.option('f', {
alias: 'format',
describe: 'Token format (jwt or opaque)',
type: 'string',
default: 'jwt'
})
.option('j', {
alias: 'jwt',
describe: 'JWT token or path to a file containing the JWT token',
type: 'string'
})
.option('p', {
alias: 'password',
describe: 'Password for fetching a user token',
type: 'string'
})
.option('t', {
alias: 'tenant',
describe: 'Tenant for fetching the token',
type: 'string'
})
.option('u', {
alias: 'username',
describe: 'Username for fetching a user token',
type: 'string'
})
.option('r', {
alias: 'resource',
describe: 'Resource for fetching the token',
type: 'array'
})
.option('zid', {
describe: 'Zone ID for fetching the token',
type: 'string'
})
.help()
.argv;
// Load credentials from the second argument
const credentialsPath = path.resolve(process.argv[2]);
const credentials = JSON.parse(fs.readFileSync(credentialsPath, 'utf8'));
// Create the service instance
const service = createServiceFromCredentials(credentials);
async function fetchToken() {
try {
/** @type{import("../index").Types.TokenFetchOptions & import("../index").Types.IdentityServiceTokenFetchOptions & import("../index").Types.XsuaaTokenFetchOptions} */
const options = {
tenant: argv.tenant,
zid: argv.zid,
resource: argv.resource ? argv.resource.slice() : [],
token_format: argv.format,
refresh_expiry: 0,
timeout: 10000
};
// Add API resources
if (argv.api) {
argv.api.forEach(apiName => {
options.resource.push(`urn:sap:identity:application:provider:name:${apiName}`);
});
}
// Read JWT token from file if the path is provided
let jwtToken = argv.j;
if (jwtToken && fs.existsSync(jwtToken)) {
jwtToken = fs.readFileSync(jwtToken, 'utf8');
}
let response;
let token;
if (argv.u && argv.p) {
// Fetch user token
response = await service.fetchPasswordToken(argv.u, argv.p, options);
token = service instanceof XsuaaService ? response.access_token : response.id_token;
} else if (jwtToken) {
// Fetch JWT bearer token
response = await service.fetchJwtBearerToken(jwtToken, options);
token = argv.api || service instanceof XsuaaService ? response.access_token : response.id_token;
} else {
// Fetch client credentials token
response = await service.fetchClientCredentialsToken(options);
token = response.access_token;
}
// Print the token to stdout without a newline
process.stdout.write(token);
} catch (error) {
console.error('Error fetching token:', error);
}
}
fetchToken();