Skip to content

Instantly share code, notes, and snippets.

@gzumaglini
Created February 3, 2015 20:14
Show Gist options
  • Save gzumaglini/3cfee13744e8efae7a3c to your computer and use it in GitHub Desktop.
Save gzumaglini/3cfee13744e8efae7a3c to your computer and use it in GitHub Desktop.
OAuth with Ionic and ngCordova - Trakt.tv API
/*
* Sign into the Trakt service
*
* @param string clientId
* @param string clientSecret
* @return promise
*/
trakt: function(clientId, clientSecret) {
var deferred = $q.defer();
if(window.cordova) {
var cordovaMetadata = cordova.require("cordova/plugin_list").metadata;
if(cordovaMetadata.hasOwnProperty("org.apache.cordova.inappbrowser") === true) {
var browserRef = window.open("https://trakt.tv/oauth/authorize?client_id=" + clientId + "&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code", "_blank", "location=no,clearsessioncache=yes,clearcache=yes");
browserRef.addEventListener("loadstart", function(event) {
console.log(event.url);
if((event.url).indexOf("http://trakt.tv/oauth/authorize/") === 0) {
var requestToken = (event.url).split("authorize/")[1];
console.log('requestToken:'+requestToken);
$http.defaults.headers.post['Content-Type'] = 'application/json';
$http({method: "post", url: "http://api.trakt.tv/oauth/token", data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=urn:ietf:wg:oauth:2.0:oob" + "&grant_type=authorization_code" + "&code=" + requestToken })
.success(function(data) {
deferred.resolve(data);
})
.error(function(data, status, headers, config, statusText) {
deferred.reject("Problem authenticating");
})
.finally(function() {
setTimeout(function() {
browserRef.close();
}, 10);
});
}
});
browserRef.addEventListener('exit', function(event) {
deferred.reject("The sign in flow was canceled");
});
} else {
deferred.reject("Could not find InAppBrowser plugin");
}
} else {
deferred.reject("Cannot authenticate via a web browser");
}
return deferred.promise;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment