Phonegap + Hello.js (server side authentication)

954 views Asked by At

I have a Phonegap application that is communicating with Nodejs server.

Also for the Facebook\Twitter login I'm using Hello.js library (which is very easy to use by the way).

Unfortunately this library only makes client side login (authentication), so at server side I don't know if the user is valid or not (have been looged in with Facebook\Twitter).

Edit: After the user is logged in (client side), Hello.js provides the user credentials, with a Facebook unique user ID, but I don't know how to pass it safely to the server, or generally if its a good idea to use it as a user id in my DB.

I'm looking for a simple example that will check the validity of the login at server side too.

Thanks.

2

There are 2 answers

0
Guy P On BEST ANSWER

This is the main idea as I figured:

In the Phonegap application, after the user has logged in, this function will be called:

hello.on('auth.login', function(r){
    var token = r.authResponse.access_token;
}

now, you can send only the token to the server, and the server will get the user credentials directly from Facebook.

For example, in Facebook, call this usr:

https://graph.facebook.com/me?access_token={token}

2
Josh Lankford On

If you are using https then sending the id to your server will be fine. What you can do is just check to see if that unique id already exists in your DB and return that users data (if needed) or create a new account.

I would also recommend creating a JWT (JSON Web Token) on the server side and sending that back to the app to be stored in local storage and used to validate all future requests to your node server. You can implement that method pretty easily if you use the jwt.verify method as middleware on all of your routes.

Here is a quick example:

var jwt = require('jsonwebtoken');

var jwtValidation = function(req, res, next) {
  var token = req.body.jwt_token;
  if (token) {
    jwt.verify(token, 'yourSecretKeyHere', function(err, decoded) {
      if (err) {
        // Error when checking JWT - redirect to unauthorized
        res.redirect('/unauthorized');
      } else if (decoded.id) {
        // Token that was passed in has been decoded
        // Check your DB for the decoded.id
        // Complete any other needed tasks then call next();
        next();
      } else {
        // Something else went wrong - redirect to unauthorized
        res.redirect('/unauthorized');
      }
    });
  } else {
    // No token present - redirect to unauthorized
    res.redirect('/unauthorized');
  }
};
module.exports = jwtValidation;