node.js - 使用 Passport 注册后防止用户身份验证

标签 node.js express routes passport.js

我已经使用 Passport 和express.js 设置了登录/注册界面和机制。我遇到的问题是,用户注册后,我们会被重定向到登录页面,但我们最终可以更改 URL 并立即输入用户个人资料,但这当然不是预期和想要的。我希望用户在注册后未经过身份验证,并且他需要在进入其个人资料之前在登录页面中手动输入他/她的凭据。

router.get('/', isAuthenticated, function(req, res) {

  res.render('library', {
    // passing the id of and username the connecting user to the dust
    userid: req.user._id,
    username: req.user.userName
  });
});

router.get('/library', isAuthenticated, function(req, res) {
  res.render('library', {
    // passing the id of and username the connecting user to the dust
    userid: req.user._id,
    username: req.user.userName
  });
});

/* GET login page. */
router.get('/login', function(req, res) {
  // Display the Login page with any flash message, if any
  res.render('login', {
    message: req.flash('message')
  });
});

/* Handle Login POST 

password.authenticate is used to delegate the authentication 
to the login strategy when a HTTP POST is made to /login.
*/
router.post('/login', passport.authenticate('login', {
  successRedirect: '/library',
  failureRedirect: '/',
  failureFlash: true
}));

/* GET Registration Page */
router.get('/signup', function(req, res) {
  res.render('signup', {
    message: req.flash('message')
  });
});
/* Handle Registration POST 

password.authenticate is used to delegate the authentication 
to the signup strategy when a HTTP POST is made to /signup.
*/
router.post('/signup', passport.authenticate('signup', {
  successRedirect: '/login',
  failureRedirect: '/signup',
  failureFlash: true
}));

并且isAuthenticated函数/中间件定义如下

var isAuthenticated = function(req, res, next) {
  // if user is authenticated in the session, call the next() to call the next request handler 
  // Passport adds this method to request object. A middleware is allowed to add properties to
  // request and response objects
  if (req.isAuthenticated()) {
    return next();
  } else {
    res.redirect('/login');
  }

}

我做错了什么?

基本上,注册后,我有一个重定向到 / 的按钮,如果我们被重定向到 library (就像发生在我身上的情况一样),那么用户应该已经通过身份验证,但我不希望这样......

最佳答案

至少有两种解决方案:

  1. session: false 添加到您传递给 passport.authenticate('signup', {...}) 的配置对象,如 passportjs documentation 中所述。

  2. 请勿使用 Passport 进行注册。 Passport 的主要用例是用于身份验证(和建立 session ),DIY 注册逻辑或多或少只是从signup Passport 中间件复制代码。

关于node.js - 使用 Passport 注册后防止用户身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34145626/

相关文章:

node.js - 使用 Vue 处理来自 Express API 的错误

javascript - Express/nodejs 中的参数化路由 url 之后添加静态文件

c# - 路由,如果包含单词则匹配特定的url

node.js - 有没有办法阻止express渲染静态目录中的文件?

node.js - NextJS - 如何在循环内的图像链接中添加参数

javascript - Node.js 不会返回任何内容?

javascript - 如何将字符串{}值替换为obj(键值)

node.js - 如何从多部分表单数据中获取 Node JS 中间件中的请求主体?

node.js - 如何在 2 个应用程序之间共享 Mongoose 模型?

ios - 在 setRegion MapKit swift 中封装路线