无法使用本地护照注册用户

时间:2016-11-20 14:00:57

标签: node.js express sequelize.js passport.js

我试图使用本地护照登录并注册我的应用程序。

但是当我从我的注册表单发送帖子请求时,用户将被重定向到注册表单。

这是路线定义:

app.post('/signup', passport.authenticate('local-signup', {
        successRedirect : '/profile', // redirect to the secure profile section
        failureRedirect : '/signup', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

这是我的config / passport.js

var LocalStrategy   = require('passport-local').Strategy;
var User            = require('../models/user');
var mysql = require('mysql');
var connection = mysql.createConnection({
  host     : process.env.MYSQL_HOST,
  user     : process.env.MYSQL_USER,
  password : process.env.MYSQL_PASSWORD,
  database : process.env.MYSQL_DB
});

module.exports = function(passport) {
    passport.serializeUser(function(user, done) {
        console.log("abc serializeUser");
        console.log(user);
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        console.log("abc deserializeUser");
        User.findById(id).then(function(user){
            done(null, user);
        }).catch(function(e){
            done(e, false);
        });
    });

    passport.use('local-signup', new LocalStrategy(

        function(username, password, done) {
            console.log("abc local signup");
            User.findOne({where: {username: username}}).then(function(err, user) {
               if (err) { return done(err); }
               if (!user) {
                   console.log('Incorrect username.');
                   return done(null, false, { message: 'Incorrect username.' });
               } else if (password != user.password) {
                   console.log('Incorrect password');
                   return done(null, false, { message: 'Incorrect password.' });
               } else {
                   console.log('ok');
                   done(null, user);
               }
            });

        }

    ));

};

这是models / user.js

"use strict";

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    token: DataTypes.STRING
  } 

  );

  return User;
};

1 个答案:

答案 0 :(得分:1)

Sequelize的.then()仅接收结果,错误应由.catch()块处理。所以查询将如下所示:

        User.findOne({where: {username: username}}).then(function(user) {
           if (!user) {
               console.log('Incorrect username.');
               return done(null, false, { message: 'Incorrect username.' });
           } else if (password != user.password) {
               console.log('Incorrect password');
               return done(null, false, { message: 'Incorrect password.' });
           } else {
               console.log('ok');
               done(null, user);
           }
        }).catch(function(err){
           done(err);
        });