Skip to content

Instantly share code, notes, and snippets.

@joshisa
Last active August 29, 2015 14:01
Show Gist options
  • Save joshisa/47b384878660760c7733 to your computer and use it in GitHub Desktop.
Save joshisa/47b384878660760c7733 to your computer and use it in GitHub Desktop.
Demonstrates a way to create an API Key User with Cloudant and set permissions on that API Key
// Demonstrates a way to create an API Key User with Cloudant and set permissions
var dbname = 'somedb';
var cloudantCreds = {
username: 'cloudantusername',
password: 'cloudantpassword'
};
var auth = 'Basic ' + new Buffer( cloudantCreds.username + ':' + cloudantCreds.password).toString('base64');
var options = {
hostname: 'cloudant.com',
port: 443,
path: '/api/generate_api_key',
method: 'POST',
headers: {
'Authorization' : auth,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
console.log('Generating API Key on ' + dbname.toUpperCase() + ' ...');
var request=https.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
if (JSON.parse(chunk).ok === true) {
console.log("API Key+Value pair successfully generated.");
var apikeyuser = JSON.parse(chunk).key;
var apikeypass = JSON.parse(chunk).password;
//DEBUG ONLY
console.log(apikeyuser + '-' + apikeypass);
var data = querystring.stringify({
username: apikeyuser,
database: cloudantCreds.username + '/' + dbname,
roles: '_writer'
});
options = {
hostname: 'cloudant.com',
port: 443,
path: '/api/set_permissions',
method: 'POST',
headers: {
'Authorization' : auth,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
console.log('Setting permissions to writer on ' + dbname.toUpperCase() + ' for ' + apikeyuser + ' user ...');
var request=https.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
if (JSON.parse(chunk).ok === true) {
console.log("Permissions successfully set.");
} else {
console.log("Permissions fail to set");
console.log(JSON.parse(chunk).ok);
console.log('Body: ' + chunk);
}
});
});
request.write(data);
request.end();
} else {
console.log("API Key+Value pair failed to generate");
console.log('Body: ' + chunk);
}
});
});
request.write('');
request.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment