node.js - Passportjs 在注册时验证用户是否已存在

标签 node.js express passport.js

我正在尝试创建一个注册,其中数据库中已存在的用户将登录到系统中,否则将在系统中创建一个新用户。

到目前为止,我已经想出了以下代码。

//filename passport-config    
var config = require('./config');
var passport = require('passport');
var User = require('./models/user');
var LocalStrategy = require('passport-local').Strategy;

var isValidPassword = function(user, password){
    return bCrypt.compareSync(password, user.password);
};

  // Generates hash using bCrypt
var createHash = function(password){
   return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
}

  // As with any middleware it is quintessential to call next()
  // if the user is authenticated

var isAuthenticated = function (req, res, next) {
  if (req.isAuthenticated())
    return next();
  res.redirect('/');
}


passport.use('signup', new LocalStrategy({
    passReqToCallback : true
  },
  function(req, email, password, done) {
    findOrCreateUser = function(){
      // find a user in Mongo with provided email
      User.findOne({'email':email},function(err, user) {
        // In case of any error return
        if (err){
          console.log('Error in SignUp: '+err);
          return done(err);
        }
        // already exists
        if (user) {

            User.findOne({ 'email' :  email }, 
                      function(err, user) {                
                          if (!user){
                            console.log('User Not Found with email '+email);
                            return done(null, false);
                          }
                          // User exists but wrong password, log the error 
                          if (!isValidPassword(user, password)){

                            console.log('Invalid Password');
                            return done(null,false);
                          }
            });

        } else {
                  // if there is no user with that email
                  // create the user
                  var newUser = new User();
                  // set the user's local credentials
                  newUser.email = email;
                  newUser.password = createHash(password);         

                  // save the user
                  newUser.save(function(err) {
                    if (err){
                      console.log('Error in Saving user: '+err);  
                      throw err;  
                    }
                    console.log('User Registration succesful');    
                    return done(null, newUser);
                  });
          }
      });
    };

    // Delay the execution of findOrCreateUser and execute 
    // the method in the next tick of the event loop

    process.nextTick(findOrCreateUser);

  })
);

我的路由器

router.post('/signup', passport.authenticate('signup', {
    successRedirect: '/timeslot',
    failureRedirect: '/'
}));

  my server.js file 

    var express = require('express');
var bodyParser = require('body-parser');
var leisure = require('leisure');
var cors = require('cors');
var passport = require('passport');
var config = require('./config');
var passportConfig = require('./passport-config');
var session = require('express-session')
var expressHbs = require('express-handlebars');

var mediaTypes = [
  { contentType: 'application/hal+json' },
  { contentType: 'application/json' },
  { contentType: 'text/html' }
];


var app = express();



/*Handlebars */
app.engine('handlebars', expressHbs({layout: false}) );
app.set('view engine', 'handlebars');




app.use(express.static(__dirname + '/assets'));

app.use(cors(config.settings.cors));
app.use(bodyParser());
app.use(leisure.accept(mediaTypes));


/*sessions */
app.use(session({
  secret: 'keyboardSFS23432@@!#!@at'
}));
app.use(passport.initialize());
app.use(passport.session());






var routes = require('./routes');
app.use('/', routes.router);

function start () {
  var port = process.env.PORT || 3000;
  app.listen(port);
  console.log('Appoints service started on port ' + port);
}

exports.app = app;

exports.start = start;

注册路线根本不起作用,我对如何调试它感到非常困惑,任何建议将不胜感激。

最佳答案

关于node.js - Passportjs 在注册时验证用户是否已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27164952/

相关文章:

javascript - 如何在 Express 中访问 POST 表单字段

node.js - Multer 和 CSRF 以及 <form action ="?_method=PUT">

AngularJS获取passportjs策略失败消息

node.js - Node js - 在 ArrayBuffer 中存储大量数字

javascript - 向服务器传递参数(Stripe Connect 中的 oAuth 回调)

javascript - Protractor 本地和全局安装的行为不同

node.js - 使用 Node Fluent-ffmpeg 流式传输 mp4 视频

node.js - 在不在 App.js 中的函数中访问 i18next Translation

Node.js passport-jwt 如何在 cookie 中发送 token ?

node.js - 当 auth header 更改时 Express 创建不同的 session