express-mongoose-es6-rest-api icon indicating copy to clipboard operation
express-mongoose-es6-rest-api copied to clipboard

Where is the user object coming from?

Open arimourao opened this issue 6 years ago • 6 comments

Hey guys, I'm currently studying nodejs, and this boilerplate is helping me a great deal. But I got stuck in one thing. See the code below to update an user

function update(req, res, next) {
  const user = req.user;
  user.username = req.body.username;
  user.mobileNumber = req.body.mobileNumber;

  user.save()
    .then(savedUser => res.json(savedUser))
    .catch(e => next(e));
}

Is the client supposed to send the entire user in the request? If not, how is the user embedded in the request?

arimourao avatar Dec 29 '18 13:12 arimourao

few.user is not what you want. It is an object which contains information that was encoded in JWT and got decided after successfull JWT validation.

Client should send user information in req.body And you should:

  • Select user from database fires to see if user exists
  • update user that you selected in previous step with information from req.body
  • save user to database

okonon avatar Dec 29 '18 14:12 okonon

@okonon Ok tnx man. So I have to first have a succesful login through JWT so I can update the user, is that it? Can I test this using Postman?

arimourao avatar Dec 29 '18 14:12 arimourao

First check if the route that your update function is tied to is protected with JWT. If yes then you will get req.user automatically if client (Postman) sends requests with valid Authorization token (you get this token from auth endpoint)

Usually this req.user object is for checking JWT decoded info.

I think you are confusing it with user records stored in the database.

okonon avatar Dec 29 '18 14:12 okonon

User routes are not protected. So I think you will not get req.user object at all.

okonon avatar Dec 29 '18 14:12 okonon

@okonon exactly, it is not protected. This is very confusing. How come no one noticed until now? Maybe we are missing something. This should be more clear in the documentation.

arimourao avatar Dec 29 '18 14:12 arimourao

see example pseudoscode below wrote it on my phone so I do not know if this actual code will work and I apologize for formatting

const user = User.findById(req.params.userId).then((user) => {
  //update user here
  user.username = req.body.username;
  user.mobileNumber =  req.body.mobileNumber;

  user.save()
    .then(savedUser => res.json(savedUser))
    .catch(e => next(e));
})

okonon avatar Dec 29 '18 15:12 okonon