Last active
May 4, 2017 08:53
-
-
Save nosolopau/4723662 to your computer and use it in GitHub Desktop.
Amazon S3 upload policy generation with JavaScript (Node.js).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var crypto = require("crypto"); | |
var moment = require("moment") | |
var s3 = { | |
generateS3Policy: function (fileName) { | |
var s3Policy = { | |
'conditions': [ | |
{'bucket': CONF.s3.bucket}, | |
['starts-with', '$key', 'uploads/' + fileName], | |
{'acl': 'public-read'}, | |
{'success_action_redirect': 'http://' + CONF.host + '/upload_done'}, | |
["content-length-range", 0, CONF.s3.policy.maxSize], | |
['starts-with', '$Content-Type', 'image'] | |
], | |
'expiration': moment().add('minutes', CONF.s3.uploadWindow).format("YYYY-MM-DDTHH:mm:ss\\Z") | |
}; | |
return s3Policy; | |
}, | |
generateS3Credentials: function (s3Policy) { | |
var encodedPolicy = new Buffer(JSON.stringify(s3Policy)).toString('base64'), | |
credentials = { | |
policy: encodedPolicy, | |
signature: crypto.createHmac("sha1", CONF.s3.secretKey).update(encodedPolicy).digest("base64"), | |
key: CONF.s3.key, | |
redirect: 'http://' + CONF.host + '/upload_done', | |
plain_policy: s3Policy | |
}; | |
return credentials; | |
} | |
}; | |
module.exports = s3; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var S3 = require('./s3'); | |
var policy = S3.generateS3Policy("user_" + req.user.id); | |
var credentials = S3.generateS3Credentials(policy); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the moment date format is wrong - it should be: YYYY-MM-DDTHH:mm:ss\Z (minutes: m, not M)