google+ api login not returning email - javascript

I have implemented javascript based google+ login in my application using the following code:
var isGPInitialzed = false;
function render() {
gapi.signin.render('loginWithGoogle', {
'callback': 'onSignIn',
'clientid': 'the client id',
'cookiepolicy': 'single_host_origin',
'requestvisibleactions': 'http://schema.org/AddAction',
'scope': 'https://www.googleapis.com/auth/plus.login'
});
isGPInitialzed = true;
}
//Google
function onSignIn(authResult) {
if (!isGPInitialzed) {
if (authResult['status']['signed_in']) { //get some user info
gapi.client.load('oauth2', 'v2', function () {
gapi.client.oauth2.userinfo.get().execute(function (response) {
console.log(response.email);
$.ajax({
url: '/Account/GLogin',
type: 'POST',
data: {
email: response.email,
name: response.name,
profilePicture: response.picture
},
dataType: 'json',
success: function (isUserLoggedIn) {
if (isUserLoggedIn) {
window.location.reload();
}
}
});
});
});
}
}
else {
isGPInitialzed = false;
}
};
It was working fine until I created a new application from another account and replaced the client id. On successful authentication, the api is not returning the user email in the response. I have checked in the google+ account settings for the Apps and there is not setting to give acces to the email. What can be the issue?

change the scope with
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email',

For anyone who still looking for the answer, try to use this:
scope: 'openid profile email'

based on latest update from google developers, please change the scope,
https://www.googleapis.com/auth/plus.profile.emails.read
This scope requests that your app be given access to:
the user's Google account email address, as well as any public, verified email addresses in the user's Google+ profile. You access the email addresses by calling people.get, which returns the emails array.
the name of the Google Apps domain, if any, that the user belongs to.

If you're using Rails, the issue might be that you need to update omniauth-google-oauth2 to (0.6.0)
https://github.com/zquestz/omniauth-google-oauth2/issues/358
Google seems to have changed what gets returned by their API. The first comment in the above issue shows the structure of the hash has changed.

Related

How to send email using MailChimp API

