简体   繁体   English

如果用户标记设置为true,如何使用passport.authenticate?

[英]How to use passport.authenticate if flag on user is set to true?

I want to let the users log in to my webapp only if a flag/property called isVerified on the user is set to true(by default is false). 我只想让用户上名为isVerified的标志/属性设置为true(默认为false)时,才允许用户登录到我的isVerified应用程序。

currently I have a login route: 目前我有一个登录路线:

router.post('/login', authController.login);

which goes the the POST login controller: 这是POST登录控制器:

exports.login = passport.authenticate('local', {
  failureRedirect: '/login',
  failureFlash: 'Failed Login!',
  successRedirect: '/',
  successFlash: 'You are now logged in!'
});

But I want to only let the users be logged in, only if the isVerified flag on the user is set to true. 但是,仅当用户的isVerified标志设置为true时,我才希望允许用户登录。

which would be set after they click on a link i sent them after registering. 在他们单击注册后我发送给他们的链接后进行设置。

This is what I tried so far, I changed the login method to do this: 到目前为止,这是我尝试过的方法,为此我更改了登录方法:

When they try to login, i check if that user has the flag isVerified set to true If is false, throw an error and redirect them to login, and tell them they need to click on the lin on the email. 当他们尝试登录时,我检查该用户是否将isVerified标志设置为true如果为false,则抛出错误并将其重定向到登录名,并告诉他们需要单击电子邮件上的林。 If is set to true i want to log them in. 如果设置为true,我要登录。

But it gets stuck.. just loading, what Im I doing wrong? 但是它卡住了..只是加载,我在做什么错? this how I modified the login methid from above: 这就是我从上面修改登录方法的方式:

exports.login = async (req, res) => {

  const user = await User.findOne({ email: req.body.email });
  if (!user) {
    req.flash('error', 'No account with that email exists.');
    return res.redirect('/login');
  }

  if (user.isVerified) {
    passport.authenticate('local', {
      failureRedirect: '/login',
      failureFlash: 'Failed Login!',
      successRedirect: '/',
      successFlash: 'You are now logged in!'
    });
  } else {
    req.flash('Warning', `Please verify your account by clicking on the link we sent you to ${req.body.email}`);
    return res.redirect('/login');
  }

};

Also I have passport setup like this: 我也有这样的护照设置:

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

Any ideas what could be the problem? 任何想法可能是什么问题?

I found the solution, I am using the passport-local-mongoose package, and in their documentation the have an example on how to do exaclty this: 我找到了解决方案,我使用的是passport-local-mongoose包装,在他们的文档中有一个有关如何做到这一点的示例:

https://github.com/saintedlama/passport-local-mongoose#allow-only-active-users-to-authenticate https://github.com/saintedlama/passport-local-mongoose#allow-only-active-users-to-authenticate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM