-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth_adapter.js
406 lines (335 loc) · 13.4 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
/*
* 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
*/
Ti.include('lib/sha1.js');
Ti.include('lib/oauth.js');
// 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;
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 == false) 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
var createMessage = function(pUrl)
{
var message = {
action: pUrl
,
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)
{
accessor.tokenSecret = '';
var message = createMessage(pUrl);
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var client = Ti.Network.createHTTPClient();
client.open('POST', pUrl, false);
client.send(OAuth.getParameterMap(message.parameters));
var responseParams = OAuth.getParameterMap(client.responseText);
requestToken = responseParams['oauth_token'];
requestTokenSecret = responseParams['oauth_token_secret'];
Ti.API.debug('request token got the following response: ' + client.responseText);
return client.responseText;
}
// 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', 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
var authorizeUICallback = function(e)
{
Ti.API.debug('authorizeUILoaded');
var xmlDocument = Ti.XML.parseString(e.source.html);
var nodeList = xmlDocument.getElementsByTagName('div');
for (var i = 0; i < nodeList.length; i++)
{
var node = nodeList.item(i);
var id = node.attributes.getNamedItem('id');
if (id && id.nodeValue == 'oauth_pin')
{
pin = node.text;
if (receivePinCallback) setTimeout(receivePinCallback, 100);
id = null;
node = null;
destroyAuthorizeUI();
break;
}
}
nodeList = null;
xmlDocument = null;
};
// shows the authorization UI
this.showAuthorizeUI = function(pUrl, pReceivePinCallback)
{
receivePinCallback = pReceivePinCallback;
window = Ti.UI.createWindow({
modal: true,
fullscreen: true
});
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
});
closeLabel = Ti.UI.createLabel({
textAlign: 'right',
font: {
fontWeight: 'bold',
fontSize: '12pt'
},
text: '(X)',
top: 10,
right: 12,
height: 14
});
window.open();
webView = Ti.UI.createWebView({
url: pUrl,
autoDetect:[Ti.UI.AUTODETECT_NONE]
});
Ti.API.debug('Setting:['+Ti.UI.AUTODETECT_NONE+']');
webView.addEventListener('load', authorizeUICallback);
view.add(webView);
closeLabel.addEventListener('click', destroyAuthorizeUI);
view.add(closeLabel);
window.add(view);
var animation = Ti.UI.createAnimation();
animation.transform = Ti.UI.create2DMatrix();
animation.duration = 500;
view.animate(animation);
};
this.getAccessToken = function(pUrl)
{
accessor.tokenSecret = requestTokenSecret;
var message = 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)
Ti.API.debug(p + ': ' + parameterMap[p]);
var client = Ti.Network.createHTTPClient();
client.open('POST', pUrl, false);
client.send(parameterMap);
var responseParams = OAuth.getParameterMap(client.responseText);
accessToken = responseParams['oauth_token'];
accessTokenSecret = responseParams['oauth_token_secret'];
Ti.API.debug('*** get access token, Response: ' + client.responseText);
processQueue();
return client.responseText;
};
var processQueue = function()
{
Ti.API.debug('Processing queue.');
while ((q = actionsQueue.shift()) != null)
send(q.url, q.parameters, q.title, q.successMessage, q.errorMessage);
Ti.API.debug('Processing queue: done.');
};
// TODO: remove this on a separate Twitter library
var send = function(pUrl, pParameters, pTitle, pSuccessMessage, pErrorMessage)
{
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({
url: pUrl,
parameters: pParameters,
title: pTitle,
successMessage: pSuccessMessage,
errorMessage: pErrorMessage
});
return;
}
accessor.tokenSecret = accessTokenSecret;
var message = createMessage(pUrl);
message.parameters.push(['oauth_token', accessToken]);
for (p in pParameters) message.parameters.push(pParameters[p]);
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
for (var p in parameterMap)
Ti.API.debug(p + ': ' + parameterMap[p]);
var client = Ti.Network.createHTTPClient();
client.open('POST', pUrl, false);
client.send(parameterMap);
if (client.status == 200) {
Ti.UI.createAlertDialog({
title: pTitle,
message: pSuccessMessage
}).show();
} else {
Ti.UI.createAlertDialog({
title: pTitle,
message: pErrorMessage
}).show();
}
Ti.API.debug('*** sendStatus, Response: [' + client.status + '] ' + client.responseText);
return client.responseText;
};
this.send = send;
};