forked from markgardner/passport-identityserver3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
108 lines (89 loc) · 2.8 KB
/
common.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var crypto = require('crypto'),
url = require('url'),
qs = require('querystring'),
extend = require('json-extend');
var agents = {
'http:': require('http'),
'https:': require('https')
};
function request(method, requestedUrl, headers, body, callback) {
var parsedUrl = url.parse(requestedUrl);
var req = agents[parsedUrl.protocol].request({
hostname: parsedUrl.hostname,
port: parsedUrl.port,
headers: headers,
path: parsedUrl.pathname,
method: method
}, function(res) {
var data = '';
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
callback(null, data);
});
});
req.setTimeout(instance.timeout, function() {
callback(new Error('Request timed out.'));
});
if(body) {
req.end(body);
} else {
req.end();
}
}
var instance = module.exports = {
timeout: 10000,
addQuery: function(url, params) {
var joinChar = ~url.indexOf('?') ? '&' : '?';
return url + joinChar + qs.stringify(params);
},
formatCert: function(x5c) {
var parts = ['-----BEGIN CERTIFICATE-----'];
while(x5c.length) {
parts.push(x5c.slice(0, 64));
x5c = x5c.slice(64);
}
parts.push('-----END CERTIFICATE-----\n');
return parts.join('\n');
},
randomHex: function(numOfChars) {
return crypto.randomBytes(numOfChars).toString('hex');
},
resolveUrl: function(req, absoluteOrRelative) {
var headers = req.headers,
protocol = headers['x-forwarded-proto'] || (req.connection.encrypted ? 'https' : 'http'),
host = headers.host,
path = req.url,
parsed = url.parse(absoluteOrRelative);
if(parsed.protocol) {
return absoluteOrRelative;
} else {
return url.resolve(protocol + '://' + host + path, absoluteOrRelative);
}
},
form: function(method, requestedUrl, body, headers, callback) {
extend(headers || (headers = {}), {
'Content-Type': 'application/x-www-form-urlencoded'
});
if(body) {
body = qs.stringify(body);
}
request(method, requestedUrl, headers, body, callback);
},
json: function(method, requestedUrl, body, headers, callback) {
extend(headers || (headers = {}), {
Accept: 'application/json'
});
if(body) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(body);
}
request(method, requestedUrl, headers, body, function(err, data) {
if(!err && data) {
data = JSON.parse(data);
}
callback(err, data);
});
}
};