I am trying to check whether the signed in user is admin or not. User data is stored in a format like this:
[
{
"isAdmin": "true",
"_id": "60c6df22f25d381e78ab5f31",
"name": "Admin",
"email": "admn@xyz.com",
"password": "$2a$10$dPF0rtehOYXv5aLkmxXgw.99horXCuzbQgvu5ywRaa5C73xQJpaG6",
"__v": 0,
"createdAt": "2021-06-14T04:46:26.769Z",
"updatedAt": "2021-06-14T04:46:26.769Z"
},
{
"isAdmin": "false",
"_id": "60c6df22f25d381e78ab5f32",
"name": "Messi",
"email": "messi@xyz.com",
"password": "$2a$10$Lkhuz2///oLfrCRMSYoHoeS3QHUCNQDH3OyiN6LyveogGfzldSBDC",
"__v": 0,
"createdAt": "2021-06-14T04:46:26.770Z",
"updatedAt": "2021-06-20T03:45:44.533Z"
},
]
when the user enter its credentials I am passing adminMiddleware to check wheather isAdmin is false or true. But when I tested it in thunder client I got user data no matter who's bearer token I passed (Admin or normal users).
here is the source code:
adminMiddleware.js
const admin = (req, res, next) => {
try {
console.log("Name:", req.user.name);
console.log("isAdmin:", req.user.isAdmin);
if (req.user && req.user.isAdmin) {
next();
} else {
const error = new Error("Not Authorized As An Admin");
error.status = 401;
next(error);
}
} catch (error) {
next(error);
}
};
module.exports = admin;
userRoutes.js
const express = require("express");
const {
registerUser,
getUsers,
} = require("../controllers/userController");
const protect = require("../middleware/authMiddleware");
const admin = require("../middleware/adminMiddleware");
const router = express.Router();
router.route("/").post(registerUser).get(protect, admin, getUsers);
module.exports = router;
I console logged the isAdmin value for both admin and normal user by there Bearer Token respectively and got:


Aucun commentaire:
Enregistrer un commentaire