Skip to content

Instantly share code, notes, and snippets.

@danielnegri
Forked from joemaffia/app.js
Created September 21, 2012 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielnegri/3761312 to your computer and use it in GitHub Desktop.
Save danielnegri/3761312 to your computer and use it in GitHub Desktop.
foursquare OAuth in Titanium
/**
*
*
* Copyright 2011 Aaron K. Saunders, Clearly Innovative Inc
*
* 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
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* 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.
*/
Ti.include('fsq_module.js');
FOURSQModule.init('CLIENT ID GOES HERE', 'http://www.clearlyinnovative.com/oAuth.html');
FOURSQModule.login(loginSuccess, function(e) {
Titanium.UI.createAlertDialog({
title: "LOGIN FAILED",
message: e,
buttonNames: ['OK']
}).show();
});
function loginSuccess(e) {
FOURSQModule.callMethod("users/self", {}, onSuccess_self, function(e) {
Titanium.UI.createAlertDialog({
title: "users/self: METHOD FAILED FAILED",
message: e,
buttonNames: ['OK']
}).show();
});
};
function onSuccess_self(xhr) {
Ti.API.info(" checkins response-> " + xhr.responseText);
var respJSON = JSON.parse(xhr.responseText);
Ti.API.info(" Name -> " + respJSON.response.user.firstName + " " + respJSON.response.user.lastName);
Ti.API.info(" Email -> " + respJSON.response.user.contact.email);
Ti.API.info(" Badges -> " + respJSON.response.user.badges.count);
Ti.API.info(" Checkins -> " + respJSON.response.user.checkins.count);
};
/**
*
* this code was inspired by the work done by David Riccitelli
*
* Copyright 2011 Aaron K. Saunders, Clearly Innovative Inc
*
* 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
*
* <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
*
* 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.
*/
var FOURSQModule = {};
(function() {
FOURSQModule.init = function(clientId, redirectUri) {
FOURSQModule.clientId = clientId;
FOURSQModule.redirectUri = redirectUri;
FOURSQModule.ACCESS_TOKEN = null;
FOURSQModule.xhr = null;
FOURSQModule.API_URL = "https://api.foursquare.com/v2/";
};
FOURSQModule.logout = function() {
showAuthorizeUI(
String.format('https://foursquare.com/oauth2/authorize?response_type=token&client_id=%s&redirect_uri=%s',
FOURSQModule.clientId,
FOURSQModule.redirectUri)
);
return;
};
/**
* displays the familiar web login dialog we all know and love
*
* @params authSuccess_callback method called when successful
*
*/
FOURSQModule.login = function(authSuccess_callback) {
if (authSuccess_callback != undefined) {
FOURSQModule.success_callback = authSuccess_callback;
}
showAuthorizeUI(
String.format('https://foursquare.com/oauth2/authenticate?response_type=token&client_id=%s&redirect_uri=%s',
FOURSQModule.clientId,
FOURSQModule.redirectUri)
);
return;
};
FOURSQModule.callMethod = function(method, params, success, error) {
// get the login information and let it roll!!
try {
if (FOURSQModule.xhr == null) {
FOURSQModule.xhr = Titanium.Network.createHTTPClient();
}
FOURSQModule.xhr.open("GET", FOURSQModule.API_URL + method + "?oauth_token=" + FOURSQModule.ACCESS_TOKEN);
FOURSQModule.xhr.onerror = function(e) {
Ti.API.error("FOURSQModule ERROR " + e.error);
Ti.API.error("FOURSQModule ERROR " + FOURSQModule.xhr.location);
if ( error ) {
error(e);
}
};
FOURSQModule.xhr.onload = function(_xhr) {
Ti.API.debug("FOURSQModule response: " + FOURSQModule.xhr.responseText);
if ( success ) {
success(FOURSQModule.xhr);
}
};
FOURSQModule.xhr.send();
} catch(err) {
Titanium.UI.createAlertDialog({
title: "Error",
message: String(err),
buttonNames: ['OK']
}).show();
}
};
/**
* code to display the familiar web login dialog we all know and love
*/
function showAuthorizeUI(pUrl)
{
window = Ti.UI.createWindow({
modal: true,
fullscreen: true,
width: '100%'
});
var transform = Ti.UI.create2DMatrix().scale(0);
view = Ti.UI.createView({
top: 5,
width: '100%',
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: 5,
right: 12,
height: 14
});
window.open();
webView = Ti.UI.createWebView({
top: 25,
width: '100%',
url: pUrl,
autoDetect: [Ti.UI.AUTODETECT_NONE]
});
Ti.API.debug('Setting:[' + Ti.UI.AUTODETECT_NONE + ']');
webView.addEventListener('beforeload',
function(e) {
if (e.url.indexOf('http://www.clearlyinnovative.com/') != -1 || e.url.indexOf('http://www.foursquare.com/') != -1) {
Titanium.API.debug(e);
authorizeUICallback(e);
webView.stopLoading = true;
}
});
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);
};
/**
* unloads the UI used to have the user authorize the application
*/
function destroyAuthorizeUI()
{
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();
}
catch(ex)
{
Ti.API.debug('Cannot destroy the authorize UI. Ignoring.');
}
};
/**
* fires event when login fails
* <code>app:4square_access_denied</code>
*
* fires event when login successful
* <code>app:4square_token</code>
*
* executes callback if specified when creating object
*/
function authorizeUICallback(e)
{
Ti.API.debug('authorizeUILoaded ' + e.url);
Titanium.API.debug(e);
if (e.url.indexOf('#access_token') != -1)
{
var token = e.url.split("=")[1];
FOURSQModule.ACCESS_TOKEN = token;
Ti.App.fireEvent('app:4square_token', {
data: token
});
if (FOURSQModule.success_callback != undefined) {
FOURSQModule.success_callback({
access_token: token,
});
}
destroyAuthorizeUI();
} else if ('http://foursquare.com/' == e.url) {
Ti.App.fireEvent('app:4square_logout', {});
destroyAuthorizeUI();
} else if (e.url.indexOf('#error=access_denied') != -1) {
Ti.App.fireEvent('app:4square_access_denied', {});
destroyAuthorizeUI();
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment