node-jenkins
node-jenkins copied to clipboard
Creating/Revoking API Tokens
I'd like to add functionality to create and revoke API Tokens. I've already did it in our application. The only tricky part is that the calls need to be done with the username/password
(and not username/token) which can be added in the headers
initialization config as:
headers: {
Authorization: 'Basic <Base64_username:password>'
}
Also, since it'll be using password
instead of token
, we'll need to generate a Crumb before each request, but I THINK this part is already being handled by this lib?
What do you think? Should I prepare a PR?
For completeness, here is what I have so far (although it's using request
instead of papi
, which I'll need to convert)
function generateJenkinsToken({ crumbRequestField, crumb, sessionId }, newTokenName, callback) {
const url = `${url}/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken`;
const options = {
auth: getBasicAuth(),
headers: {
[crumbRequestField]: crumb,
cookie: sessionId,
},
rejectUnauthorized: false,
form: { newTokenName },
json: true,
};
request.post(url, options, function (error, response, body) {
if (error || (body && body.status && body.status !== 'ok')) {
return callback(new Error(body.message));
}
callback(null, body.data);
});
}
// A successful revoke does not return a body
// Jenkins returns 200 even if tokenUuid doesn't exist
function revokeJenkinsToken({ crumbRequestField, crumb, sessionId }, tokenUuid, callback) {
const url = `${url}/me/descriptorByName/jenkins.security.ApiTokenProperty/revoke`;
const options = {
auth: getBasicAuth(),
headers: {
[crumbRequestField]: crumb,
cookie: sessionId,
},
rejectUnauthorized: false,
form: { tokenUuid },
json: true,
};
request.post(url, options, function (error, response, body) {
if (error || (body && body.status && body.status !== 'ok')) {
return callback(new Error(body.message));
}
callback(null);
});
}