/
FacebookClient.js
364 lines (307 loc) · 10.7 KB
/
FacebookClient.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
* This file is part of node-facebook-client
*
* Copyright (c) 2010 DracoBlue, http://dracoblue.net/
*
* Licensed under the terms of MIT License. For the full copyright and license
* information, please see the LICENSE file in the root folder.
*/
var sys = require("sys");
var http = require("http");
var https = require("https");
var querystring = require("querystring");
var crypto = require("crypto");
var FacebookSession = require("./FacebookSession").FacebookSession;
var FacebookToolkit = require("./FacebookToolkit");
function doRequest(host, port, path, secure, method, data, parser) {
return function(cb) {
var protocol = http;
if(secure) protocol = https;
var options = {
host: host,
port: port,
path: path,
method: method || 'GET'
};
var timed_out = false;
var timeout_timer = null;
var request = protocol.request(options, function(response){
response.setEncoding("utf8");
var body = [];
response.on("data", function (chunk) {
body.push(chunk);
});
response.on("end", function () {
if (timed_out)
{
return;
}
clearTimeout(timeout_timer);
cb(parser(body.join("")));
});
});
timeout_timer = setTimeout(function() {
timed_out = true;
try
{
request.abort();
}
catch (error)
{
}
cb();
}, 10000);
if(data != null)
{
request.write(querystring.stringify(data));
}
request.end();
};
};
function doRawJsonRequest(host, port, path, secure, method, data) {
return doRequest(host, port, path, secure, method, data, JSON.parse);
};
function doRawQueryRequest(host, port, path, secure, method, data) {
return doRequest(host, port, path, secure, method, data, querystring.parse);
};
var FacebookClient = function(api_key, api_secret, options) {
var self = this;
this.options = options || {};
this.options.facebook_graph_server_host = this.options.facebook_graph_server_host || 'graph.facebook.com';
this.options.facebook_graph_server_port = this.options.facebook_graph_server_port || '80';
this.options.facebook_graph_secure_server_port = this.options.facebook_graph_secure_server_port || '443';
this.options.facebook_graph_secure_server_host = this.options.facebook_graph_secure_server_host || 'graph.facebook.com';
this.options.facebook_server_host = this.options.facebook_server_host || 'api.facebook.com';
this.options.facebook_server_port = this.options.facebook_server_port || '443';
this.options.facebook_server_path = this.options.facebook_server_path || '/method/';
var doRestCall = function(method, params, access_token) {
var request_path_array = [self.options.facebook_server_path, method, '?'];
params = params || {};
params['access_token'] = access_token;
params['format'] = "json";
var is_first = true;
for (var key in params) {
if (is_first) {
is_first = false;
} else {
request_path_array.push('&');
}
if (typeof params[key] === 'object') {
params[key] = JSON.stringify(params[key]);
}
request_path_array.push(encodeURIComponent(key));
request_path_array.push("=");
request_path_array.push(encodeURIComponent(params[key]));
}
console.log(request_path_array.join(''));
return doRawJsonRequest(self.options.facebook_server_host, self.options.facebook_server_port, request_path_array.join(''), true);
};
this.restCall = function(method, params, access_token) {
return doRestCall(method, params, access_token);
};
this.graphCall = function(path, params, method) {
/*
* Default to take HTTP because it's faster.
*/
var host = self.options.facebook_graph_server_host;
var port = self.options.facebook_graph_server_port;
var secure = false;
var data = null;
if (params.access_token) {
/*
* We have to do a secure request, because the access_token is given. This is HTTPS.
*/
host = self.options.facebook_graph_secure_server_host;
port = self.options.facebook_graph_secure_server_port;
secure = true;
}
for (var key in params) {
if (params.hasOwnProperty(key) && typeof params[key] === 'object') {
params[key] = JSON.stringify(params[key]);
}
}
if (method == 'POST') {
data = params;
} else {
path = path + '?' + querystring.stringify(params);
}
return doRawJsonRequest(host, port, path, secure, method, data);
};
this.getAccessToken = function(params) {
var access_params = {
client_id: api_key,
client_secret: api_secret
};
for (var key in params) {
access_params[key] = params[key];
}
return function(cb) {
doRawQueryRequest(self.options.facebook_graph_secure_server_host, self.options.facebook_graph_secure_server_port, "/oauth/access_token" + '?' + querystring.stringify(access_params), true)(function(response) {
if (!response) {
cb();
} else {
cb(response.access_token, response.expires);
}
});
};
};
this.signaturePayload = function(payload) {
var hmac = crypto.createHmac('sha256', api_secret);
hmac.update(payload);
return hmac.digest('hex');
};
};
FacebookClient.prototype.getSessionByAccessToken = function(access_token) {
var self = this;
return function(cb) {
var session = new FacebookSession(self, access_token);
cb(session);
};
};
FacebookClient.prototype.getSessionByOauthCode = function(oauth_code) {
var self = this;
return function(cb) {
var session = new FacebookSession(self, null, oauth_code);
cb(session);
};
};
FacebookClient.prototype.getSessionByFbsCookie = function(fbs_cookie) {
var self = this;
return function(cb) {
var facebook_cookie = querystring.parse(fbs_cookie);;
if (!facebook_cookie)
{
/*
* The cookie cannot be parsed.
*/
cb();
return ;
}
if (!facebook_cookie['access_token'] || !facebook_cookie['expires']) {
/*
* We don't have an access_token nor expires, this won't work.
*/
cb();
return ;
}
var now = new Date();
var expires_time = parseInt(facebook_cookie['expires'], 10) * 1000;
if (now.getTime() < expires_time)
{
/*
* The token is expired.
*/
cb();
return ;
}
self.getSessionByAccessToken(facebook_cookie['access_token'])(cb);
};
};
FacebookClient.prototype.convertBase64ToHex = function(base64_string) {
var buffer = new Buffer(base64_string, 'base64');
try
{
return buffer.toString('hex');
}
catch (error)
{
/*
* We actually don't have a toString('hex') implementation, let's do
* it on our own!
*/
var toHex = function (n) {
return ((n < 16) ? '0' : '') + n.toString(16);
}
var hex_string = '';
var length = buffer.length;
for (var i = 0; i < length; i++) {
hex_string += toHex(buffer[i]);
}
return hex_string;
}
};
FacebookClient.prototype.getSessionByFbsrCookie = function(fbsr_cookie) {
var self = this;
return function(cb) {
var facebook_cookie = null;
var fbsr_cookie_parts = fbsr_cookie.split('.');
var signature = self.convertBase64ToHex(fbsr_cookie_parts[0].replace(/\-/g, '+').replace(/\_/g, '/'));
var payload = fbsr_cookie_parts[1];
var facebook_cookie_raw_json = new Buffer(payload.replace(/\-/g, '+').replace(/\_/g, '/'), 'base64').toString('binary');
try
{
facebook_cookie = JSON.parse(facebook_cookie_raw_json);
}
catch (error)
{
/*
* Invalid json :(
*/
facebook_cookie = null;
}
if (!facebook_cookie)
{
/*
* The cookie cannot be parsed.
*/
cb();
return ;
}
if (!facebook_cookie['algorithm'] || !facebook_cookie['code'] || !facebook_cookie['issued_at']) {
/*
* We don't have an algorithm, code or issued_at, this won't work.
*/
cb();
return ;
}
if (facebook_cookie['algorithm'].toUpperCase() != 'HMAC-SHA256')
{
/*
* We cannot support any other alogrithm at the moment (actually
* this is the only one facebook supports right now).
*/
cb();
return ;
}
var expected_signature = self.signaturePayload(payload);
if (expected_signature !== signature)
{
/*
* The signature was wrong.
*/
cb();
return ;
}
self.getSessionByOauthCode(facebook_cookie['code'])(cb);
};
};
FacebookClient.prototype.getSessionByRequestHeaders = function(request_headers) {
var self = this;
return function(cb) {
if (!request_headers['cookie'])
{
/*
* We have not even cookies on this request!
*/
cb();
return
}
var facebook_cookie_raw = request_headers["cookie"].match(/fbs_[\d]+\=\"([^; ]+)\"/);
if (facebook_cookie_raw)
{
self.getSessionByFbsCookie(facebook_cookie_raw[1])(cb);
return ;
}
facebook_cookie_raw = request_headers["cookie"].match(/fbsr_[\d]+\=([^; ]+)/);
if (facebook_cookie_raw)
{
self.getSessionByFbsrCookie(facebook_cookie_raw[1])(cb);
return ;
}
/*
* There is no such thing as a fbs_ or fbsr_ cookie in the request.
*/
cb();
};
};
exports.FacebookClient = FacebookClient;