google api javascript get logged in user's email - javascript

There are many resources and stack overflow questions that are similar but not exactly the same as what I will ask. I will rehash some of the solutions here and explain them.
I have a user that is already logged into Google. By logged in I mean manually logged in and the cookie is present. Not logged in by my application.
I just need to get the email address.
There are 3 ways to do this that I have seen but neither works for me.
Way #1:
auth2 = gapi.auth2.getAuthInstance();
if (auth2.isSignedIn.get()) {
var profile = auth2.currentUser.get().getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
}
Way #2:
gapi.client.setApiKey(API_KEY);
gapi.client.load("plus", "v1", function() {
gapi.client.plus.people.get({ userId: "me" }).execute(function(resp) {
// Shows profile information
console.log(resp);
});
});
Way #3:
gapi.client.load('oauth2', 'v2', function () {
gapi.client.oauth2.userinfo.get().execute(function (resp) {
// Shows user email
console.log(resp.email);
})
});
For Way #2 and Way #3 stack overflow says that you have to use a token and not an api key. But the user is already logged in and I don't have and cannot obtain the token.
How to get the EMAIL of an ALREADY logged in user?
Thanks

Though an old question.. this may help .. just incase..
var auth2 = gapi.auth2.getAuthInstance();
var profile = auth2.currentUser.get().getBasicProfile();
console.log(profile.getName());
console.log(profile.getEmail());
The instance can be initiated by either gapi.auth2.getAuthInstance() or gapi.auth2.init(). Based on what is used to instantiate you can use either to get profile details.

Related

UserCannotBeAlteredWithoutSessionError when updating PFUser on Parse from Heroku node.js app

I'm trying to update a PFUser in my Parse database from a node.js app running on Heroku. I'm calling the Parse cloud function from an iOS app.
Here's the part of the code I use to update the user on parse as well as creating the user on Stripe (the Stripe part works fine):
Parse.Cloud.define("createCustomerWithCreditCardToken", function(request, response) {
var userId = request.user.id;
var sourceId = request.params.creditCardToken;
var customerId;
var userSessionToken = request.user.getSessionToken();
console.log('userId: ' + userId + ' source: ' + sourceId + ' userSessionToken: ' + userSessionToken);
stripe.customers.create({
source: sourceId,
description: userId
}, function(error, customer) {
if (error !== null) {
response.error('error creating customer: ' + error);
}else {
var userQuery = new Parse.Query('User');
userQuery.equalTo('objectId', userId);
userQuery.first({sessionToken: userSessionToken}).then(function(user) {
console.log('user from parse query: ' + user.get("username"));
user.set("stripeCustomerId", customer.id);
user.save(null, {
success: function(parseCustomer) {
console.log('customer saved to parse: ' + parseCustomer);
},
error: function(error, parseCustomer) {
console.log('customer save failed: ' + JSON.stringify(error, null, 2) + ' with error: ' + JSON.stringify(parseCustomer,null, 2));
}
});
});
customerId = customer.id;
console.log('customerId: '+ customerId);
// response.success(customer);
response.success('Customer: ' + JSON.stringify(customer, null, 2) + 'error: ' + error);
}
});
});
I get the following error log output when I run this:
error log output
error: { "code": 206, "message": "Parse::UserCannotBeAlteredWithoutSessionError" }
In this post the current user concept in a node.js app context is discussed by a Parse engineer.
Also in Cloud Code, the concept of a method that returns the current
user makes sense, as it does in JavaScript on a web page, because
there’s only one active request and only one user. However in a
context like node.js, there can’t be a global current user, which
requires explicit passing of the session token.
Essentially he advises to do this:
Parse.Cloud.define('findBacon', function(req, res) {
var token = req.user.getSessionToken();
var query = new Parse.Query('Bacon');
// Pass the session token to the query
query.find({ sessionToken: token }).then( ... );
});
I have also tried using {useMasterKey:true} instead of {sessionToken:userSessionToken} which produces the same error.
I might just be missing some obvious detail, but I just can't seem to find it. Any ideas on how to solve this are greatly appreciated.
Turns out there's a third way of handling credentials:
Parse.Cloud.useMasterKey();
I placed this line in the beginning of the entire method, that did it for me. I'm not sure of the implications of giving the whole function these credentials though.
I'm not sure when you would use the other options either.
If someone comes across this and would like to elaborate, I'll be happy to give the right answer to a good explanation of when to grant which credentials.

Parse Javascript - Adding user error

I created a factory in angularJS to store data to Parse User object. Every time I click to process the details and open an account for the user, it shows the following error in console:
Failed to load resource: https://api.parse.com/1/users the server
responded with a status of 400 (Bad Request)
I checked if the service parameter is valid with attributes content, and yes it has content (not empty). This is the service body:
.factory('CreateUserService', function() {
return {
createAccount: function(user) {
console.log("Service User: " + user.name);
var parseUser = new Parse.User();
parseUser.set("username", user.username);
parseUser.set("email", user.username);
parseUser.set("name", user.username);
parseUser.set("password", user.username);
parseUser.set("mobile", user.username);
/*Attempt to create user in DB*/
parseUser.signUp(null, {
success: function(parseUser) {
// Hooray! Let them use the app now.
//alert("success!");
return 1;
},
error: function(parseUser, error) {
// Show the error message somewhere and let the user try again.
//alert("Error: " + error.code + " " + error.message);
return error;
}
});
}
}
});
I added the Parse CDN in the index.html of my application with:
<script src="http://www.parsecdn.com/js/parse-1.6.7.min.js"></script>
Update: In Parse API Guide, this is the body of the signup:
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
The user object in Parse (I review through the browser) is not showing any changes to the rows number hence user not added. Any idea what is going wrong?
Thanks
Update: When I deleted the existing empty user object in Parse and ran the code, it worked and created a user Object with all columns specified in the code. Then if I try to add another user, I get a POST error. There must be a way around this since signup method by parse surely considered adding multiple users to the User object.

unable to get email address, location, values using oauth.io

I am integrating facebook, twitter, github, linkedin using https://oauth.io/signin third party site.
I integrated facebook and was able to successfully get id, name, gender properties directly but am seeing difficulty in getting email address, location values.
In oauth.io site, I even added scope permissions for facebook
I am using the below code to get info of the logged in user.
OAuth.popup('facebook')
.done(function (result) {
res = result;
result.me().done(function (response) {
debugger;
console.log('me ' + response.name);
console.log('me ' + response.email);
});
})
.fail(function (error) {
alert('fail');
});
I even tried filtering the results only to give email, birthdate values using
OAuth.popup('facebook')
.done(function (result) {
res = result;
result.me(['email', 'birthdate', 'location']).done(function (response) {
debugger;
console.log('me ' + response.name);
console.log('me ' + response.email);
});
})
.fail(function (error) {
alert('fail');
});
But it just returned empty object.
Can some one let me know if I am missing something?
I was able to get the required fields for facebook using
result.get('/me?fields=name,email,gender,birthday').done(function (response) {
console.log('me ' + response.name);
});
But the same code is not working for twitter.
Still looking for an answer which works in a generic way for most of the apis

Google Auth User Email Not Present

I'm using the javascript api for Google Auth 2.0 . I'm running into the problem where the users email is not showing up, even though I request with https://www.googleapis.com/auth/userinfo.email .
My code looks like this:
gapi.auth.authorize({
client_id : 'xxxxxxxxxx.apps.googleusercontent.com',
scope : ['https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'],
immediate : false
}, function(result) {
if (result != null) {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
console.log(resp);
});
});
}
});
What am I missing to get the user's email?
While the userinfo.email role gives you access to the information, the plus v1 client doesn't provide it. You will need to make an additional call to a different endpoint to get the info.
You will need the oauth2 v2 endpoint, which you can request with gapi.client.load('oauth2', 'v2', callback). The endpoint itself that you want is gapi.client.oauth2.userinfo.get(). This is untested, but the code might look something like:
gapi.client.load('oath2','v2',function(){
gapi.client.oauth2.userinfo.get().execute(function(resp){
console.log(resp);
});
});
See How can I get the user's email address in google apps? and Why can't I retrieve the users email from Google Plus API after getting permission for some related questions and https://developers.google.com/accounts/docs/OAuth2 for more details from the official doc.
Here's how I did it:
function tryAuth() {
var clientId = CLIENT_ID;
var configString = {
client_id: clientId,
scope: SCOPE,
immediate: 'false'
};
gapi.auth.authorize(configString, handleAuthResult);
}
Where SCOPE = 'https://www.googleapis.com/auth/fusiontables email';
Replace https://www.googleapis.com/auth/fusiontables scope with your scope but keep ' email' .
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
var access_token = authResult.access_token;
alert('Successfully logged in.' + access_token);
tryGetEmail(access_token);
}
And then
function tryGetEmail(access_token) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + access_token, false );
xmlHttp.send( null );
if(xmlHttp.status == 200) {
var strJSON = xmlHttp.responseText;
var objJSON = eval("(function(){return " + strJSON + ";})()");
email = objJSON.email;
alert('got email ' + email);
}
}
The userinfo endpoint and oauth2 v2 are being deprecated. The older answers are for the old system. All the details for migration are here:
https://developers.google.com/+/api/auth-migration#email
In short: put 'email' instead of 'h ttps://www.googleapis.com/auth/userinfo.email' for your scope, and the G+ email will be included as the first entry of the 'emails' property in the 'person' object you're fetching. There's also apparently an option described in the link to pull it out of the ID token, referenced in the link above.
Full example

Javascript SDK get facebook friendlist member

I luckly get some ununderstandable response when trying to get friendlist from a facebook account, this is what i got when console.log:
#v_3 { __wrapped=#v_3, __observableEvents={...}, name="v_3", more...}
The method FB.Data.query:toString is not officially supported by Facebook and access to it will soon be removed.
Here is my code for login and get user's friendlist member:
FB.init({ appId:'my_appid' });
// fetch the status on load
FB.getLoginStatus(handleSessionResponse);
$('#login').bind('click', function() {
FB.login(handleSessionResponse);
});
$('#logout').bind('click', function() {
FB.logout(handleSessionResponse);
});
// handle a session response from any of the auth related calls
function handleSessionResponse() {
FB.api('/me', function(response) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log(access_token);
console.log(response);
var friends = FB.Data.query('SELECT uid, flid FROM friendlist_member WHERE flid IN (SELECT flid FROM friendlist WHERE owner=me())');
console.log(friends);
$('#user-info').html(response.id + ' - ' + response.name);
});
}
Anyone has exprienced the same issue?
Well, there is a much better way to get the friendlist of a user:
FB.api('me/friends', function(response) {
console.log(response);
}
If you really want to use FQL (which is not a good way in this case), it is explained how to use FQL with the JavaScript SDK in this thread: How can I execute a FQL query with Facebook Graph API
The correct FQL call to get the friends would be this one:
SELECT uid2 FROM friend WHERE uid1=me()
https://developers.facebook.com/docs/reference/fql/

Categories

Resources