Saturday 10 June 2017

JWT Authentication React/Node

Hello I am still figuring react out. Can someone point me in the right direction here in authenticating users. I know I have to use the jwt token on the backend, but I am finding it difficult to figure out. I have seen people talk about webpack? I am not sure. Here is what I have:

Login action:

export function loginUser(username1, password1) {
  const mainPage = (response, dispatch) => {
   if(true) {
    history.push('/main');
   }
  dispatch({
      type: POST_DATA_SUCCESS,
      response,
  });
  };
  const promise = fetch('http://localhost:8080/users/login', {
   method: 'POST',
    headers: {
   'Accept': 'application/json',
    'Content-Type': 'application/json',
  'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
 },
 body: JSON.stringify({
   username: username1,
   password: password1,
  })
 });
 return {
    onRequest: POST_DATA_TRIGGERED,
    onSuccess: mainPage,
    onFailure: POST_DATA_FAILURE,
    promise,
};
}

And the backend for "/login":

router.post('/login', function (req, res, next) {
 passport.authenticate('basic', function (err, user, info) {
    if (err) {
        return console.log(err);
    }
    if (!user) {
        return res.status(401).json({
            message: 'Username/Password Incorrect'
        });
    }
    return res.status(200).json({
        user: user.username
    });
    req.logIn(user, function (err) {
        if (err) {
            return console.log(err);
        }
    });
   })(req, res, next);
});



via JontheNerd

No comments:

Post a Comment