mongoose 如何使用express & mongodb激活和停用用户帐户?

bfnvny8b  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(146)

我不想从数据库中删除用户帐户,而是想停用一个帐户以阻止他们登录。

//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' });
  }
})

在User Schema中,我使用类型为Boolean的active field来检查用户帐户是激活还是停用。我可以从管理员路径停用和激活,但当从用户登录路径进行验证时(如上面显示的代码),问题是当用户尝试登录时,我没有任何方法来捕获active field以检查帐户是否激活。
第一个
有什么建议或想法吗?

2vuwiymt

2vuwiymt1#

你可以通过在路由器异步函数中添加一个check语句来实现。

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
  }
});

谢谢

相关问题