-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
70 lines (60 loc) · 2.05 KB
/
auth.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
var crypto = require('crypto');
AccessID = "YOURACCESSID";
AccessKey = "YOURACCESSKEY";
function GenAuthorization(signature) {
authorization = "QS-HMAC-SHA256 " + AccessID + ":" + signature;
return authorization;
}
exports.GenAuthorization = GenAuthorization;
function GenSignature(method, authpath, headers, params) {
// Append method
var stringToSign = "";
stringToSign += method.toUpperCase();
// Append Content-Type and Content-Md5
var ContentType = headers['Content-Type'] || "";
var ContentMD5 = headers['Content-MD5'] || "";
stringToSign += "\n" + ContentType + "\n" + ContentMD5;
// Append time
var dateStr = headers['Date'] || "";
stringToSign += "\n" + dateStr;
// Generate canonicalized headers
var signedHeaders = genSignedHeaders(headers);
for (item in signedHeaders.sort()) {
key = signedHeaders[item];
stringToSign += "\n" + key.toLowerCase() +":" + headers[key];
}
// Generate canonicalized resource
var canonicalizedQuery = genCanonicalizedQuery(params);
var canonicalizedResource = authpath;
if (canonicalizedQuery) {
canonicalizedResource += "?" + canonicalizedQuery;
}
stringToSign += "\n" + canonicalizedResource;
console.log(stringToSign)
signature = crypto.createHmac('sha256', AccessKey).update(
stringToSign).digest().toString('base64').trim();
return signature;
}
exports.GenSignature = GenSignature;
function genSignedHeaders(headers) {
var signedHeaders = [];
for (var key in headers) {
if (key.toLowerCase().indexOf('x-qs-') === 0) {
signedHeaders.push(key);
}
}
return signedHeaders;
}
function genCanonicalizedQuery(params) {
var canonicalizedQuery = "";
for (var key in params) {
if (canonicalizedQuery) {
canonicalizedQuery += "&";
}
canonicalizedQuery += encodeURIComponent(key);
if (params[key]) {
canonicalizedQuery += "=" + encodeURIComponent(params[key]);
}
}
return canonicalizedQuery;
}