Auth0 Home Blog Docs

Create rule save to db if user not found, else next

webtask
roles

#1

Hi,
I am trying to create rule where I check if the user id is already in my database, if he is I want to continue, if not I want to send a post request with some data.

Now, I was able to do both separately but I don’t know how to make this script working, even when the user.id is on my db, still tries to create it and I am getting mongodb error.

Can someone help me with the right code ?

function (user, context, callback) {
  var baseURL = 'http://tttt.ngrok.io/api';
  var usr_id = new Buffer(user.user_id).toString('base64');
  var newUser = {
    'identity': {
      'user_email': user.email,
      'user_id': user.user_id
    }
  };
  var test = 'testtesttest';
  var getURL = baseURL + "/users/" + user.user_id;
  request.get({
    "url": getURL,
  },
  function(err, response, body) {
    if(response.body === 'null') {
      var putURL = baseURL + "/users/" + usr_id;
      request.post({
        "url": putURL,
        "json": newUser
      });
      console.log("user created" + usr_id);
      console.log(response.body);
    }
    if(err) return callback(err);
    console.log("user exist");
    return callback(null, user, context);
  });
}

my simple backend code:

router.post('/users/*', (req, res) => {
  User.create(new User({
    email: req.body.identity.user_email,
    authUserId: req.body.identity.user_id
  }))
  res.json(console.log("User Created"))
})
router.get('/users/:id', (req, res, next) => {
  User.findOne({authUserId: req.params.id}, (err, userr) => {
    if(err) {
      return next(err);
    } else if (userr) {
      res.json(userr.email);
    } else {
      res.json(null)
    }
  });
});

#2

Can you put a console.log(response.body); in your GET callback function to see what is being returned by your API.


#3