forked from dyashkir/amazon-s3-url-signer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (36 loc) · 1.41 KB
/
index.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
var join = require('path').join;
var crypto = require('crypto');
exports.urlSigner = function(key, secret, options){
options = options || {};
var endpoint = options.host || 's3.amazonaws.com';
var port = options.port || '80';
var protocol = options.protocol || 'http';
var subdomain = options.useSubdomain === true;
var hmacSha1 = function (message) {
return crypto.createHmac('sha1', secret)
.update(message)
.digest('base64');
};
var url = function (fname, bucket) {
if (subdomain) {
return protocol + '://'+ bucket + "." + endpoint + (port != 80 ? ':' + port : '') + (fname[0] === '/'?'':'/') + fname;
} else {
return protocol + '://'+ endpoint + (port != 80 ? ':' + port : '') + '/' + bucket + (fname[0] === '/'?'':'/') + fname;
}
};
return {
getUrl : function(verb, fname, bucket, expiresInMinutes){
var expires = new Date();
expires.setMinutes(expires.getMinutes() + expiresInMinutes);
var epo = Math.floor(expires.getTime()/1000);
var str = verb + '\n\n\n' + epo + '\n' + '/' + bucket + (fname[0] === '/'?'':'/') + fname;
var hashed = hmacSha1(str);
var urlRet = url(fname, bucket) +
( (fname.indexOf('?') == -1) ? '?' : '&') +
'Expires=' + epo +
'&AWSAccessKeyId=' + key +
'&Signature=' + encodeURIComponent(hashed);
return urlRet;
}
};
};