Home > Back-end >  How to activate and deactivate the User account using express & mongodb?
How to activate and deactivate the User account using express & mongodb?

Time:09-23

instead of deleting the user account from the database I want to deactivate an account to prevent them from login.

//Can not capture active field
router.post('/login', loginValidation, async (req, res) => {
  let user = await UserSchema.findOne;

  const { email, password } = req.body;
  console.log('Active = ', active);

  if (!email || !password)
    return res.json({
      status: 'error',
      message: 'Email and password are require',
    });

  const user = await getUserByEmail(email);
  const passFromDB = user && user._id ? user.password : null;

  if (!passFromDB)
    return res.json({ status: 'error', message: 'Wrong Email or Password' });
  console.log(user.name);
  const result = await comparePassword(password, passFromDB);
  if (!result) {
    return res.json({ status: 'error', message: 'Wrong Email or Password' });
  }
})

In User Schema I have active field with type Boolean to check if the user account is activate or deactivate. I can deactivate and activate from the admin route, but when it came to validation from the user login route as I show code above, the problem is I don't have any way to capture active field to check if the account is activated or not when user tries to log in.

//user schema
onst UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    //unique: true,
    maxLength: 50,
  },
password: {
    type: String,
    required: true,
  },
active: {
    type: Boolean,
    default: false,
  },
})
//admin deactivate and activate user accounts
router.patch(
  '/account',
  userAuthorization,
  roleBase(['admin']),
  async (req, res) => {
    await UserSchema.findOneAndUpdate(
      { _id: req.userId },
      { $set: { active: req.body.active } },
      { new: true }
    )
      .then((account) => {
        if (account)
          return res.json({ msg: 'User account deactivate successfully!' });
      })
      .catch((err) => {
        return res
          .status(500)
          .json({ msg: 'Unable to deactivate account', error: err.message });
      });
  }
);

Any suggestion or idea?

CodePudding user response:

You can achieve it in this way. By adding a check statement inside the router async function.

router.post('/login', loginValidation, async (req, res) => {
  const { email, password } = req.body;
    if (!email || !password)
    return res.json({
      status: 'error',
      message: 'Email and password are required',
    });
  const user = await User.find({email})
//Now you have the user data in user variable.
  console.log(`Active = ${user.active}`) 
  if(user.active !== true){
  //you can add your actions
  }
});

Thanks

  • Related