getting gmail Contacts - javascript

I am trying to get g mail contacts ,with oauth google plus api javascript i am to get his profile, but unfortunately i am not able to get all email of contacts,but i mention every thing correct in scope and all,
can any one suggest me how can i get gmail contacts.
I am using below js :
https://apis.google.com/js/client.js
i wrote bellow code to get contact emails
var authParams = gapi.auth.getToken(); // from Google oAuth
authParams.alt = 'json';
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full',
dataType: 'jsonp',
data: authParams,
success: function(text) {
alert("text?????????"+JSON.stringify(text.feed));
}
});

The Contacts API has a hard limit to the number of results it can return at a time even if you explicitly request all possible results. If the requested feed has more fields than can be returned in a single response, the API truncates the feed and adds a "Next" link that allows you to request the rest of the response.
Source
So you have to take the response, get the Next link from it, and make another request to get additional contacts.

Related

frontend: how-to access a dictionary and save a key's value in a variable

I have a webapp that its backend is written in Python and renders some html for the frontend users.
What I would like to achieve is:
when a user makes a POST request to /token, the backend replies with a JSON document {"access_token": access_token, "token_type": "bearer"}; this is already in place
after the above takes place, every subsequent request / navigation to the webapp, should set a header named Authorization equal to Bearer <access_token> to every GET, POST, etc. request that it does; not important for the time being
can you advise and describe how to maintain a single variable client-side called access_token that its default value is null, but when doing POST to /token, then the variable access_token is initialised and never changes through navigation, unless the end user makes another POST request to /token again to reset the access_token to the new value ?
I am not familiar with jQuery or javascript much. Can you suggest how to initialise, set, reset a variable (and just print it, for example, using console.log) based on the background information above ?
You can store the token in local storage, or in cookies, either would work. Then, when you go to make an ajax call, you'll retrieve the value from whichever you used, and add it to the outgoing ajax request. How exactly you do that willl depend on what specific ajax implementation you use. For example google "add auth token to jquery.ajax" and you'll find the right syntax for that library
Something like this would work:
// do initial login and get token
var token = response.access_token;
// store it in local storage
localStorage.setItem('apiKey', token);
// ... navigate around and what not...
// later, when you need to make another call, get the token
var token = localStorage.getItem('apiKey');
$.ajax({
url: url,
method: "POST",
dataType: "json",
//.. other props as needed...
beforeSend: function (xhr) {
/* set the Authorization header with the token */
xhr.setRequestHeader("Authorization", "Bearer " + token);
},
success: function (data) {
// do something cool with data
},
error: function (jqXHR, textStatus, errorThrown) {
// handle errors ...
}
});

Stop Malicious POST requests

I have an AJAX function that makes call to a page on my website.
$(document).on('click', thisIdentity, function() {
var trigger = $(this);
var items = trigger.attr('data-values').split('_');
$.ajax({
type: "POST",
url: "/mod/mypage.php",
data : { pid : item[0], uid : item[1] },
dataType: "json",
success: function(data) {
if(data.job == 1) {
// do something
}
}
});
});
Now this works fine and do as intended. However, if I use any third-party app like POSTMAN and make a POST request to www.xyz.com/mod/mypage.php with parameters pid : 1 and uid : 2. It still goes through and make changes to my database.
Is there anyway to check that request is generated from my
domain/server only?
How to stop such POST requests outside from my domain?
One thing I thought was to generate a token and set in SESSION before this request and check in mypage.php that if token is set or not. Is this a feasible way?
This is exactly what a CSRF token is for. Users must navigate to the page first, which generates a token to submit, ergo without navigating to the page will render any POST requests invalid.
However, trying to stop someone from POST'ing a request to your endpoint from a utility like POSTman is an exercise in futility. You must authenticate every request to the endpoint, in this case just check the photo id is owned by the submitting client.
OWASP provides a decent description of what a CSRF is:
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request.
Example validation flow
Login.php
<?php
// Establish DB connection, validate
$_SESSION['id'] = $db->getUserId();
$_SESSION['admin'] = $db->getAdminStatus();
Delete.php
<?php
if (!$db->isPhotoOwner($_POST['pid'])) {
exit;
}
// Delete photo flow
Admin.php
<?php
if (!$_SESSION['admin']) {
die("Not admin.");
}
// Do admin action or whatever
You could have the calling page identify itself with $_SERVER['SCRIPT_NAME'] and write that value to a hidden input field or $_POST and check for it at the beginning of processing. Any confirmed value you choose might work.
If they are already imitating the data of your JSON, then maybe drop it into the javascript with PHP dynamically writing the code value on page serving.

400 Error on AJAX Call to Twitter

