Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
generating short lived credentials for s3
'use strict';
var util = require('util');
var aws = require('aws-sdk');
var async = require('async');
var EXPIRATION_TIME_SECS = 60 * 60; //60 mins
var BUCKET = 'myTestBucket';
var OBJECT_PATH = 'path/where/the/object/is/store';
var ACCESS_KEY='<access_key>';
var SECRET_KEY='<secret_key>';
function initialize(params, next) {
params.s3 = new aws.S3({
accessKeyId: ACCESS_KEY,
secretAccessKey: SECRET_KEY
});
util.log('s3 initialized');
return next();
}
function createBucket(params, next) {
var bucketOptions = {
Bucket: BUCKET
};
util.log('Creating bucket ' + bucketOptions.Bucket);
params.s3.createBucket(bucketOptions,
function(err) {
return next(err);
}
);
}
function generateGETUrl(params, next) {
util.log('Generating GET url for object');
var options = {
Bucket: BUCKET,
Key: OBJECT_PATH,
Expires: EXPIRATION_TIME_SECS
};
params.s3.getSignedUrl('getObject', options,
function(err, url) {
if (err)
return next(err);
params.accessors.get = url;
return next();
}
);
}
function generatePUTUrl(params, next) {
util.log('Generating PUT url for object');
var options = {
Bucket: BUCKET,
Key: OBJECT_PATH,
Expires: EXPIRATION_TIME_SECS
};
params.s3.getSignedUrl('putObject', options,
function(err, url) {
if (err)
return next(err);
params.accessors.put = url;
return next();
}
);
}
function generateDELETEUrl(params, next) {
util.log('Generating DELETE url for object');
var options = {
Bucket: BUCKET,
Key: OBJECT_PATH,
Expires: EXPIRATION_TIME_SECS
};
params.s3.getSignedUrl('deleteObject', options,
function(err, url) {
if (err)
return next(err);
params.accessors.delete = url;
return next();
}
);
}
function generateHEADUrl(params, next) {
util.log('Generating HEAD url for object');
var options = {
Bucket: BUCKET,
Key: OBJECT_PATH,
Expires: EXPIRATION_TIME_SECS
};
params.s3.getSignedUrl('headObject', options,
function(err, url) {
if (err)
return next(err);
params.accessors.head = url;
return next();
}
);
}
function main(cb) {
var params = {};
params.accessors = {
get: '',
put: '',
delete: ''
};
async.series([
initialize.bind(null, params),
createBucket.bind(null, params),
generateGETUrl.bind(null, params),
generatePUTUrl.bind(null, params),
generateDELETEUrl.bind(null, params),
generateHEADUrl.bind(null, params)
], function (err) {
if (err) {
util.log(
util.format(
'Error generating accessor URLs for Bucket %s and path %s',
BUCKET, OBJECT_PATH));
util.log(util.inspect(err));
} else {
util.log('Accessors : ' + util.inspect(params.accessors));
}
cb();
});
}
main(function () {
util.log('Done');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment