Home > Net >  Save user data in MongoDB after user registers by their google account
Save user data in MongoDB after user registers by their google account

Time:09-06

I'm developing an application that will allow users to access the website after authenticating with their Facebook or Google IDs. and this will be done by front-end and in the back-end front-end side will send only the access-token something like this: ya29.a0AVA9y1tHwvchD95jJmDNMzKkW7P9nIAyvHX58AY-bC_Dy_-7lhXkrXpfe8iRXIrLHbDKZRFmzphfMceFH3di6X_2-_FcwiXa8GvDwOmYwwzgt1MUETzlFRrcnuWDDbAsa2Yj00BFDyAqK6fuO8smUYmyXw1taCgFRDTASAQASFQE65dr8E1cHOK0krpI8Efn0d9eXDg7852

Now, Based on this access token how can I get details of that user and save it to the database.

CodePudding user response:

You can retrieve the user profile using the google node API client library. In this case, please retrieve the access token and refresh token as the scope of https://www.googleapis.com/auth/userinfo.profile. The sample script is as follows. When you use this sample, please set your ACCESS TOKEN.

var google = require('googleapis').google;
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2();
oauth2Client.setCredentials({access_token: 'ACCESS TOKEN HERE'});
var oauth2 = google.oauth2({
  auth: oauth2Client,
  version: 'v2'
});
oauth2.userinfo.get(
  function(err, res) {
    if (err) {
       console.log(err);
    } else {
       console.log(res);
       /*WRITE SIMPLE MongoDB INSERT LOGIC HERE*/
        db.users.insert(res)

    }
});

From above logic you'll be able to get user details and insert it in MongoDB

  • Related