Wednesday, October 19, 2022

[FIXED] How can I verify admin in frontend from backend? (Node.js, Angular, Mongodb)

Issue

In the user model, I have a property called isAdmin which default value is false. In MongoDB, I manually created an admin account who has property isAdmin set to true. When I log in as an admin, the program verifies it and terminal shows "admin". But how move this true value to frontend to check if it's admin? What can I write then in frontend?

    isAdmin: {
        type: Boolean,
        default: false
    },
router.post('/login', (req, res) => { 
  let userData = req.body;

  User.findOne({ email: userData.email }, (error, user) => {
    if (error) {
      console.log(error);
    } else {
      if (!user) {
        res.status(401).send('Invalid email');
      } else
        if (user.password !== userData.password) {
          res.status(401).send('Invalid password')
        } else {
          if (user.isAdmin) { // admin <--------------------
            console.log('admin');          
          }
          let payload = { subject: user._id };
          let token = jwt.sign(payload, 'secretKey');
          res.status(200).send({ token });
        }
    }

  })
})

Solution

I return the isAdmin flag alongside the token and it works.



Answered By - Weronika
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.