-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.js
73 lines (62 loc) · 2.65 KB
/
main.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
crypto = require('crypto');
function s3instance(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, cb) {
var dateObj = new Date;
var expiration = new Date(dateObj.getTime() + duration * 1000);
expiration = Math.round(expiration.getTime() / 1000);
var policy = 'GET\n\n\n' + expiration + '\n';
policy += '/' + bucket + '/' + key;
if (download) {
policy += '?response-content-disposition=attachment;filename=' + encodeURIComponent(download);
}
var signature = crypto.createHmac("sha1", this.secretKey).update(policy);
var url = 'https://s3.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 (cb) {
cb(null, url);
} else {
return url;
}
};
this.writePolicy = function(key, bucket, duration, filesize, cb) {
var dateObj = new Date;
var dateExp = new Date(dateObj.getTime() + duration * 1000);
var policy = {
"expiration":dateExp.getUTCFullYear() + "-" + dateExp.getUTCMonth() + 1 + "-" + dateExp.getUTCDate() + "T" + dateExp.getUTCHours() + ":" + dateExp.getUTCMinutes() + ":" + dateExp.getUTCSeconds() + "Z",
"conditions":[
{ "bucket":bucket },
["eq", "$key", key],
{ "acl":"private" },
["content-length-range", 0, filesize * 1000000],
["starts-with", "$Content-Type", ""]
]
};
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 (cb) {
cb(s3Credentials);
} else {
return s3Credentials;
}
};
}
module.exports = s3instance;