-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
82 lines (61 loc) · 1.43 KB
/
server.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
//
// Initiate the node server
//
// Abstracted away for tidying
var proxy = require('./index');
var http = require('http');
var https = require('https');
var port = process.env.PORT || 5002;
// Start app
console.log("Proxy server listening on port "+ port);
http.createServer( proxy ).listen( port );
// Define the credentials
proxy.intervene = function( options, next ){
if( options.host === 'api.twitter.com' ){
getTwitterBearerToken(function(token){
// Update the options
options.headers['Authorization'] = 'Bearer '+token;
// Call next
next();
});
return;
}
// Nothing to do
next();
};
function getTwitterBearerToken(callback){
request( {
protocol : 'https:',
hostname : 'api.twitter.com',
headers : {
'Authorization' : 'Basic '+ process.env.TWITTER,
'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8'
},
path : '/oauth2/token',
method : 'POST'
}, 'grant_type=client_credentials', function(response){
var json;
try{
json = JSON.parse(response);
}catch(e){}
callback(json.access_token);
});
}
function request(options, body, callback ){
var req = ( options.protocol === 'https:' ? https : http ).request(options, function(res){
var data = '';
res.on('data', function(chunk){
data+=chunk;
});
res.on('end', function(){
callback(data);
});
});
req.on('error', function(){
console.log('whoops');
});
if(body){
req.write(body);
}
req.end();
}