forked from mogya/oauth-adapter
/
oauth_adapter.js
553 lines (488 loc) · 19.2 KB
/
oauth_adapter.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/*
* ATTENTION: Some efforts has been put in order to produce this code.
* If you like and use it consider making a dontation in order
* to allow me to do more and provide you with more solutions.
*
* Thanks,
* David Riccitelli
*
* To donate, copy and paste this link in your browser:
* https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=T5HUU4J5EQTJU&lc=IT&item_name=OAuth%20Adapter¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted
*
* Copyright 2010 David Riccitelli, Interact SpA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This library currently works only with Twitter, although I'd like to
* spend some more time to make it generally compatible with other services
* too.
*
* Sample use with Twitter:
// create a new OAuthAdapter instance by passing by your consumer data and signature method
var oAuthAdapter = new OAuthAdapter(
'your-consumer-secret',
'your-consumer-key',
'HMAC-SHA1');
// load the access token for the service (if previously saved)
oAuthAdapter.loadAccessToken('twitter');
// consume a service API - in this case the status update by Twitter
oAuthAdapter.send('https://api.twitter.com/1/statuses/update.json', [['status','Hey @ziodave, I managed to use the #oauth adapter for @titanium consuming @twitterapi']],'Twitter','Tweet published.','Tweet not published.');
// if the client is not authorized, ask for authorization. the previous tweet will be sent automatically after authorization
if (oAuthAdapter.isAuthorized() == false)
{
// this function will be called as soon as the application is authorized
var receivePin = function() {
// get the access token with the provided pin/oauth_verifier
oAuthAdapter.getAccessToken('https://api.twitter.com/oauth/access_token');
// save the access token
oAuthAdapter.saveAccessToken('twitter');
};
// show the authorization UI and call back the receive PIN function
oAuthAdapter.showAuthorizeUI('https://api.twitter.com/oauth/authorize?' + oAuthAdapter.getRequestToken('https://api.twitter.com/oauth/request_token'), receivePin);
}
*/
/*
* The Adapter needs 2 external libraries (oauth.js, sha1.js) hosted at
* http://oauth.googlecode.com/svn/code/javascript/
*
* Save them locally in a lib subfolder
*/
// create an OAuthAdapter instance
var OAuthAdapter = function(pConsumerSecret, pConsumerKey, pSignatureMethod){
Ti.API.info('*********************************************');
Ti.API.info('If you like the OAuth Adapter, consider donating at');
Ti.API.info('https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=T5HUU4J5EQTJU&lc=IT&item_name=OAuth%20Adapter¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted');
Ti.API.info('*********************************************');
// will hold the consumer secret and consumer key as provided by the caller
var consumerSecret = pConsumerSecret;
var consumerKey = pConsumerKey;
// will set the signature method as set by the caller
var signatureMethod = pSignatureMethod;
// the pin or oauth_verifier returned by the authorization process window
var pin = null;
// will hold the request token and access token returned by the service
var requestToken = null;
var requestTokenSecret = null;
var accessToken = null;
var accessTokenSecret = null;
// the accessor is used when communicating with the OAuth libraries to sign the messages
var accessor = {
consumerSecret: consumerSecret,
tokenSecret: ''
};
// holds actions to perform
var actionsQueue = [];
// will hold UI components
var window = null;
var view = null;
var webView = null;
var receivePinCallback = null;
var HttpClientWrapper = function (){
this.httpMethod = 'POST';
this.requestURL = '';
this.async = true;
};
HttpClientWrapper.prototype.open = function(method, url, async){
this.httpMethod = method;
this.requestURL = url;
if(async === false){
this.async = false;
}
};
HttpClientWrapper.prototype.send = function(parameters, success, failure){
var client = Ti.Network.createHTTPClient();
client.onload = function (){
return success(this);
};
client.onerror = failure;
client.open(this.httpMethod, this.requestURL, this.async);
if(/android/i.test(Titanium.Platform.osname)){
var post = [];
for(var p in parameters){
if(parameters.hasOwnProperty(p)){
post.push(encodeURIComponent(p) + '=' + encodeURIComponent(parameters[p]));
}
}
return client.send(post.join('&'));
}
return client.send(parameters);
};
var createHttpClient = function (){
return new HttpClientWrapper();
};
this.loadAccessToken = function(pService){
Ti.API.debug('Loading access token for service [' + pService + '].');
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
if (!file.exists()) {
return;
}
var contents = file.read();
if (contents == null) {
return;
}
try {
var config = JSON.parse(contents.text);
} catch(ex) {
return;
}
if (config.accessToken) {
accessToken = config.accessToken;
}
if (config.accessTokenSecret) {
accessTokenSecret = config.accessTokenSecret;
}
Ti.API.debug('Loading access token: done [accessToken:' + accessToken + '][accessTokenSecret:' + accessTokenSecret + '].');
};
this.saveAccessToken = function(pService){
Ti.API.debug('Saving access token [' + pService + '].');
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
if (file == null) {
file = Ti.Filesystem.createFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
}
file.write(JSON.stringify({
accessToken: accessToken,
accessTokenSecret: accessTokenSecret
}));
Ti.API.debug('Saving access token: done.');
};
// will tell if the consumer is authorized
this.isAuthorized = function(){
return ! (accessToken == null || accessTokenSecret == null);
};
// creates a message to send to the service
this.createMessage = function(pUrl, method){
var message = {
action: pUrl ,
method: (method) ? method : 'POST' ,
parameters: []
};
message.parameters.push(['oauth_consumer_key', consumerKey]);
message.parameters.push(['oauth_signature_method', signatureMethod]);
return message;
};
// returns the pin
this.getPin = function() {
return pin;
};
// requests a requet token with the given Url
this.getRequestToken = function(pUrl, callback){
accessor.tokenSecret = '';
var message = this.createMessage(pUrl);
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var client = createHttpClient();
client.open('POST', pUrl);
client.send(OAuth.getParameterMap(message.parameters), function (http){
var text = http.responseText;
Ti.API.debug('request token got the following response: ' + text);
var responseParams = OAuth.getParameterMap(text);
requestToken = responseParams.oauth_token;
requestTokenSecret = responseParams.oauth_token_secret;
return callback(text);
});
};
// unloads the UI used to have the user authorize the application
var destroyAuthorizeUI = function(){
Ti.API.debug('destroyAuthorizeUI');
// if the window doesn't exist, exit
if (window == null) {
return;
}
// remove the UI
try {
Ti.API.debug('destroyAuthorizeUI:webView.removeEventListener');
webView.removeEventListener('load', this.authorizeUICallback);
Ti.API.debug('destroyAuthorizeUI:window.close()');
window.hide();
// Ti.API.debug('destroyAuthorizeUI:window.remove(view)');
// window.remove(view);
// Ti.API.debug('destroyAuthorizeUI:view.remove(webView)');
// view.remove(webView);
// Ti.API.debug('destroyAuthorizeUI:nullifying');
// webView = null;
// view = null;
// window = null;
} catch(ex) {
Ti.API.debug('Cannot destroy the authorize UI. Ignoring.');
}
};
// looks for the PIN everytime the user clicks on the WebView to authorize the APP
// currently works with TWITTER
this.authorizeUICallback = function(e){
Ti.API.debug('authorizeUILoaded');
// invalid HTML source occured exception to parseString, browser evalJS call
/*
var xmlDocument = Ti.XML.parseString(e.source.html);
var nodeList = xmlDocument.getElementsByTagName('div');
*/
var browser = e.source;
var viewport = [];
viewport.push('(function (){');
viewport.push(' var head = document.getElementsByTagName("head")[0];');
viewport.push(' var viewport = document.createElement("meta");');
viewport.push(' viewport.setAttribute("name", "viewport");');
viewport.push(' viewport.setAttribute("content", "height=device-height, width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no");');
viewport.push(' head.appendChild(viewport);');
viewport.push('})()');
browser.evalJS(viewport.join('\n'));
var loc = browser.evalJS('(function (){return location.href})()');
Titanium.API.debug('webView location: ' + loc);
//
// TODO: switch if location: service provider pin read
//
if(/^https\:\/\/www\.google\.com\/accounts\/(.+\/)?OAuthAuthorizeToken$/.test(loc)){
var title = browser.evalJS('(function (){return document.title})()');
Titanium.API.debug('OAuthAuthorize: ' + title);
var m = title.match(/\[ov\:(.*)\]/);
if(m && 0 < m.length){
pin = m[1];
if (receivePinCallback) {
setTimeout(receivePinCallback, 100);
}
}
return destroyAuthorizeUI();
}
if('https://api.twitter.com/oauth/authorize' == loc){
var js = [];
js.push('(function (){');
js.push(' var nodeList = document.getElementsByTagName("div");');
js.push(' for(var i = 0, length = nodeList.length; i < length; ++i){');
js.push(' var node = nodeList[i];');
js.push(' var id = node.attributes.getNamedItem("id");');
js.push(' if(id && id.nodeValue == "oauth_pin"){');
js.push(' return node.text;');
js.push(' }');
js.push(' }');
js.push(' return "";');
js.push('})()');
var result = browser.evalJS(js.join('\n'));
if('' != result){
pin = result;
if (receivePinCallback) {
setTimeout(receivePinCallback, 100);
}
destroyAuthorizeUI();
}
}
};
this.createWindow = function (){
var w = Ti.UI.createWindow({
top: 0,
modal: true,
fullscreen: true
});
w.open();
return w;
};
this.setupWindow = function(childContent){
if(null == window){
window = this.createWindow();
}
window.add(childContent);
};
// shows the authorization UI
this.showAuthorizeUI = function(pUrl, pReceivePinCallback){
Titanium.API.debug('showAuthroizeUI');
receivePinCallback = pReceivePinCallback;
/*
var transform = Ti.UI.create2DMatrix().scale(0);
view = Ti.UI.createView({
top: 5,
width: 310,
height: 450,
border: 10,
backgroundColor: 'white',
borderColor: '#aaa',
borderRadius: 20,
borderWidth: 5,
zIndex: -1,
transform: transform
});
*/
webView = Ti.UI.createWebView({
url: pUrl,
scalesPageToFit: true,
touchEnabled: true,
top: 0,
border: 10,
backgroundColor: 'white',
borderColor: '#aaa',
borderRadius: 20,
borderWidth: 5,
});
webView.addEventListener('load', this.authorizeUICallback);
//view.add(webView);
this.setupWindow(webView);
/*
var animation = Ti.UI.createAnimation();
animation.transform = Ti.UI.create2DMatrix();
animation.duration = 500;
view.animate(animation);
*/
};
this.getAccessToken = function(pUrl, callback){
accessor.tokenSecret = requestTokenSecret;
var message = this.createMessage(pUrl);
message.parameters.push(['oauth_token', requestToken]);
message.parameters.push(['oauth_verifier', pin]);
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
for (var p in parameterMap){
if(parameterMap.hasOwnProperty(p)){
Ti.API.debug(p + ': ' + parameterMap[p]);
}
}
var client = createHttpClient();
client.open('POST', pUrl);
client.send(parameterMap, function(http){
var text = http.responseText;
Ti.API.debug('*** get access token, Response: ' + text);
var responseParams = OAuth.getParameterMap(text);
accessToken = responseParams.oauth_token;
accessTokenSecret = responseParams.oauth_token_secret;
processQueue();
return callback(text);
});
};
var processQueue = function(){
Ti.API.debug('Processing queue.');
while ((q = actionsQueue.shift()) != null){
send(q);
}
Ti.API.debug('Processing queue: done.');
};
var oauthParams = 'OAuth realm,oauth_version,oauth_consumer_key,oauth_nonce,oauth_signature,oauth_signature_method,oauth_timestamp,oauth_token'.split(',');
var removeOAuthParams = function(parameters) {
var checkString = oauthParams.join(',') + ',';
for (var p in parameters) {
if (checkString.indexOf(p + ',') >= 0) {
delete parameters[p];
}
}
};
var makePostURL = function(url,parameters) {
var checkString = oauthParams.join(',') + ',';
var query = [];
var newParameters = [];
for (var i = 0 , len = parameters.length; i < len ; i++) {
var item = parameters[i];
if (checkString.indexOf(item[0] + ',') < 0) {
query.push(encodeURIComponent(item[0]) + '=' + encodeURIComponent(item[1]));
} else {
newParameters.push(item);
}
}
parameters = newParameters;
if (query.length) {
query = query.join('&');
return [url + ((url.indexOf('?') >= 0) ? '&' : '?') + query, parameters];
}
return [url, parameters];
};
var makeGetURL = function(url, parameterMap) {
var query = [];
var keys = [];
for (var p in parameterMap) {
if(parameterMap.hasOwnProperty(p)){
query.push( encodeURIComponent(p) + "=" + encodeURIComponent(parameterMap[p]) );
}
}
query.sort();//(9.1.1. Normalize Request Parameters)
if (query.length) {
query = query.join('&');
return url + ((url.indexOf('?') >= 0) ? '&' : '?') + query;
}
return url;
};
var makeHeaderParam = function(parameterMap){
var header = [];
for(var p in parameterMap){
if(parameterMap.hasOwnProperty(p)){
header.push(encodeURIComponent(p) + '="' + encodeURIComponent(parameterMap[p]) + '"');
}
}
header.sort();//(9.1.1. Normalize Request Parameters)
return 'OAuth ' + header.join(', ');
};
var self = this;
var send = function(params) {
var pUrl = params.url;
var pParameters = params.parameters || [];
var pTitle = params.title;
var pMethod = params.method || 'POST';
var resultByXML = params.resultByXML || false;
var stickOAuthParam = params.stickOAuthParam || false;
Ti.API.debug('Sending a message to the service at [' + pUrl + '] with the following params: ' + JSON.stringify(pParameters));
if (accessToken == null || accessTokenSecret == null)
{
Ti.API.debug('The send status cannot be processed as the client doesn\'t have an access token. The status update will be sent as soon as the client has an access token.');
actionsQueue.push(params);
return;
}
accessor.tokenSecret = accessTokenSecret;
var message = self.createMessage(pUrl, pMethod);
message.parameters.push(['oauth_token', accessToken]);
for (var p in pParameters) {
if(pParameters.hasOwnProperty(p)){
message.parameters.push(pParameters[p]);
}
}
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
for (var pd in parameterMap) {
if(pParameters.hasOwnProperty(pd)){
Ti.API.debug(pd + ': ' + parameterMap[pd]);
}
}
var client = Ti.Network.createHTTPClient();
if (pMethod == 'GET') {
if(!stickOAuthParam){
pUrl = makeGetURL(pUrl, parameterMap);
}
Ti.API.debug('url for GET:' + pUrl);
}
client.onerror = function(e){
Ti.API.debug(e);
if(params.onError){
params.onError(e);
}
};
client.onload = function(){
Ti.API.debug('*** sendStatus, Response: [' + client.status + '] ' + client.responseText);
if (('' + client.status).match(/^20[0-9]/)) {
if(params.onSuccess){
params.onSuccess(client.responseText);
}
} else {
if(params.onError){
params.onError({error:'[' + client.status + '] ' + client.responseText});
}
}
};
client.open(pMethod, pUrl, false);
if(stickOAuthParam){
var header = makeHeaderParam(parameterMap);
Ti.API.debug('header = ' + header);
client.setRequestHeader('Authorization', header);
}
if (pMethod == 'GET') {
parameterMap = null;
}
client.send(parameterMap);
return null;
};
this.send = send;
};