mardi 7 février 2017

React-Facebook-Login and Node.js Express

Vote count: 0

I'm using React with Redux on the client and Node.js with Express as an Rest API on the server. I've implemented a local login with passport but I also wan't to implement social login, such as Facebook login.

I'm using react-facebook-login where the user gets authenticated and some information are returned in the response, including AccessToken, Email, Name, ID, etc. I then want to send these information to the server (running on another port) and save the user there to the database (MongoDb). This is how the user schema is structured:

const userSchema = Schema({
  local: {
    email: {
      type: String,
      unique: true,
    },
    password: String,
    name: String
  },
  facebook: {
    id: String,
    token: String,
    email: String,
    name: String
  },
...

After a user has been saved to the database I return a JWTtoken to the client with this function:

const tokenForUser = (user) => {
  const timestamp = new Date().getTime();
  return jwt.encode({ sub: user._id, iat: timestamp }, SECRET);
};

The token can then be used to authenticate.

OK, here is the real problem. When creating a Facebook user I first check if the user exists, if not then create him:

const facebookSignIn = (model, cb) => {
  User.findOne({ 'facebook.id': model.id }, (err, docs) => {
    if (err) {
      return cb({ 'status': HTTP_INTERNAL_SERVER_ERROR,
        'message': { error: 'Unable to search for an user due to an unknown error' } });
    } else if (docs) {
      return cb(null, { token: tokenForUser(docs) });
    }

    const user = new User({
      facebook: {
        id: model.id,
        token: model.accessToken,
        email: model.email,
        name: model.name
      }
    });

    user.save((err) => {
      if (err) {
        if (err.name === VALIDATION_ERROR) {
          return cb({ 'status': HTTP_PRECONDITION_FAILED,
            'message': { error: Object.keys(err.errors).map(e => `${err.errors[e].message} `) } });
        }
        return cb({ 'status': HTTP_INTERNAL_SERVER_ERROR,
          'message': { error: 'Unable to save user due to an unknown error' } });
      }

      return cb(null, { token: tokenForUser(user) });
    });
  });
};

If a user has been authenticated (exists in the database) then there can be a request sent to the server only containing his/her Facebook ID. Then the user will be allowed to enter the website and will be returned a JWTtoken.

I need to authenticate the accessToken from the user when he/she is authenticated on the server. How can I authenticate the accessToken on the server by bypassing CORS?

Thanks in advance!

asked 18 secs ago

Let's block ads! (Why?)



React-Facebook-Login and Node.js Express

Aucun commentaire:

Enregistrer un commentaire