Sync contacts using Google Contacts API version 3.0 and NodeJS' Passport - node.js

I am using passport, and would like to use the Google Contacts API version 3.0 to sync Google contacts with my application (which would suddenly become 10 times more useful).
Has anybody done this? If so, do you have some example code? Is it even possible to use passport authentication to get it all working?

This comes in two parts, authorization, and then the actual request.
It is basically using OAuth2 protocol, where you redirect the client to google url with scopes(You must at least have https://www.google.com/m8/feeds in your scopes to be able to read and write contacts) and your client id/secret(get them by registering your app. Then google will redirect the user back with the access token on the URL.
You don't need to do this yourself, because there are different modules that already does this:
passport-google-oauth
This makes it easy and assuming you are already using passport, this probably what you want. It is written by the author of passportjs. Just follow the example in it for OAuth 2.0 strategy. Note that you need to you add the right scopes when you are calling passport.authenticate('google', ...). This module when it gets the token, it will get the user profile, so you have to have one of the 3 scopes below:
passport.authenticate('google', { scope: [ // One of the next three `auth` scopes are needed.
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/plus.login',
'https://www.google.com/m8/feeds'
] }),
googleapis
This is module is officially supported by google and created by google employees. You can use it to authenticate, but sadly it doesn't support gData, which contains google contacts. You can check the example to see how you can get the token. You only need the m8/feeds scope with this module, no need for the other ones if you don't want to get the user profile.
gdata-js
This is a non-popular non-maintaining module, but it is more lightweight than the previous two modules. It might need a little polishing out of the box. I suggest also reading the source for understanding the api right.
Once you got the tokens, then you go for the slightly easier part, making the requests and getting the data.
If you read the docs, it's actually very easy. For example to get all contacts(almost all, it's paginated), you need to make a GET request to this url:
https://www.google.com/m8/feeds/contacts/default/full?alt=json&oauth_token=THE_ACCESS_TOKEN
Again there are many modules that can help you in this.
google-contacts
node-gdata
gdata-js Read the source to understand it's api. It's pretty easy actually:
var client = require('gdata-js')(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET);
client.setToken({ access_token: accessToken, refresh_token: refreshToken });
client.getFeed('https://www.google.com/m8/feeds/contacts/default/full', function (err, result) { ... });

Google's official API for NodeJS doesn't support Contacts API, only the People API.
You can connect with Contacts API using the official googleapis library if you're already using it for other purposes by sending a request to the Contacts API after creating the auth client.
Given that you already have the access token of the user (e.g. if you generated it using Passport, here's the code:
const {google} = require("googleapis");
const authObj = new google.auth.OAuth2({
access_type: 'offline',
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
});
Refresh access token automatically before it expires
authObj.on('tokens', (tokens) => {
const access_token = tokens.access_token
if (tokens.refresh_token){
this.myTokens.refreshToken = tokens.refresh_token
// save refresh token in the database if it exists
}
this.myTokens.accessToken = tokens.access_token
// save new access token (tokens.access_token)
}
authObj.setCredentials({
access_token:this.myTokens.accessToken,
refresh_token:this.myTokens.refreshToken,
});
Make the request to Contacts API (Google uses Gaxios for making the requests to their APIs although it's not documented officially in googleapis, so just be aware that they might change remove/change the request call in the future without documenting it)
authObj.request({
headers:{
"GData-Version":3.0
},
params:{
"alt":"json",
//"q":"OPTIONAL SEARCH QUERY",
//"startindex":0
"orderby":"lastmodified",
"sortorder":"descending",
},
url: "https://www.google.com/m8/feeds/contacts/default/full"
}).then( response => {
console.log(response); // extracted contacts
});

Related

How to make HTML auth form and JSON Web Tokens communicate together in Ionic/Angular

I'm working on an Ionic application.
On the one hand I have an auth basic form in which people fill in their username and password. On the other hand I'd like to implement authentification with JSON Web Tokens and Node JS.
The workflow would be this one : as soon as a user fills in his credentials, they will be sent with a POST request. If these credentials are correct, the user can access to the application and gets an access token as a response.
The thing is that I'm a little bit lost with all that concepts. I built a form and sent informations with a POST request. I managed to create some APIs with Node JS and that's ok. I see how to build a authentified webservice too (e.g : https://github.com/jkasun/stack-abuse-express-jwt/blob/master/auth.js).
But I concretely don't understand the links between the html form and the authorisation check part..
To be clearer, how is it possible to make the html part and the Node JS scripts communicate together ?
Before posting that question I made many researches and found many stuff on building an authentified API. But there was very few advice on how to make it communicate with the client part (I mean the form), which is what I have to do.
If anyone has any ressources (document, Github examples..) on that, I'll greatly appreciate. But I would be very happy too if someone try to make me understand these concepts. I guess I have to improve my knowledge on all that so that I could test some POCs.
Many thanks in advance !
JWT General flow:
1- Authenticate using a strategy (You done it)
2- Deliver an accessToken along with response (You done it)
3- The client MUST store this accessToken (LocalStorage is the best place, not cookies: They are vulnerable to csrf attacks)
4- On every request you are going to make to a protected area (where user is supposed to be authenticated and authorized), make sure to send you accessToken along with it, you can put it on Authorization header, a custom header, directly in body of the request... Basicaly just make sure to send it properly.
5- On the server receiving client requests, you NEED to verify that token (You verify it by checking the signature of the accessToken).
6- If he is authorized, great, if not, send back an HTTP Unauthorized Error.
Here is my implementation using an accessToken on a header + passportjs-jwt:
Client code
To store token:
localStorage.setItem('accessToken', myAccessToken);
To send it:
const myAccessToken = localStorage.getItem('accessToken');
{
headers: {'Authorization', `Bearer ${myAccessToken}`}
}
Server code
1- Configure passport
passport.use('jwt', new JwtStrategy({
jwtFromRequest: jwtPassport.ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: myAccessTokenSecret,
passReqToCallback: true
}, (req, payload, done: (err?, user?) => void): void {
User
.findOne({where: {id: req.params.id}})
.then((user: User) => {
if (!user) {
return done(new Error(`No user found with id: ${req.params.id}`), null);
}
return done(null, user);
})
.catch((e: Error) => done(e, null));
}));
Pay attention to callback: If your callback is called, it means that passport has successfuly verified the token (It is valid). In my example, i get the user details in database and this is the user that will be returned and put in req.user object passed to my controller below:
2- Finally, the controller route (protected area):
.get('/users/:id', passport.authenticate('jwt'), (req, res, next) => {
// do stuff in protected area.
}
And that's it. If you want more security, check refreshTokens implementation.
I used passport because i found it relevant in my case, but you can write your own handler, by using jsonwebtoken and just calling its "verify" function.
You can find documentation of passport jwt strategy here => http://www.passportjs.org/packages/passport-jwt/

How to add Google Contact using Nodejs API or curl request

I want to add new contact details if it does not exist in my google contacts
I don't think Nodejs is supported in Google Contacts API. Use this guide of google contacts.
This document is intended for programmers who want to write client
applications that can interact with Google's contact lists. It
provides a series of examples of basic API interactions. These
examples come in various forms, including raw XML/HTTP requests,
Java, .NET and Python source code.
Also, you can run the sample codes using these protocols.
If you're using a UNIX system and you want to try the examples in this
document without writing any code, you may find the UNIX command-line
utilities curl or wget useful; for more
information, see the manual pages for those utilities.
Use https://www.npmjs.com/package/google-contacts-crud npm to read and add google contacts.
Google's official API for NodeJS doesn't use Contacts API, only the People API.
You can connect with Contacts API using the official googleapis library if you're already using it for other purposes by sending a request to the Contacts API after creating the auth client.
Given that you already have the access token of the user (e.g. if you generated it using Passport, here's the code:
const {google} = require("googleapis");
const authObj = new google.auth.OAuth2({
access_type: 'offline',
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
});
Refresh access token automatically before it expires
authObj.on('tokens', (tokens) => {
const access_token = tokens.access_token
if (tokens.refresh_token){
this.myTokens.refreshToken = tokens.refresh_token
// save refresh token in the database if it exists
}
this.myTokens.accessToken = tokens.access_token
// save new access token (tokens.access_token)
}
authObj.setCredentials({
access_token:this.myTokens.accessToken,
refresh_token:this.myTokens.refreshToken,
});
Make the request to Contacts API:
authObj.request({
headers:{
"GData-Version":3.0
},
params:{
"alt":"json",
//"q":"OPTIONAL SEARCH QUERY",
//"startindex":0
"orderby":"lastmodified",
"sortorder":"descending",
},
url: "https://www.google.com/m8/feeds/contacts/default/full"
}).then( response => {
console.log(response); // extracted contacts
});

How to handle expiration of OAuth access_token using Asana node client?

Using Asana's NodeJS module (https://github.com/Asana/node-asana) with OAuth, how should I handle expiration of the access_token? Does the client provide some mechanism that I should use to detect this? Does it provide something I should use to get a new access_token using the refresh_token? I haven't been able to find any discussion of the refresh_token in the documentation.
I've registered my app and I'm able to successfully get credentials using the Client.app.accessTokenFromCode API. Something like this:
function handleOauthCallback(req, res) {
var client = Asana.Client.create({
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
redirectUri: computeRedirectUrl(req)
});
client.app.accessTokenFromCode(req.query.code).then(function(credentials) {
// store credentials
}
}
I'm storing the entire credentials object that comes back from this call and later creating a client using those credentials. Something like this:
var client = Asana.Client.create({
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
redirectUri: computeRedirectUrl(req)
});
var storedCredentials = getStoredCredentials();
client.useOauth({ credentials : storedCredentials });
Now that I've got a client that's initialized with the credentials I got back from Asana (which includes an access_token and refresh_token), how should I handle expiration of the access_token? Do I need to check whether it's still valid myself and ask for a new token using the refresh token? Or will the client handle it for me automatically? If the client handles it, how do I find out when it gets a new access token?
Update
Reading the code, it appears that the client will try to use the refresh token if the access token is no longer valid. But I don't see any kind of notification that I can hook into to find out that there's a new access token. Is there a recommended strategy to handle this?
(I work at Asana). This is a great question, and we should add answers to the documentation.
The dispatcher can be passed an option called handleUnauthorized which is a callback to run when it gets a 401 (which if you started with good credentials should only happen when your token expires). It's documented in the code.
The default behavior of this option is to call Dispatcher.maybeReauthorize, which will make the backend request to get a new access token if it has a refresh token.
So if you just want the dispatcher to transparently refresh the access token, you don't need to do anything, it should "just work"! But if you want to intercept this process, you can pass handleUnauthorized in the dispatch options and then do whatever you want, possibly including calling the default method.
If you want to see the new access token, well .. the Authenticator class is abstract and we haven't provided a robust way to extract credentials from it; maybe we can add that. If you really need this, you could assume it's the oauth flavor with something like:
handleUnauthorized: function() {
return Dispatcher.maybeReauthorize.call(dispatcher).then(
function(reauthorized) {
if (reauthorized) {
onCredentials(dispatcher.authenticator.credentials);
}
return reauthorized;
});
}
This isn't beautiful, but it should work for you. Just be aware we may evolve this interface a bit over time and you may have to tweak it in the future.

Passport.js: passport-facebook-token strategy, login through JS SDK and THEN authenticate passport?

I was looking for a way to let my client authorize with the facebook JS SDK and then somehow transfer this authorization to my node server (so it can verify requests with the fb graph api)
I stumbled across:
https://github.com/jaredhanson/passport-facebook/issues/26
&
https://github.com/drudge/passport-facebook-token
what seems to be an entirely different strategy from passport-facebook.
Am I correct when assuming that:
One logs in with the fb JS SDK, and then the facebook-token strategy somehow extracts the token and fb id from the document or body object?
Or is there any other decent way to achieve this? I'm namely trying to avoid the redirects enforced by the server SDKs
I've spent a couple of days this week trying to figure out the best way to use Facebook Authentication for a private API, using passport.js — passport-facebook-token is perfect for this.
You are correct in assuming these are two separate authentication strategies. You don't need passport-facebook installed to use passport-facebook-token.
If you have Facebook authentication implemented in the client-side JS (or iOS etc.), and are looking for a way to then authenticate API requests using your user's Facebook authToken, passport-facebook-token is a really elegant solution.
passport-facebook-token works totally independently of passport-facebook, and basically handles the redirects required by Facebook internally, before passing the request along to your controller.
So to authenticate an API route using passport-facebook-token, you'll need to set up a passport strategy like so:
passport.use('facebook-token', new FacebookTokenStrategy({
clientID : "123-your-app-id",
clientSecret : "ssshhhhhhhhh"
},
function(accessToken, refreshToken, profile, done) {
// console.log(profile);
var user = {
'email': profile.emails[0].value,
'name' : profile.name.givenName + ' ' + profile.name.familyName,
'id' : profile.id,
'token': accessToken
}
// You can perform any necessary actions with your user at this point,
// e.g. internal verification against a users table,
// creating new user entries, etc.
return done(null, user); // the user object we just made gets passed to the route's controller as `req.user`
}
));
It's worth noting that the User.findOrCreate method used in the passport-facebook-token Readme is not a default mongo/mongoose method, but a plugin that you'll have to install if you want it.
To use this auth strategy as middleware for any of your routes you'll need to pass it an access_token object either as a URL parameter, or as a property of the request body.
app.get('/my/api/:access_token/endpoint',
passport.authenticate(['facebook-token','other-strategies']),
function (req, res) {
if (req.user){
//you're authenticated! return sensitive secret information here.
res.send(200, {'secrets':['array','of','top','secret','information']});
} else {
// not authenticated. go away.
res.send(401)
}
}
NB. the access_token property is case-sensitive and uses an underscore.
The documentation for passport-facebook-token isn't extensive, but the source is really well commented and pretty easy to read, so I'd encourage you to take a look under the hood there. It certainly helped me wrap my head around some of the more general ways that passport works.

Google Spreadsheet Creation - Node.js

I am trying to create new google spreadsheet using the google spreadsheet api using node.js
I have managed to get the Google OAuth 2.0 working, where I am getting the access tokens for the clients.
Now on searching the Google API docs there are example using the gData client library but nothing giving me pointers to node.js
Here are my findings for creating a new google spreadhseet
Upload a spreadsheet manually OR
Use a resumable upload link
There is not much information on the resumable upload link.
I can see the HTTP Post Request and Response but I do not understand how to construct the post request in node.js
EDIT--
I am reading Google Apps Platform
Here is how to do it with the create method of the Google Sheets API (currently v4).
This code examples does not use any 3rd party libraries, it uses googleapis: Google API's official Node.js client
const google = require('googleapis');
const sheets = google.sheets('v4');
// authenticate, and store that authentication, in this example
// it is stored in a variable called `auth`. I am using JWT
// authentication, but you can use the any form of authentication
const auth = new google.auth.JWT(
key.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/spreadsheets'], // make sure that your auth scope includes `spreadsheets`, `drive` or `drive.file`
null
);
sheets.spreadsheets.create({
auth: auth,
resource: {
properties: {
title: 'Title of your new spreadsheet'
}
}
}, (err, response) => {
if (err) {
console.log(`The API returned an error: ${err}`);
return;
}
console.log('Created a new spreadsheet:')
console.log(response);
});
If all you want to know is how to construct post request, then check this example
http://nodejs.org/api/http.html#http_http_request_options_callback
Checkout
https://github.com/EastCloud/node-spreadsheets/
EastCloud has written a friendly-ish wrapper around the Google Docs/Drive API
If you are new and want to get and add data to Google spreadsheets, please refer below link to get step-by-step guide.
https://www.twilio.com/blog/2017/03/google-spreadsheets-and-javascriptnode-js.html
I was tested same in recent nodejs project

Resources