Created
April 12, 2017 01:36
-
-
Save ragingprodigy/eb7e85cfef810a4d5067ba261ba95b23 to your computer and use it in GitHub Desktop.
Generate File Upload policy for Amazon s3
This file contains 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
'use strict'; | |
var AWS = require('aws-sdk'), | |
crypto = require('crypto'), | |
createS3Policy, | |
getExpiryTime; | |
getExpiryTime = function () { | |
var _date = new Date(); | |
return '' + (_date.getFullYear()) + '-' + (_date.getMonth() + 1) + '-' + | |
(_date.getDate() + 1) + 'T' + (_date.getHours() + 3) + ':' + '00:00.000Z'; | |
}; | |
createS3Policy = function(contentType, subFolder, callback) { | |
var s3Policy = { | |
'expiration': getExpiryTime(), | |
'conditions': [ | |
['starts-with', '$key', subFolder], | |
{'bucket': 'nba-agc'}, | |
{'acl': 'public-read'}, | |
['starts-with', '$Content-Type', contentType] | |
] | |
}; | |
// stringify and encode the policy | |
var stringPolicy = JSON.stringify(s3Policy); | |
var base64Policy = new Buffer(stringPolicy, 'utf-8').toString('base64'); | |
// sign the base64 encoded policy | |
var signature = crypto.createHmac('sha1', process.env.AWS_SECRET_KEY) | |
.update(new Buffer(base64Policy, 'utf-8')).digest('base64'); | |
// build the results object | |
var s3Credentials = { | |
s3Policy: base64Policy, | |
s3Signature: signature, | |
AWSAccessKeyId: process.env.AWS_ACCESS_KEY_ID | |
}; | |
// send it back | |
callback(s3Credentials); | |
}; | |
/* | |
* Later, we can then use the preceeding methods in a request handler | |
*/ | |
app.get('/s3_policy', function(req, res) { | |
createS3Policy(req.query.mimeType, req.query.subFolder, function (creds, err) { | |
if (!err) { | |
return res.send(200, creds); | |
} else { | |
return res.send(500, err); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment