Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google api javascript get logged in user's email

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

like image 626
aleksandar Avatar asked Oct 21 '16 21:10

aleksandar


1 Answers

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.

like image 192
Ashish Avatar answered Nov 09 '22 03:11

Ashish