0

Here are my three files jwtToken.js jwtToken.js, middleware auth.js auth.js, and getUser get user. I want to get my user after registering the user but my code is showing the error of "Not token provided".

jwtToken

export const sendToken = (user, statusCode, res, message) => {
  const token = user.getJWTToken();
  const options = {
    expires: new Date(
      Date.now() + process.env.COOKIE_EXPIRE * 24 * 60 * 60 * 1000
    ),
    httpOnly: true, // Set httpOnly to true
  };

  res.status(statusCode).cookie("token", token, options).json({
    success: true,
    user,
    message,
    token,
  });
};                                                                                                                  

auth.js


import { User } from "../models/userSchema.js";
import { catchAsyncError } from "./catchAsyncError.js";
import ErrorHandler from "./error.js";
import jwt from "jsonwebtoken";

export const isAuthorized = catchAsyncError(async (req, res, next) => {

    // get token from cookies
    const { token } = req.cookies;
    // Checking if there is No token or user doesn't registerd yet
    if (!token) {
        return next(new ErrorHandler("Access denied. No token provided", 401));
    }
    // if token exists then verify the secret key is same as we declayerd
    const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);

    req.user = await User.findById(decoded.id);

    next();
});

getUser

export const getUser = catchAsyncError((req, res, next) => {
    const user = req.user;
    res.status(200).json({
        success: true,
        user,
    });
});                                   

register where I register the user


  const handleRegister = async (e) => {
    e.preventDefault();
    try {
      const { data } = await axios.post(
        "http://127.0.0.1:8000/api/v1/user/register",
        { name, email, role, password },
        {
          headers: { "Content-Type": "application/json" },
          withCredentials: true,
        }
      );
      toast.success("Successfully Registerd!");
      setName("");
      setEmail("");
      setPassword("");
      setRole("");
      setIsAuthorized(true);
    } catch (error) {
      toast.error(error.response.data.message);
    }
  };

fetchuser function to fetch user and see isAuthorized true.

 // works whenever isAuthorized is changed
  useEffect(() => {
    const fetchuser = async () => {
      try {
        // get and set user using axios 
        const res = await axios.get("http://127.0.0.1:8000/api/v1/user/getuser", { withCredentials: true });
        setUser(res.data.user);
        setIsAuthorized(true);
      } catch(error) {
        setIsAuthorized(false);
      }
    };
    fetchuser();
  }, [isAuthorized] ); // changing value of isAuthorized 

I am expecting to send a token in my auth.js so, I will get the user after registering.

1 Answer 1

0

I don't see the jwt being signed anywhere, but I assume that the axios post is signing the token using the password provided, so seems like you are not registering your cookie before using your isAuthorized middleware

Try setting res.cookie right after registration in handleRegister

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.