UttamMarandi / AdminPanel-FoodHub

0 stars 0 forks source link

Bug Fix : Protected routes response unauthorized(401) even if user is Admin. #4

Open UttamMarandi opened 2 years ago

UttamMarandi commented 2 years ago
//apiCalls.js

//login funciton
const login = async (dispatch, user) => {
  dispatch(loginStart());
  try {
    const res = await request.post("/auth/login", user, {
      withCredentials: true,
    });
    if (res) {
      dispatch(loginSuccess(res.data.user));
    }
  } catch (error) {
    dispatch(loginFailure());
  }
};

//get all users -> only admin have access to this endpoint , but we get 401 response even if user is admin
const getUsers = async () => {
  const userData = getUserFromLocalStorage();
  console.log("userData", userData);
  try {
    const res = await request.get("/auth/allusers", {
      withCredentials: true,
    });
    console.log("res in getUsers", res);
    if (res) {
      return res;
    }
  } catch (err) {
    throw err;
  }
};
//login.js
 const handleClick = (e) => {
    e.preventDefault();
    // login(dispatch, { email, password });
  };
UttamMarandi commented 2 years ago

The problem occurs because we are using passport-local strategy in backend. If it was passport-jwt this may be the correct frontend code. passport-local handles everything regarding authentication for us. We don't need to store the user or any "token" b.c there is none in our redux store. The reason I was using redux is to persist the user even if the page refreshes. But with passport-local we don't need to do that. passport-local creates a session and handles "persist" all in background.

//apiCalls.js
const login = (email, password) => {
  request
    .post(
      "/auth/login",
      { email, password },
      {
        withCredentials: true,
      }
    )
    .then((res) => {
      const {
        data: { user },
      } = res;
      console.log("user", user);
    })
    .catch((err) => {
      console.log("err login", err);
    });
};
//login.js
 const handleClick = (e) => {
    e.preventDefault();
    login(email, password);
  };

TAKEAWAYS =>Never store user info in redux store. Basically redux store along with redux persist uses localstorage to persist the data. This compromises the security of app. =>tokens, and non-sensitive data should be stored in redux.