-2

Code

this is my code in VS code to check if the user is an admin or a user

exports.authorizeRoles = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return next(
        new ErrorHandler(
          `Role: ${req.user.role} is not allowed to access this resource`,
          403
        )
      );
    }

    next();
  };
};

Error in postman API

the used declaration should be fine i don't know what's this problem

"success": false,
"message": "Cannot read properties of null (reading 'role')"
frank
  • 1,217
  • 2
  • 10
  • 18
  • 1
    how did you set the user ? – Mohammed naji Mar 28 '22 at 11:23
  • 1
    According to error, you are trying to access `role` property of `null` object. That means your `user` object is getting null value. From where are you getting `user` object? Are you getting it from body, or from somewhere else? – Aditya Mar 28 '22 at 11:23

2 Answers2

0

Based on your description, I assume your user object on req.user is null, therefor it tries reading the property role of a null object.

Now, you can just check for null before validating the role, this way the API will at least return the correct error. (e.g. see here)

Something along the lines of (haven't tested the code):

if (null == req?.user?.role) {
    return next(new ErrorHandler(`Bad request`, 400));
}

But that still doesn't solve the issue for a valid request. For that I suggest you give us some more information on how you declare the request.

товіаѕ
  • 2,881
  • 4
  • 23
  • 53
  • this is the default role i declared in my user model schema ```role: { type: String, default: "user", },``` and this is my user in the user controller ```const user = await User.create({ name, email, password, avatar: { public_id: "this is a sample id", url: "profilepicUrl", }, });``` this is how it's saved in mongodb ```name : "malek" email : "6pp@test.com" password : "$2a$10$8P9R2VjtDKf0b3EkukfSje7t3wswECEzdNAchsau17Kl79N.27RT." avatar : Object role : "user"``` still don't get the problem sadly. – Adam Thabet Mar 28 '22 at 12:03
  • @AdamThabet I assume those are test records and not your real credentials but I still get uncomfortable seeing a password and email posted like this ^^. Regarding your issue: 1) you could set a breakpoint in your controller to see weather your user actually gets created. Assuming he does (since its record is in the database apparently) you can 2) show us your Postman request (the issue might be invalid/incomplete request data) or 3) your backend - maybe also test that with a breakpoint - to see what you actually receive (i.e. there might be an encoding/decoding issue or something) – товіаѕ Mar 28 '22 at 13:23
0

I know where you are stuck ...

Go to auth.js file. In there use:

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

instead of ._id

Mahyar Mottaghi Zadeh
  • 1,178
  • 6
  • 18
  • 31