I am having a website which contains login page. When user tries to log in using username and password. Data is being passed in Form Data. Please have a look as following image to get idea.
Now I want to use the same api in my Titanium application and get all details or logged in user which i am performing using below mentioned code.
var url= "http://www.randomwebsite.com/login/";
var jsonData = {
username: "admin",
password: "password1"
};
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function(e) {
var obj = JSON.parse(this.responseText);
alert("DATA IS " + JSON.stringify(obj));
};
xhr.onerror = function(e) {
Ti.API.info("ERROR " + e.error);
};
xhr.onsendstream = function(e){
Ti.API.info("onsendstream");
};
xhr.ondatastream = function(e){
Ti.API.info("ondatastream");
};
xhr.open('POST',url);
xhr.send(JSON.stringify(jsonData));
I am getting HTTP error. I even tried setting xhr.setHeader('Content-Type','application/json') as well as verified url its same as that is being used by website. Can any one help me out with this ? Or is there any way in order to make sure that titanium code passes data in form-data ? Or any suggestion regarding this would be of great help.
Its working fine now. Mistake that I was doing is that i was stringifying text when data was being send. So changing xhr.send(JSON.stringify(jsonData)) to xhr.send(jsonData) works for me. Hope so this would help some one.
Related
I have been using this method (https://github.com/ebryn/twitter-titanium) of authenticating with Twitter for a while now. I am currently using Ti Studio 4.2.0.201508141038, Ti SDK 3.5.1. I know this is a little old but I am on this version for support reasons.
I am trying to allow the sharing of text entered in a TextArea to twitter including emojis. For some reason sharing to Facebook works like a charm but twitter I receive "����". Please note that I have only tested iOS to date. Android will follow.
Is there some encoding method that I should be using that will get me through this?
The code I am using to post is simply as follows:
var Twitter = require('twitter').Twitter;
var client = Twitter({
consumerKey: consumerKey,
consumerSecret: consumerSecret,
accessTokenKey: accessTokenKey,
accessTokenSecret: accessTokenSecret
});
client.addEventListener('login', function(e) {
if (e.success) {
Ti.App.Properties.setString('twitterAccessTokenKey', e.accessTokenKey);
Ti.App.Properties.setString('twitterAccessTokenSecret', e.accessTokenSecret);
var tweet = textArea.value.replace(/[\n\r]/g, '');
client.request("1.1/statuses/update.json", {status: tweet, trim_user:'t'}, 'POST', function(e) {
if (e.success) {
console.log('success');
} else {
console.log('Twitter Post failed.\nDetail is:'+JSON.stringify(e.data));
}
});
} else {
Ti.API.debug(JSON.stringify(e));
}
});
client.authorize();
Funnily, I found that if I make tweet equal to:
var tweet = textArea.value.replace(/[\n\r]/g, '') + '\ue415';
I do get a smiley in my tweet but only on my device not on twitter.com. But if I type that code directly into my TextArea it gets tweeted verbatum.
I have also tried using encode(tweet) and urlEncode(tweet) but they really don't work.
Is there a way I can get emojis tranlated into text that will then post correctly on twitter?
This is my Titanium code:
var loginReq = Titanium.Network.createHTTPClient({
onload: function(e){
// just displays the response
var webview = Titanium.UI.createWebView({html:this.responseText});
win.add(webview);
}
});
loginReq.open("POST",url);
var params = {
email: email.value,
passowrd: password.value
};
loginReq.send(params); // this is sending nothing according to a CF variable dump
The ColdFusion page just dumps all the variables, and it shows up on the iPhone emulator. But it's giving me an empty struct for the variables, which means no variables are actually getting sent in.
How do I fix my Titanium code to actually post data?
If you want to send post data to a script you will have to to set the header accordingly:
loginReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
If you are sending JSON data to an API, you might need to stringify your parameters to send them:
loginReq.send(JSON.stringify(params));
Edit:
According to the docs this is done automatically (see comments). In some of my network clients I had to do that explicitly, though...
Moreover, you might also want to implement the onerror callback, so in case your call fails for any reason you will know why:
var loginReq = Titanium.Network.createHTTPClient({
onload: function(e){
// just displays the response
var webview = Titanium.UI.createWebView({html:this.responseText});
win.add(webview);
},
onerror: function(e) {
Ti.API.debug('Status: ' + this.status);
Ti.API.debug('Response: ' + this.responseText);
}
});
I had a Google Apps Script to take appointments from my Google Calendar, copy them into a Google Sheet, convert it to XLS and email it. It was working fine until this week.
The initial problem was a 302 error, probably caused by the new version of Sheets. This has been discussed here: Export (or print) with a google script new version of google spreadsheets to pdf file, using pdf options
I got the new location of the file by muting the HTTP exceptions and adjusting the URL accordingly. I also updated the OAuth scope to https://docs.google.com/feeds/ as suggested.
The program is failing with an "OAuth error" message. When muteHttpExceptions is set to true, the message is "Failed to authenticate to service: google".
I guess this is a scope problem but I really can't see what I've done wrong. Naturally, I've tried a few other possibilities without luck.
I've included the code below. Commented code is the instruction that worked until this week.
function getSSAsExcel(ssID)
{
var format = "xls";
//var scope = "https://spreadsheets.google.com/feeds/";
var scope = "https://docs.google.com/feeds/";
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=" + scope);
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var requestData = {
//"muteHttpExceptions": true,
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
//var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ssID
var url = "https://docs.google.com/spreadsheets/d/" + ssID
+ "/feeds/download/spreadsheets/Export?"
+ "&size=A4" + "&portrait=true" +"&fitw=true" + "&exportFormat=" + format;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
return contents;
}
Thanks for your help!
Instead of using OAuthConfig (which must be auth'ed in the Script Editor) you can pass an OAuth2 token instead, retrievable via ScriptApp.getOAuthToken().
The code snippet below uses the Advanced Drive service to get the export URL, but if you hand construct the URL you'll need to ensure that the Drive scope is still requested by your script (simply include a call to DriveApp.getRootFolder() somewhere in your script code).
function exportAsExcel(spreadsheetId) {
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
return response.getBlob();
}
Hello guys I need help in auto login to youtube.com to upload videos "browser-based" (and later get them data to show in a site by api). So basicly I downloaded extension from here http://framework.zend.com/downloads/latest Zend Gdata. And make it work.
It works fine (demos/.../YouTubeVideoApp). But how can i do auto login to youtube without confirmation page ("grant access" \ "deny access")? Currently I use developer key to work with youtube api.
The message of confirmation is
An anonymous application is requesting access to your Google Account for the product(s) listed below.
YouTube
If you grant access, you can revoke access at any time under 'My Account'. The anonymous application will not have access to your password or any other personal information from your Google Account. Learn more
This website has not registered with Google to establish a secure connection for authorization requests. We recommend that you continue the process only if you trust the following destination:
http://somedomain/operations.php
In general I need create connection to youtube (by api) and upload there (using my own account) video without any popups and confirmation pages.
i think all you need is to get a access token and set it to a session value "$_SESSION['sessionToken']". Combination of javascript and PHP will need to do this. previously i always have to grant access or deny it while using Picasa web API but after changes that i described below, grant or access page is no longer needed.
I have not integrated youtube with zend Gdata but have integrated Picasa web Albums using it
make a login using javascript popup and get a token for a needed scope. below is a javascript code. change your scope to youtube data as in this scope for picasa is used.. click function "picasa" on your button onclick.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://picasaweb.google.com/data';
var CLIENTID = YOUR_CLIENT_ID;
var REDIRECT = 'http://localhost/YOUR_REDIRECT_URL'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function picasa() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
console.log(win);
console.log(win.document);
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
//alert(responseText.toSource());
getPicasaAlbums(token);
loggedIn = true;
},
dataType: "jsonp"
});
}
function getPicasaAlbums(token) {
$.ajax({
url: site_url+"ajaxs/getAlbums/picasa/"+token,
data: null,
success: function(response) {
alert("success");
}
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
Here i am making a ajax call in function "getPicasaAlbums" and setting token to a $_session there and after it i am able to get a album listing using zend queries. here is a some code of php file that i am calling using ajax in function "getPicasaAlbums".
function getAlbums($imported_from = '',$token = '') {
//echo $imported_from; //picasa
//echo $token;
$_SESSION['sessionToken'] = $token;// set sessionToken
$client = getAuthSubHttpClient();
$user = "default";
$photos = new Zend_Gdata_Photos($client);
$query = new Zend_Gdata_Photos_UserQuery();
$query->setUser($user);
$userFeed = $photos->getUserFeed(null, $query);
echo "<pre>";print_r($userFeed);echo "</pre>";exit;
}
i think this will help you a little in your task. relpace above "getAlbums" function's code with your youtube zend data code to retrieve data.
good example & referene of a login popup is here
http://www.gethugames.in/blog/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html
I am building a mobile app that connects to my grails app that uses spring security core.
Im building the app in titanium studio.
How do i check it the user has an open session on the mobile app.
I log in using the with the following code:
var xhr = Ti.Network.createHTTPClient();
var url = "http://localhost:8080/FYP/j_spring_security_check";
var postData = "";
postData += 'j_username=' + usernameField.value;
postData += '&j_password=' + passwordField.value;
postData += '&_spring_security_remember_me=on';
Ti.API.debug(url);
xhr.open("POST", url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
win.close({animate:true});
slidingMenu.open({animate:true});
if( response.error ){
alert( response.error );
} else {
//logged in now do something
}
};
xhr.onerror = function(){
Ti.API.error( "Error Logging in" );
};
xhr.send(postData);
But how would i check if the user has already logged in?
Make a custom method in grails using
springsecurityservice.isLoggedIn()
and do a GET request :)
I simply use an application level variable. It situations when I need to protect data, I always pass the username and password I stored to the server so it has to authenticate every time.