Troubles with passport js and react getting user with fetch

Viewed 14

Hello guys I have a problem trying to get my user session with passport on reactjs. I have no problem to get on post man , I cannot fetch the data with a Get method on react js, im getting undefined:(. I configurated my cors and everything and still no data :(.

This is my fetch

const [user, setUser] = useState(null);

 useEffect(() => {
   const getUser = async () => {
     try {
       const response = await axios.get("http://localhost:8080/login/success");
       const data = await response.json();
       setUser(data);
     } catch (error) {
       throw new Error(`error fetching data ${error}`);
     }
   };
   getUser();
 }, []);

and this is my end point and passport js config.

function checkAuthentication(req, res, next) {
  if (req.isAuthenticated()) next();
  else {
    res.status(401).json({
      message: "Failure",
    });
  }
}

router.get("/login/success", checkAuthentication, (req, res) => {
  if (req.user) {
    res.status(200).json({
      success: true,
      message: "success user",
      user: req.user,
    });
    console.log(req.user);
  } else {
    req.status(404).json({
      success: false,
      message: "No user",
    })
  }
});

passport.use(
  "login",
  new LocalStrategy(async (username, password, done) => {
    try {
      const user = await User.findOne({ username: username });
      if (!user) {
        return done(null, false, { message: "Incorrect username" });
      }
      const isMatch = await user.isValidPassword(password);
      if (!isMatch) {
        return done(null, false, { message: "Incorrect password" });
      } else {
        return done(null, user, { message: "Logged in successfully" });
      }
    } catch (error) {
      console.log(error);
    }
  })
);
0 Answers
Related