Skip to content

Instantly share code, notes, and snippets.

@nulltask
Created July 5, 2011 04:16
Show Gist options
  • Save nulltask/1064244 to your computer and use it in GitHub Desktop.
Save nulltask/1064244 to your computer and use it in GitHub Desktop.
oauth_adaptor.js.diff
27,30d26
< * 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.
< *
48c44
< // this function will be called as soon as the application is authorized
---
> // this function will be called as soon as the application is authorized
50,53c46,48
< // 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');
---
> oAuthAdapter.getAccessToken('https://api.twitter.com/oauth/access_token', function(){
> oAuthAdapter.saveAccessToken('twitter');
> });
56,57c51,56
< // 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);
---
> // show the authorization UI and call back the receive PIN function
> oAuthAdapter.getRequestToken('https://api.twitter.com/oauth/request_token', function(token){
> if(token){
> oAuthAdapter.showAuthorizeUI('https://api.twitter.com/oauth/authorize?' + token , receivePin);
> }
> });
58a58,64
> You can disable this feature by init 4th parameter if any problem.
> var oAuthAdapter = new OAuthAdapter(
> 'your-consumer-secret',
> 'your-consumer-key',
> 'HMAC-SHA1',
> {useQueue:false}
> );
67,68c73,74
< Ti.include('./lib/sha1.js');
< Ti.include('./lib/oauth.js');
---
> Ti.include(path_lib+'sha1.js');
> Ti.include(path_lib+'oauth.js');
71c77
< var OAuthAdapter = function(pConsumerSecret, pConsumerKey, pSignatureMethod)
---
> var OAuthAdapter = function(pConsumerSecret, pConsumerKey, pSignatureMethod, params)
73,78d78
<
< 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&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted');
< Ti.API.info('*********************************************');
<
101a102
> var useQueue = true;
103a105,110
> if(params){
> if (params.useQueue == false){
> useQueue = false;
> }
> }
>
119c126
<
---
> var config;
122c129
< var config = JSON.parse(contents.text);
---
> config = JSON.parse(contents.text);
127a135
> if (!config) { return; }
146,148d153
< this.deleteAccessToken = function(pService)
< {
< Ti.API.debug('Deleting access token for service [' + pService + '].');
149a155
> this.clearAccessToken = function(pService){
151,156c157,161
< if (file.exists == false) return;
<
< var result = file.deleteFile();
< if (result == false) {
< Ti.API.error('Deleting access token: error [accessToken:' + accessToken + '][accessTokenSecret:' + accessTokenSecret + '].');
< return;
---
> if (file == null) file = Ti.Filesystem.createFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
> file.write(JSON.stringify(
> {
> accessToken: null,
> accessTokenSecret: null
158c163
<
---
> ));
160a166
> };
162c168,173
< Ti.API.debug('Deleting access token: done [accessToken:' + accessToken + '][accessTokenSecret:' + accessTokenSecret + '].');
---
> this.clearActionsQueue = function(){
> while ((q = actionsQueue.shift()) != null){
> var p = q.parameters || [];
> if(p.onError)
> p.onError({error:'clearActionsQueue() was called'});
> }
164c175
<
---
>
190c201
< this.getRequestToken = function(pUrl)
---
> this.getRequestToken = function(pUrl,pCallback)
199c210,223
< client.open('POST', pUrl, false);
---
> client.onload = function(){
> 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);
> pCallback(client.responseText);
> };
> client.onerror = function(e){
> Ti.API.debug(e);
> Ti.API.debug({error:'[' + client.status + '] ' + client.responseText});
> pCallback(null);
> };
> client.open('POST', pUrl, true);
> Ti.API.debug(pUrl);
201,209c225,226
<
< 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;
< }
---
> Ti.API.debug(OAuth.getParameterMap(message.parameters));
> };
216c233
< if (window == null) return;
---
> if (!window) return;
221,232c238,245
< 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;
---
> webView.removeEventListener('load', authorizeUICallback);
> window.hide();
> window.close();
> window.remove(view);
> view.remove(webView);
> webView = null;
> view = null;
> window = null;
246,265c259,262
< 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;
< }
---
> var val = webView.evalJS('window.document.querySelector(\'kbd[aria-labelledby="code-desc"] > code\').innerHTML');
> if( val ){
> pin = val;
> if (receivePinCallback) receivePinCallback();
267,270d263
<
< nodeList = null;
< xmlDocument = null;
<
285,287c278,280
< width: 310,
< height: 450,
< border: 10,
---
> width: '99%',
> height: '600',
> border: 5,
306d298
< window.open();
310c302,305
< autoDetect:[Ti.UI.AUTODETECT_NONE]
---
> top: closeLabel.height + closeLabel.top,
> width: '97%',
> height: view.height - closeLabel.height - closeLabel.top - view.borderWidth * 4,
> autoDetect:[Ti.UI.AUTODETECT_NONE]
312c307,314
< Ti.API.debug('Setting:['+Ti.UI.AUTODETECT_NONE+']');
---
> if (Titanium.version<'1.7.0'){
> view.width = 310;
> view.height = 450;
> webView.width = 300;
> webView.height = view.height - closeLabel.height - closeLabel.top - view.borderWidth * 4;
> }
>
> Ti.API.debug('Setting:['+Ti.UI.AUTODETECT_NONE+']');
316c318,320
< closeLabel.addEventListener('click', destroyAuthorizeUI);
---
> closeLabel.addEventListener('click', function(e){
> destroyAuthorizeUI();
> });
319a324
> window.open();
327,328c332
< // if xauth is used, set params
< this.getAccessToken = function(pUrl, params)
---
> this.getAccessToken = function(pUrl,pCallback,params)
330c334
< var message = createMessage(pUrl);
---
> var message = createMessage(pUrl);
332,334c336,338
< accessor.tokenSecret = requestTokenSecret;
< message.parameters.push(['oauth_token', requestToken]);
< message.parameters.push(['oauth_verifier', pin]);
---
> accessor.tokenSecret = requestTokenSecret;
> message.parameters.push(['oauth_token', requestToken]);
> message.parameters.push(['oauth_verifier', pin]);
336,338c340,342
< message.parameters.push(['x_auth_mode', 'client_auth']);
< message.parameters.push(['x_auth_password', params.password]);
< message.parameters.push(['x_auth_username', params.username]);
---
> message.parameters.push(['x_auth_mode', 'client_auth']);
> message.parameters.push(['x_auth_username', params.username]);
> message.parameters.push(['x_auth_password', params.password]);
346,347c350
< Ti.API.debug(p + ': ' + parameterMap[p]);
<
---
> Ti.API.debug(p + ': ' + parameterMap[p]);
350,370c353,367
< if (params != null) {
< client.onerror = function(e){
< Ti.API.debug(e);
< if(params.onError){
< params.onError(e);
< }
< }
< client.onload = function(){
< Ti.API.debug('*** getAccessToken, 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('POST', pUrl, false);
---
> client.onload = function(){
> 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();
> destroyAuthorizeUI();
> pCallback();
> };
> client.onerror = function(e){
> Ti.API.debug(e);
> destroyAuthorizeUI();
> pCallback();
> };
> client.open('POST', pUrl, true);
372,382d368
<
< 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;
<
386a373
> if(!useQueue) { return; }
437c424
< query.sort();//(9.1.1. Normalize Request Parameters)
---
> query.sort();//(9.1.1. Normalize Request Parameters)
451c438
< var resultByXML = params.resultByXML || false;
---
> var resultByXML = params.resultByXML || false;
454c441
< if (accessToken == null || accessTokenSecret == null)
---
> if (!this.isAuthorized())
455a443
> if(!useQueue) { return; }
457,458c445
< //actionsQueue.push(params);
< params.onError('No Access Token.');
---
> actionsQueue.push(params);
469d455
< alert(parameterMap);
477,483d462
< client.onerror = function(e){
< alert(e);
< Ti.API.debug(e);
< if(params.onError){
< params.onError(e);
< }
< }
486d464
< alert(client.responseText);
496,497c474,481
< }
< client.open(pMethod, pUrl, false);
---
> };
> client.onerror = function(e){
> Ti.API.debug(e);
> if(params.onError){
> params.onError(e);
> }
> };
> client.open(pMethod, pUrl, true);
499,500d482
<
< return null;
503,511c485,504
<
< // taken from
< // https://github.com/kurain/TitaniumTestApp/blob/master/Resources/lib/oauth_adapter.js
<
< this.createOAuthHeader = function (params) {
< this.loadAccessToken('twitter');
< var pUrl = params.url;
< var pMethod = params.method || "POST";
< var message = createMessage(pUrl, pMethod);
---
>
> var sendMultiPart = function(pUrl, realm, pParameters, pTitle, pSuccessMessage, pErrorMessage)
> {
> Ti.API.debug('Sending a message to the service at [' + pUrl + '] with the following params: ' + JSON.stringify(pParameters));
> Ti.API.debug(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;
> }
514d506
< message.parameters.push(['oauth_token', accessToken]);
515a508,509
> var message = createMessage(pUrl);
> message.parameters.push(['oauth_token', accessToken]);
519,522c513,515
< var parameterMap = OAuth.getParameterMap(message.parameters);
< var oAuthHeaderElms = [];
< for (var p in parameterMap) {
< oAuthHeaderElms.push( encodeURIComponent(p) + "=" + encodeURIComponent(parameterMap[p]) );
---
> parameterMap = {};
> for(p in pParameters) {
> parameterMap[pParameters[0][0]] = pParameters[0][1];
524c517,538
< return 'OAuth ' + oAuthHeaderElms.sort().join(', ');
---
>
> var client = Ti.Network.createHTTPClient();
> client.open('POST', pUrl, false);
> client.setRequestHeader("Authorization", OAuth.getAuthorizationHeader(realm, message.parameters) );
> 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;
>
525a540
> this.sendMultiPart = sendMultiPart;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment