javascript - NodeJS 不喜欢通行证 + Sequelize 登录

标签 javascript node.js sequelize.js dom-events passport.js

我对 nodejs 快要疯了。我正在尝试使用 Passport-Local 和 Sequelize 库为由 NodeJS 提供支持的简单用户管理 web 应用程序实现后端。现在我刚刚设计了用户模型。我遇到的主要问题是注册过程给了我一个错误:看起来我正在处理一个 undefined object 。请有人帮我弄清楚发生了什么?
这是我的代码(与我在互联网上找到的一些解决方案合并 - 根据墨菲定律,显然没有任何效果)。
如果代码不好,请 Javascript 程序员原谅我。我的借口是,这是我第一次尝试使用 Javascript 进行编程,我必须为一个项目做这件事,最后(借口)但并非最不重要的是我是在 C 和微芯片中长大的。
错误:

TypeError: Cannot read property 'findOne' of undefined at Strategy._verify (/home/me/Documents/cerbero/config/passport.js:21:17)


应用程序.js
var app = express();


//blabla favicon stuff

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(session({ secret:'holaholaholaholaholaholahola',
                  resave:true,
                  saveUninitialized:true
                }));



app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

var models = require("./models")
require('./config/passport.js')(passport, models.usermodel);

app.use('/', index);
app.use('/user', require('./routes/users')(passport));


models.sequelize.sync().then(function(){
  console.log("Database connected");
}).catch(function(err) {
  console.log(err, "Somenthing went wrong with the dbdbdb");
});

 //blabla listening stuff



module.exports = app;
模型/用户模型.js
    module.exports = function(sequelize, Sequelize) {
  var User = sequelize.define('user', {

        id: {
            autoIncrement: true,
            primaryKey: true,
            type: Sequelize.INTEGER
        },

        username: {
            type: Sequelize.TEXT
        },

        public_key: {
            type: Sequelize.TEXT
        },

        email: {
            type: Sequelize.STRING,
            validate: {
                isEmail: true
            }
        },

        password: {
            type: Sequelize.STRING,
            allowNull: false
        },

        last_login: {
            type: Sequelize.DATE
        },

    });

    return User;
}
路线/用户.js
var express = require('express');

module.exports = function(passport, user) {
  var router = express.Router();

  //blablabla other routes
  router.get('/signup', function(req,res,next) {
    res.render('signup', {message: req.flash('signupMessage')});
  });


  router.post('/signup', passport.authenticate('local-signup', {
    successRedirect: '/user/dashboard',
    failureRedirect: '/user/signup'}
  ));

  router.post('/login', passport.authenticate('local'), function(req, res) {
    res.redirect('/');
  });



  return router;
};

function isLogged(req, res, next) {
  if (req.isAuthenticated())
    return next();

  res.redirect('/');
};
编辑
我忘记了 Passport 策略。
Passport .js
var bCrypt = require('bcrypt-nodejs');


module.exports = function(passport, user) {

    var User = user;
    var LocalStrategy = require('passport-local').Strategy;
    console.log('debug: sono nella routine');


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

        {
            usernameField: 'email',
            passwordField: 'password',
            passReqToCallback: true
        },
        function(req, email, password, done) {
          

            User.findOne({
                where: {
                    email: email
                }
            }).then(function(user) {
                if (user) {
                  return done(null, false, {message: req.flash('email already taken')});
                  console.log('mail already taken');
                }
                else {
                    var pass = generateHash(password);

                    var data =

                        {
                            email: email,
                            password: pass,
                            username: req.body.username,
                            public_key: '0',
                            last_login: null

                        };

                    User.create(data).then(function(newUser, created) {

                        if (!newUser) {

                            return done(null, false);

                        }

                        if (newUser) {

                            return done(null, newUser, {message: req.flash('tappost')});

                        }

                        next();

                    });

                }

            });

        }

    ));

    passport.deserializeUser(function(id, done) {

        User.findById(id).then(function(user) {

            if (user) {

                done(null, user.get());

            } else {

                done(user.errors, null);

            }

        });

    });


    passport.serializeUser(function(user,done) {
      done(null, user.id);
    });

var generateHash = function(password) {
                return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
              };

最佳答案

问题解决了。
“只是”改变了如何在passport.js中引用模型如下

var User = user;

不得不改写为
var User = db.user;

这里是最终的 Passport 策略文件
const db = require('./../models/');
var bCrypt = require('bcrypt-nodejs');


module.exports = function(passport) {

    var User = db.user;
    var LocalStrategy = require('passport-local').Strategy;

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

        {
            usernameField: 'email',
            passwordField: 'password',
            passReqToCallback: true
        },
        function(req, email, password, done) {
          var generateHash = function(password) {
            return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
          };

            User.findOne({
                where: {
                    email: email
                }
            }).then(function(user) {
                if (user) {
                  return done(null, false, {message: req.flash('email already taken')});
                  console.log('mail already taken');
                }
                else {
                    var pass = generateHash(password);

                    var data =

                        {
                            email: email,
                            password: pass,
                            username: req.body.username,
                            public_key: '0',
                            last_login: null

                        };

                    User.create(data).then(function(newUser, created) {

                        if (!newUser) {

                            return done(null, false);

                        }

                        if (newUser) {

                            return done(null, newUser, {message: req.flash('tappost')});

                        }

                    });

                }

            }).catch(function(err) {
              console.log(err);
            });

        }

    ));


    passport.serializeUser(function(user, done) {
            done(null, user.id);
        });

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




}

关于javascript - NodeJS 不喜欢通行证 + Sequelize 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44856291/

相关文章:

javascript - Google Cloud Storage - 如何直接从浏览器上传内容 (JavaScript)

javascript - Select2 - 只允许一个选定的和禁用的弹出窗口

node.js - 如何限制服务器使其仅允许 SSH、与外部 RabbitMQ 服务器的连接以及与外部 MongoDB 服务器的连接?

sql-server - Node JS Sequelize v4 在将数据插入 SQL Server 时生成错误

javascript - Sequelize.js 最小和最大长度验证器不工作

javascript - 如何在两个单元格之间拉伸(stretch)线(<td> 标签)

javascript - JQuery获取按钮的标题

javascript - 在功能组件中使用外部js库

node.js - node进程内存占用,resident set size不断增加

postgresql - 如何使用 Sequelize.js 显示语句的执行计划