Search code examples
node.jsgoogle-oauthgoogle-api-nodejs-clientpassport-google-oauth

NodeJS - Is there a way to get the current logged in user with the Google API?


Is it possible to get the current logged in user (email, name etc.) from the refreshToken, accessToken, or by a method similar to this Retrieve profile information for a signed-in user in NodeJS?


Solution

  • you can use the userinfo endpoint to request some of this information.

    https://openidconnect.googleapis.com/v1/userinfo?access_token=XXXX
    

    The one issue is that you will need to add the profile scope to your authroization request then you will get back something like this

    {
      "sub": "117475532672775346",
      "name": "Linda Lawton",
      "given_name": "Linda",
      "family_name": "Lawton",
      "picture": "https://lh3.googleusercontent.com/a-/AOh14GhroCYJp2P9xeYeYk1npchBPK-zbtTxzNQo0WAHI20",
      "locale": "en"
    }
    

    You could then also go though the google people api people.get which will give you even more information.

    However you cant get email back from the userinfo endpoint without requesting the email scope but there is a trick you really dont need to as you are using the google calendar scope.

    if you use calendar.get and request the users primary calendar the calendar name is their email address.

    {
     "kind": "calendar#calendar",
     "etag": "\"Qvsbvz0_YlxYi3Ml2Fd7A\"",
     "id": "xxxxx@gmail.com",
     "summary": "Linda Lawton ",
     "description": "test",
     "timeZone": "Europe/Copenhagen",
     "conferenceProperties": {
      "allowedConferenceSolutionTypes": [
       "hangoutsMeet"
      ]
     }
    }