WhoAmI
WhoAmI

Reputation: 317

Check if profile is admin or user and display accordingly

I am trying to display information based on role of user's login. If user is admin then display all the data from database and if other user then display only his details.

I tried this for /profile route after auth login

//get user details of login profile
router.get('/profile', checkAuth, (req, res, data) =>{  
    User.find(req.userData, function(err, users) {
        if (req.role === "admin") {
        return res.json(users);
        }else{
        res.send(req.userData);
        }
  });
});

The if condition is not working here if (req.role === "admin") Only res.send(req.userData); is working over here.

I have already mentioned the role in /login

const adminEmail = "[email protected]";                                               
    const role = user[0].email===adminEmail? "admin" : "user";                                  
    const token = jwt.sign( 
    {
        email: user[0].email,
        userId: user[0]._id,
        phoneNo: user[0].phoneNumber,
        role
    }

In response I am getting

{
    "email": "[email protected]",
    "userId": "5c2dee17ea4264a40156f0",
    "phoneNo": "8xxx25",
    "role": "admin",
    "iat": 1547111673,
    "exp": 1547115273
}

Upvotes: 0

Views: 1685

Answers (3)

WhoAmI
WhoAmI

Reputation: 317

I have solved it in this way

router.get('/profile', checkAuth, (req, res) =>{  
    if (req.userData.role === "admin") { 
        User.find({}, function(err, users) {
            res.json(users);
       });
    }else{
        res.send(req.userData); 
    }
});

Upvotes: 1

Alex M.
Alex M.

Reputation: 139

You try to check role in req, but it is undefined. First you have to check if user is logged up. Then, if user is admin, get some data from database. Otherwise, send user's object.

router.get('/profile', checkAuth, (req, res, data) =>{ 
    //  if req.userData is user object
    if(req.userData.role === 'admin') {
        User
        .find()
        .then(users => res.json(users))
        .catch(error => res.json({error}))
    } else {
        res.json(req.userData);
    }

});

Upvotes: 1

darth-coder
darth-coder

Reputation: 762

Why are you doing a user[0]??

It should be user["email"] or user.email directly.

Given your response a single object and not an array of objects.

Upvotes: 0

Related Questions