I'm creating an app in nodejs to send an email using MailChimp. I've tried to use https://apidocs.mailchimp.com/sts/1.0/sendemail.func.php but changed it to use 3.0 api because 1.0 seems to no longer work (big surprise). I've setup my app with
var apiKey = '<<apiKey>>',
toEmail = '<<emailAddress>>',
toNames = '<<myName>>',
message = {
'html': 'Yo, this is the <b>html</b> portion',
'text': 'Yo, this is the *text* portion',
'subject': 'This is the subject',
'from_name': 'Me!',
'from_email': '',
'to_email': toEmail,
'to_name': toNames
},
tags = ['HelloWorld'],
params = {
'apikey': apiKey,
'message': message,
'track_opens': true,
'track_clicks': false,
'tags': tags
},
url = 'https://us13.api.mailchimp.com/3.0/SendEmail';
needle.post(url, params, function(err, headers) {
if (err) {
console.error(err);
}
console.log(headers);
}
});
I keep getting a 401 response (not authorized because I'm not sending the API key properly)
I have to use needle due to the constraints on the server.
There is no "SendEmail" endpoint in API v3.0. MailChimp's STS was a pre-cursor to its Mandrill transactional service and may only still work for user accounts that have existing STS campaigns. No new STS campaigns can be created. If you have a monthly, paid MailChimp account, you should look into Mandrill. If not, I've had good luck with Mailgun.
You should use HTTP Basic authentication in MailChimp API 3.0.
needle.get('https://<dc>.api.mailchimp.com/3.0/<endpoint>', { username: 'anystring', password: 'your_apikey' },
function(err, resp) {
// your code here...
});
EDIT
#TooMuchPete is right, the SendMail endpoint is not valid in MailChimp API v3.0. I didn't notice that and I've edited my answer.

Testing deezer application and is returned: "You must enter a valid redirect uri"

I'm testing a application using deezer javascript SDK, but when I try to login page I receive a "You must enter a valid redirect uri".
Using:
DZ.init({
appId: '000000',
channelUrl: 'http://localhost:13350/channel/channel.html',
player: {
onload: function (response) {
alert('register: DZ.player is ready');
}
}
});
And for login:
DZ.login(function (response) {
if (response.authResponse) {
DZ.api('/user/me', function (response) {
alert('Good to see you, ' + response.name + '.');
});
} else {
alert('User cancelled login or did not fully authorize.');
}
}, { perms: 'basic_access,email' });
So, what I need to do for test the application? The channelUrl is setted exactly this way in Application Domain.
The problem was in My apps in developers.deezer.com.
It's only necessary configure Application Domain as localhost:13350.
This error is displayed when the application domain you filled is different than the domain of your host. Did you check this?

How to verify Google's auth gapi.auth.signIn response?

I have a database with users and I want to let user to connect his website account with his google account. I want to be able to let user to log in with his google account too and maybe later to be able to interact with his google+ account etc.
User is logged in on the website and he initiates this process with a click on a button which does following:
// user initiates the process
$('#google-connect').on(function() {
gapi.auth.signIn({
'callback': function(data) {
if(data['status']['signed_in'])
console.log("Signed in", data, gapi.auth.getToken());
// just get some additional user's data
gapi.client.load('oauth2', 'v2', function() {
gapi.client.oauth2.userinfo.get().execute(function(resp) {
console.log("OAuth", resp);
data.userID = resp.id;
// tell server to add google account to user's account
$.post('/add/google', data, function(data) {
console.log("Connected", "data");
});
});
});
},
'clientid': GOOGLE_CLIENT_ID,
'cookiepolicy': 'single_host_origin',
'requestvisibleactions': 'http://schemas.google.com/AddActivity',
'approvalprompt':'force',
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
//'scope': 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me'
});
return false;
});
// load libs
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
it basicly works without problem but I am not sure is this secure and how to verify the answers form google server. For example, Facebook login returns "signedRequest" and I am able to run the verification with hash_hmac (php) to verify the response.
Google answers with this on my gapi.auth.signIn() request:
access_token: "ya29.KgDiGDMeEpOEFxoAAAD2dV1eldwT_ZCcr-ODNR_LBKWbam7bOwZ0pplZ33hG3A"
authuser: "0"
client_id: "...."
code: "4/iqLG-akrpp_BGWGGx2b_RAqTSj29.AuyFPmgozMATOl05ti8ZT3bxU6v2jAI"
cookie_policy: "single_host_origin"
expires_at: "1402232030"
expires_in: "3600"
g-oauth-window: Window
g_user_cookie_policy: "single_host_origin"
id_token: "eyJhbGciOiJSUzI1NiIsImtpZCI6IjgxNDBjNWYxYzlkMGM3MzhjMWI2MzI4NTI4ZjdhYjFmNjcyZjViYTAifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTExNTQ2NTQxNjExMzkyOTAzMTYzIiwiYXpwIjoiOTMyNjIxNDU0NTUxLThrNW8yOXY0djEyZmN2cG1tNWFqYXZsbW9ic2x1NzQwLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJtaXJ6YS5jd0BnbWFpbC5jb20iLCJhdF9oYXNoIjoiTUNERVJkZjJpaUo0eUZ4ZHU1RUdpUSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhdWQiOiI5MzI2MjE0NTQ1NTEtOGs1bzI5djR2MTJmY3ZwbW01YWphdmxtb2JzbHU3NDAuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJjX2hhc2giOiJXMXY4UUhkUndLM3FQbGhMZE1XY1Z3IiwiaWF0IjoxNDAyMjI4MTMwLCJleHAiOjE0MDIyMzIwMzB9.Fil-uV6oFdeiRrO_vHFr5oVOnzVIfa2DvneDYaFF_eo3HOdOmD2wElD5UOjXxTLcNHtxyXg-zInyB9wDn1aQaZpYTSgG3Q-PN7oXcmUECyX5UJ7Aga0xgjAH6j57XBTx_BVdeiq1xLTPSMq9J2hZ1jGIkv-1qPedng7bRVGuRgQ"
issued_at: "1402228430"
num_sessions: "1"
prompt: "consent"
response_type: "code token id_token gsession"
scope: "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.moments.write https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/plus.profile.agerange.read https://www.googleapis.com/auth/plus.profile.language.read https://www.googleapis.com/auth/plus.circles.members.read https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.profile.emails.read"
session_state: "14f90adcf0c130936b1545ec15dbd8fe1515b4dc..0c9b"
state: ""
status: Object
token_type: "Bearer"
I did not find any information how to verify the response. There is no signature or something else except "id_token" which could be some kind of signature.
Is there a way to verify google's answer to be sure that information is correct, that there is no MITM? Or am I just worrying too much?
Yes, there is :
Have you read ID Token verification(PHP lib) ?
I guess, you could do the same in JavaScript using :
$.get("https://www.googleapis.com/oauth2/v1/tokeninfo",{
"id_token" : authResult["id_token"]},function(data){
//Handle data...
});

Facebook api in javascript: how add the privacy?

I want publish a post on my friend's wall via Facebook Api in Javascript, but this code don't run correctly when I insert in "FB.api" the "privacy". Can someone help me?
Thank you.
var privacy = {value: 'CUSTOM', friends: 'SOME_FRIENDS', allow: '{UID}'};
var privacy2 = JSON.stringify(privacy);
FB.api("/{UID}/feed", 'post', {
message: 'Message',
privacy: privacy2,
}, function(response) {
if (!response || response.error) {
alert(response.error);
} else {
alert('Message sent!');
}
}
);
Change the privacy JSON to include quotes around your keys as well:
var privacy={"value":"CUSTOM", "friends": "SOME_FRIENDS", "allow":"{UID}"};
FB.api("/{UID}/feed", 'post', {
message: 'Message',
privacy: privacy,
}, function(response) {
if (!response || response.error) {
alert(response.error);
} else {
alert('Message sent!');
}
}
);
However, it appears that you cannot post private messages to another user's wall. From the privacy settings page on Facebook:
Note: The privacy parameter only applies for posts to the user's own
timeline and is ultimately governed by the privacy ceiling a user has
configured for an app. It does not apply to posts made by an app on
behalf of a user to another user's timelines or to Pages, events, or
groups. In those cases, such posts are viewable by anyone who can see
the timeline or content in the group or event.
This appears to be why you are getting an OAuth error.

Using Facebook Javascript SDK to post to user's friend's wall - getting valid response but post does not appear on Facebook

I'm attempting to use the Facebook Javascript SDK to post to an authenticated user's friend's wall. I get what appears to be a valid post ID in the response but the post does not appear on Facebook, and when I use the FB Graph API explorer to view the post, it simply returns false.
I'm using the FB login button with "publish_stream" permission for authentication and have a test FB app set up to get a valid App ID. I'm using the following code to post to the user's friend's wall:
FB.api('/[USER_ID]/feed', 'post', {
message: 'Testing the Facebook JavaScript API',
link: 'http://developers.facebook.com'
}, function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('Post ID: ' + response.id);
console.dir(response);
}
});
It works as expected when I replace [USER_ID] with 'me' - I can see the post on my FB timeline. However, when I use one of my friends' user IDs, I get a post ID response, but the post does not appear anywhere on their feed. Thoughts?
Here's my login button, too:
<fb:login-button show-faces="false" width="200" scope="publish_stream,publish_actions" perms="publish_stream"></fb:login-button>
I had the same problem. I worked on it like crazy for 5 hours. And actually, I think there is no problem. The only thing is that the posts on other's walls can arrive few hours later.
If anyone has the same problem, at least wait for a few hours before completely changing your code and turning crazy.
You can't post to a friend's wall
I was able to resolve this issue by creating an entirely new FB App from scratch, after which point the above code worked, which led me to think the issue must be in the configuration of my previous Facebook app. The only major difference I found was in App > Settings > Basic > Website > Site URL, I had entered the domain for my app and not the full path to the app page itself. So, you can indeed dynamically publish a post to the authenticated user's friend's wall.
here is with javascript sdk and facebbok c# sdk:
function fb_publish() {
FB.ui(
{
method: 'stream.publish',
message: 'Message here.',
attachment: {
name: 'Name here',
caption: 'Caption here.',
description: (
'description here'
),
href: 'url here'
},
action_links: [
{ text: 'Code', href: 'action url here' }
],
user_prompt_message: 'Personal message here'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
and
var client = new FacebookClient("my_access_token");
dynamic parameters = new ExpandoObject();
parameters.message = "Check out this funny article";
parameters.link = "http://www.example.com/article.html";
parameters.picture = "http://www.example.com/article-thumbnail.jpg";
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
parameters.description = "Longer description of the link";
parameters.actions = new {
name = "View on Zombo",
link = "http://www.zombo.com",
};
parameters.privacy = new {
value = "ALL_FRIENDS",
};
parameters.targeting = new {
countries = "US",
regions = "6,53",
locales = "6",
};
dynamic result = client.Post("me/feed", parameters);
and would you please mark it as answered if it helps :)

Categories