forked from jproulx/Gigya-Node-SDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
384 lines (381 loc) · 12.7 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
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*globals require, module, Buffer */
"use strict";
var services = {
'socialize' : [
'checkin', 'deleteAccount', 'delUserSettings', 'exportUsers',
'facebookGraphOperation', 'getAlbums', 'getContacts', 'getFeed',
'getFriendsInfo', 'getPhotos', 'getPlaces', 'getRawData',
'getReactionsCount', 'getSessionInfo', 'getTopShares', 'getUserInfo',
'getUserSettings', 'incrementReactionsCount', 'logout', 'notifyLogin',
'notifyRegistration', 'publishUserAction', 'removeConnection',
'sendNotification', 'setStatus', 'setUID', 'setUserInfo',
'setUserSettings', 'shortenURL'
],
'accounts' : [
'deleteAccount', 'deleteScreenSet', 'finalizeRegistration', 'getAccountInfo',
'getConflictingAccount', 'getCounters', 'getPolicies', 'getProfilePhoto',
'getRegisteredCounters', 'getSchema', 'getScreenSets', 'importProfilePhoto',
'incrementCounters', 'initRegistration', 'isAvailableLoginID', 'linkAccounts',
'login', 'logout', 'notifyLogin', 'publishProfilePhoto', 'register',
'registerCounters', 'resendVerificationCode', 'resetPassword', 'search',
'setAccountInfo', 'setPolicies', 'setProfilePhoto', 'setSchema', 'setScreenSet',
'socialLogin', 'unregisterCounters', 'uploadProfilePhoto',
// Two-Factor Authentication
// Added in v5.0
'tfa.deactivateProvider', 'tfa.finalizeTFA', 'tfa.getCertificate',
'tfa.getProviders', 'tfa.initTFA', 'tfa.unregisterDevice'
],
'comments' : [
'analyzeMediaItem', 'deleteComment', 'flagComment', 'getCategories',
'getCategoryInfo', 'getComments', 'getRelatedUsers', 'getStreamInfo',
'getTopRatedStreams', 'getTopStreams', 'getUserComments', 'getUserHighlighting',
'getUserOptions', 'highlightUser', 'moveComments', 'postComment',
'getCategoryInfo', 'setStreamInfo', 'setUserOptions', 'subscribe', 'unsubscribe',
'updatedComment', 'vote'
],
'gm' : [
'deletAction', 'deleteChallenge', 'deleteChallengeVariant',
'getActionConfig', 'getActionsLog', 'getChallengeConfig',
'getChallengeStatus', 'getChallengeVariant', 'getGlobalConfig',
'getTopUsers', 'notifyAction', 'redeemPoints', 'resetLevelStatus',
'setAccountConfig', 'setChallengeConfig', 'setGlobalConfig'
],
'reports' : [
'getAccountsStats', 'getChatStats', 'getCommentsStats',
'getFeedStats', 'getGMStats', 'getGMTopUsers', 'getGMUserStats',
'getIRank', 'getReactionsStats', 'getSocializeStats'
],
'ds' : [
'delete', 'get',
'getSchema', 'setSchema',
'search',
'store'
],
// Federated Identity Providers (FIdP) / SAML
// Added in v5.1
'fidm' : [
'saml.delIdP', 'saml.getConfig', 'saml.getRegisteredIdPs',
'saml.importIdPMetadata', 'saml.registerIdP', 'saml.setConfig'
],
// Added in v2.0
'ids' : [
'deleteAccount', 'getAccountInfo', 'getCounters',
'getRegisteredCounters', 'getSchema', 'incrementCounters',
'registerCounters', 'search', 'setAccountInfo',
'setSchema', 'unregisterCounters'
],
// Replaced with Identity Storage v2.0
// GCS is deprecated as v5.2 Aug.2014
'gcs' : [
'deleteObjectData', 'deleteUserData', 'getobjectData',
'getUserData', 'search', 'setObjectData', 'setUserData'
],
};
/**
* Shallow object merge
*
* @access private
* @param Object dest
* @param Object from
* @return Object
*/
function merge(dest, from) {
var target = {},
props = null;
// First, copy all items from destination to new object
props = Object.getOwnPropertyNames(dest);
props.forEach(function (name) {
var destination = Object.getOwnPropertyDescriptor(dest, name);
Object.defineProperty(target, name, destination);
});
// Merge values with additional object
props = Object.getOwnPropertyNames(from);
props.forEach(function (name) {
if (name in dest) {
var destination = Object.getOwnPropertyDescriptor(from, name);
Object.defineProperty(target, name, destination);
}
});
// Clean return object
return target;
}
/**
* Creates a random nonce for signature
*
* @access private
* @param Number size
* @return String
*/
function createNonce(size) {
var result = [],
chars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
],
// char_pos = 0,
nonce_chars_length = chars.length,
i = 0;
for (i = 0; i < size; i += 1) {
result[i] = chars[Math.floor(Math.random() * nonce_chars_length)];
}
return result.join('');
}
/**
* Creates an appropriate HTTP client connection and returns the request
*
* @access private
* @param Object options
* @param Boolean secure
* @return http.request
*/
function createClient(options, secure) {
var proto = null;
if (secure === true) {
options.port = 443;
proto = require('https');
} else {
options.port = 80;
proto = require('http');
}
return proto.request(options);
}
/**
* Tweaks the URI encoding formula to what OAuth expects
*
* @access private
* @param Mixed value
* @return String
*/
function encode(value) {
if (value === null || value === '') {
return '';
} else {
value = encodeURIComponent(value);
return value
.replace(/\!/g, "%21")
.replace(/\'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A");
}
}
/**
* Creates a signature that Gigya is expecting for calls
*
* @access private
* @param String string string to sign
* @param String key base64 encoded client secret key
* @return String
*/
function createSignature(string, key) {
var crypto = require('crypto'),
salt = new Buffer(key, 'base64').toString('binary'),
signature = crypto.createHmac('sha1', salt).update(string).digest('base64');
return signature;
}
/**
* Creates an OAuth compatible signature based on request parameters
*
* @access private
* @param Object options
* @param String key
* @return String
*/
function createRequestSignature(options, key) {
var domain = [options.service, options.domain].join('.'),
path = '/' + [options.service, options.method].join('.'),
proto = 'http://',
url = null,
base = null,
params = [];
// Switch protocol
if (options.ssl === true) {
proto = 'https://';
}
// Sort and encode parameters
Object.getOwnPropertyNames(options.params).forEach(function (name) {
params.push(encode(name) + '=' + encode(options.params[name]));
});
params = params.sort().join('&');
params = encode(params);
// Put together the full URL and encode it again
url = encode([proto, domain, path].join(''));
// Compose the final string
base = [options.reqMethod.toUpperCase(), url, params].join('&');
// Return the final signature
return createSignature(base, options.secret);
}
/**
* Server side Gigya SDK for NodeJS
*
* @access public Configuration details, mainly API Key and Secret Token
* @param Object options
*/
function GigyaSDK(config) {
if (!(this instanceof GigyaSDK)) {
return new GigyaSDK(config);
}
var self = this,
wrappers = {},
defaults = {
'apiKey' : null,
'secret' : null,
'domain' : 'gigya.com',
'datacenter' : 'us1',
'service' : 'socialize',
'method' : null,
'reqMethod' : 'GET',
'nonceSize' : 32,
'ssl' : false
};
this.options = merge(defaults, config);
Object.getOwnPropertyNames(services).forEach(function (service) {
wrappers[service] = {};
services[service].forEach(function (method) {
wrappers[service][method] = function (params, callback) {
return self[service](method, params, callback);
};
});
});
this.services = wrappers;
}
/**
* Only export the public facing Gigya class
*/
module.exports = GigyaSDK;
/**
* Low level access to create and issue a Gigya request asynchronously
*
* @access public
* @param Object options
* @param Function callback
* @return void
*/
GigyaSDK.prototype.request = function (options, callback) {
var qs = require('querystring'),
// fs = require('fs'),
opts = null,
request = null;
// Mash together all of the options
opts = merge(this.options, options);
// Create parameter string
opts.params = options.params;
opts.params.apiKey = opts.apiKey;
opts.params.format = 'json';
if (opts.ssl === true) {
opts.params.secret = opts.secret;
} else {
opts.params.timestamp = Math.round((new Date()).getTime() / 1000);
opts.params.nonce = createNonce(opts.nonceSize);
opts.params.sig = createRequestSignature(opts);
}
opts.params = qs.stringify(opts.params);
// Setup request parameters
request = {
'host' : [opts.service, opts.datacenter, opts.domain].join('.'),
'path' : '/' + [opts.service, opts.method].join('.'),
'method' : opts.reqMethod,
'headers' : {
'User-Agent' : 'Node-Gigya-SDK'
}
};
// Add appropriate headers in case of POST requests
if (opts.reqMethod === 'POST') {
request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
request.headers['Content-Length'] = opts.params.length;
} else {
request.path += '?' + opts.params;
}
// Perform raw request
return this.raw(request, opts, callback);
};
/**
* Handles the grunt work of creating a connection and issuing a request
*
* @access public
* @param Object request
* @param Object options
* @param Function callback
* @return void
*/
GigyaSDK.prototype.raw = function (request, options, callback) {
var client = null,
chunks = [];
// Create request
client = createClient(request, options.ssl);
client.on('response', function (response) {
response.setEncoding('utf8');
// Collect chunks
response.on('data', function (chunk) {
chunks.push(chunk);
});
// Mash all chunks together and issue the callback
response.on('end', function () {
var result = JSON.parse(chunks.join(''));
if (result.errorCode) {
callback(result);
} else {
callback(null, result);
}
});
});
// Request level errors
client.on('error', function (error) {
return callback(error);
});
// We need to write the POST parameters to the request stream
if (options.reqMethod.toUpperCase() === 'POST') {
client.write(options.params);
}
client.end();
};
/**
* Validates the user information signature
*
* @access public
* @param String UID
* @param String timestamp
* @param String signature
* @return Boolean
*/
GigyaSDK.prototype.validateUserSignature = function (UID, timestamp, signature) {
var base = [timestamp, UID].join('_');
var expected = createSignature(base, this.options.secret);
return expected === signature;
};
/**
* Validates the user's friend information signature
*
* @access public
* @param String UID
* @param String timestamp
* @param String friendUID
* @param String signature
* @return Boolean
*/
GigyaSDK.prototype.validateFriendSignature = function (UID, timestamp, friendUID, signature) {
var base = [timestamp, friendUID, UID].join('_'),
expected = createSignature(base, this.options.secret);
return expected === signature;
};
Object.getOwnPropertyNames(services).forEach(function (service) {
/**
* Asynchronous caller for Socialize services
*
* @access public
* @param String method
* @param Object params
* @param Function callback
* @return void
*/
GigyaSDK.prototype[service] = function (method, params, callback) {
return this.request({
'service' : service,
'method' : method,
'params' : params
}, callback);
};
});