-
Notifications
You must be signed in to change notification settings - Fork 2
/
s3Policy.js
78 lines (68 loc) · 2.91 KB
/
s3Policy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var crypto = Npm.require('crypto');
S3Policies = s3Policies = function (accessKey, secretKey) {
if (!accessKey || !secretKey) {
console.log('Bad instantiation of s3policy! Go stand in the corner.\nDo the following:\nvar s3 = require(\'s3policy\')\nvar myBucket = new s3(\'ABCDEFG123456\', \'HFSFGA9S8H997786AS8545ASF90SDF0UA\')')
}
this.accessKey = accessKey;
this.secretKey = secretKey;
this.readPolicy = function(key, bucket, duration, download, regionDomain, cb) {
var dateObj = new Date;
var expiration = new Date(dateObj.getTime() + duration * 1000);
expiration = Math.round(expiration.getTime() / 1000);
regionDomain = regionDomain || 's3';
var policy = 'GET\n\n\n' + expiration + '\n';
policy += '/' + bucket + '/' + key;
if (download) {
if(download[0] !== '"' || download[download.length-1] !== '"') {
download = '"' + download + '"';
}
policy += '?response-content-disposition=attachment;filename=' + download;
}
var signature = crypto.createHmac("sha1", this.secretKey).update(policy);
var url = 'https://'+regionDomain+'.amazonaws.com/';
url += bucket + '/';
url += key;
url += '?AWSAccessKeyId=' + this.accessKey;
url += '&Expires=' + expiration;
url += '&Signature=' + encodeURIComponent(signature.digest("base64"));
if (download) {
url += '&response-content-disposition=attachment;filename=' + encodeURIComponent(download);
}
if (typeof cb === 'function')
cb(null, url);
return url;
};
this.writePolicy = function(key, bucket, duration, filesize, useEncryption, cb) {
if (typeof useEncryption === 'function') {
cb = useEncryption;
useEncryption = false;
}
var dateObj = new Date;
var dateExp = new Date(dateObj.getTime() + duration * 1000);
var policy = {
"expiration":dateExp.toISOString(),
"conditions":[
{ "bucket":bucket },
["eq", "$key", key],
{ "acl":"private" },
["content-length-range", 0, filesize * 1000000],
["starts-with", "$Content-Type", ""]
]
};
if(useEncryption) {
policy.conditions.push({ 'x-amz-server-side-encryption': 'AES256' });
}
var policyString = JSON.stringify(policy);
var policyBase64 = new Buffer(policyString).toString('base64');
var signature = crypto.createHmac("sha1", this.secretKey).update(policyBase64);
var accessKey = this.accessKey;
s3Credentials = {
s3PolicyBase64:policyBase64,
s3Signature:signature.digest("base64"),
s3Key:accessKey
};
if (typeof cb === 'function')
cb(null, s3Credentials);
return s3Credentials;
};
}