safak / youtube

5.04k stars 5.47k forks source link

TypeError: Cannot read property 'isAdmin' of undefined #56

Closed lanaarnous01 closed 2 years ago

lanaarnous01 commented 2 years ago

in verifyToken page const verifyTokenAndAdmin = (req, res, next) => { verifyToken(req, res, () => { if (req.user.isAdmin) { next(); } else { res.status(403).json("You are not alowed to do that!"); } }); }; isAdmin is not defined how can I fix this, please help

anilparlak commented 2 years ago

You should change the userName: req.body.user_name in auth.js like that username: req.body.username.

lanaarnous01 commented 2 years ago

it is changed const newUser = new User({ username: req.body.username,

lanaarnous01 commented 2 years ago

in postman when im searching for user but not as an admin, it prints out Token is not valid where it should print out You are not allowed to do that

anilparlak commented 2 years ago

Please check when you try login with admin user what is response. I'm not sure but response can be top of lists in the database. So, accessToken will not true for isAdmin:false. Check isAdmin is true

// in auth.js router.post('/login', async (req, res) => { try{ const user = await User.findOne( { username: req.body.username } ); can you fix it as above and try again if the mongo shemes are the same as on github?

lanaarnous01 commented 2 years ago

I did and still on postman it prints out Token is not valid

lanaarnous01 commented 2 years ago

const user = await User.findOne({userName: req.body.user_name}) should i only keep it like that?

anilparlak commented 2 years ago

I'm sorry I couldn't be of help. Make sure isAdmin of accessToken is true

lanaarnous01 commented 2 years ago

//auth.js const accessToken = jwt.sign({ id: user._id, isAdmin: user.isAdmin,

lanaarnous01 commented 2 years ago

in User model isAdmin: Type Boolean and default false

anilparlak commented 2 years ago

Yes it is. if you are trying in postman you should change it with true in your mongodb collection. After changing, make the changes in the code I mentioned above and try again. I did that and it worked

lanaarnous01 commented 2 years ago

Can you tell me the steps again so I could do them step by step and not get it wrong?

anilparlak commented 2 years ago

You should be an admin to list users. You should set the isAdmin of the user you want to be admin to true (you can do it in your collection). Then log in and get your accesToken from the reply. You will add this to the header when you get to list users. If you are getting an error while trying with the admin user, you can try making the changes I mentioned on the auth.js page.

lanaarnous01 commented 2 years ago

still not working