I'm working on a web page that lets you search for twitter users in your area. You enter a name in the search box and it returns users with that name within 50 miles of the city (the city is always the same).
I was having trouble authenticating, and I found oauth.io. I used that to authenticate and it seems to be working. But when I do a search, my request to Twitter returns as a 400 bad request error. I'm not sure what I'm doing wrong. I've looked at the oauth.io documentation but couldn't find anything.
Here is the part of the code that gets the value of what the user entered into the form field:
// Click function
$('.user-getter').submit(function(event) {
// prevent form refresh
event.preventDefault();
// zero out results if previous search has run
$('.user-results').html('');
// Get the values of what the person entered in search
var query = $(this).find("input[name='user_search']").val();
// Run function to send API request to Twitter
getUser(query);
}); // end click function
Here is the part of the code that calls the authorization and then sends the ajax request:
var getUser = function(query) {
OAuth.initialize('oMQua1CuWerqGKRwqVkzDx5uijo')
OAuth.popup('twitter').done(function(twitterData) {
$.ajax({
type: "GET",
url: "https://api.twitter.com/1.1/users/search.json?&geocode=42.94003620000001,-78.8677924,50mi&q=" + query,
dataType: "jsonp"
});
console.log( "Data Saved: " + twitterData ); // can see in inspector tab under Network
}); // end oAuth popup
};
Right now, I just want to see the result in console.log.
To make a request to Twitter API using OAuth.io you have to use the OAuth.io Javascript SDK instead of directly $.ajax (the OAuth.io Javascript SDK use the syntaxe of $.ajax behind the scene)
OAuth.initialize('oMQua1CuWerqGKRwqVkzDx5uijo')
OAuth.popup('twitter').done(function(twitterData) {
twitterData.get('/1.1/users/search.json', {
data: {
q: query
}
}).done(function(search) {
//result of the search here
console.log(search);
}).fail(function(error) {
//error management here
});
})
The SDK does all the hard things for you transparently: proxy the HTTP request, inject all the needed OAuth credentials (oauth_token, oauth_token_secret, signature, nonce, timestamp etc..)
Take a look to this jsfiddles: http://jsfiddle.net/uz76E/10/
I hope that helps,

URL in AJAX call

I am persisting the data in a textbox before redirecting the page to another. When the user clicks the back button in the page load function of the page (in javascript) I am getting the data from the textbox like
var pageval = $('#grid')
.load('/Dealer/AllClaims?page=5&__=634673230919806673 #grid', CallBackFunction);
I want to send an AJAX call by using the URL from the above data. I.e from /Dealer/AllClaims?page=5&__=634673230919806673 #grid. So I replaced the 'pageval' unnecessary data with (.replace()) in javascript. Now I store it as
var urlmain = '/Dealer/AllClaims?page=5&__=634673230919806673 #grid';
When I send an AJAX call with this 'urlmain' like
$.ajax({
type: "GET",
url: urlmain,
success: function (data) {
$("#allclaimsdiv").html(data);
},
it throws error like 'status not found' as the URL is like
http://localhost:46408/Dealer/%22Dealer/GetDealerClaims?page=3&__=634673387913756213
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
The above bold data is there in the URL before users click on the back button. I think it is concatenating the data.
But for testing purpose I had given directly the URL as:
$.ajax({
type: "GET",
url: "/Dealer/AllClaims?page=5&__=634673230919806673 #grid",
success: function (data) {
$("#allclaimsdiv").html(data);
},
Then it works fine.
What is the difference between these two? Why doesn't it work?
you have a problem in the called url:
first: there is a /22 which stands for a url-encoded doublequote
second: you have Dealer two times in the url - so you may have to remove /Dealer from your urlmain
Is there a quote character getting encoded somewhere along the line? The reason I'm wondering is the URL you've given in bold has "%22" in it:
http://localhost:46408/Dealer/%22Dealer/
See here for some info on what certain characters get encoded to.
A 500 error means a problem has occurred on your web server. Check your server log files or enable error reporting for more info - that might give you some hints or even tell you exactly what's wrong.

I dont understand how to implement the Deleting Requests in request dialog

I have read the document here
but I don't understand how should I implement it right.
In my facebook app I use apprequests from JS api like this:
function newInvite() {
var msg = document.getElementById('msg_look_id').value;
var receiverUserIds = FB.ui({
method: 'apprequests',
message: msg,
title: "Select friends to send your gift",
},
function (response) {
alert("IDS : " + response.request_ids);
});
//http://developers.facebook.com/docs/reference/dialogs/requests/
}
then the user see the request in its app request icon (with the red numbers )
the user click it , but then how do I implement the delete request ?
When the user arrives at your app’s canvas page following a request, there is a parameter called request_ids passed to your app.
Since Facebook calls apps in the iframe using the HTTP method POST, I guess this is also a POST parameter (although it is not explicitly mentioned in the docs). That means you have no access to it using pure client-side JavaScript; you have to use a server-side script to get the content of this parameter.

Categories

Resources