我正在尝试使用节点中的ORM Sequelize设置用户登录和注册。我的注册部分工作正常。我的模型实例被定义为User,当我调用User.createUser时,我的模型函数工作,并且用户被添加到db。但是,当我尝试在护照本地策略中使用我的getUserNameById函数时,出现“用户未定义”错误。我已经被困了一天试图解决这个问题。
模型文件(我导入了sequelize,bcrypt,并创建了一个连接)
var Users = connection.define("Users", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING
},
account: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
}, {
timestamps: false
});
Users.sync();
connection.authenticate()
.then(function () {
console.log("CONNECTED! ");
})
.catch(function (err) {
console.log("MYSQL ERROR: FAILED TO CONNECT");
})
.done();
module.exports = function (connection, DataTypes) {
return Users;
}
module.exports.createUser = function (newUser) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
Users.create(newUser).then(function (Users){
console.dir(Users.get());
})
});
});
}
module.exports.getUserByUsername = function (username) {
return Users.find({
where: {username: username}
}).then(function (user) {}, function (err) {
console.log(err);
});
}
module.exports.comparePassword = function(candidatePassword, hash, done, user){
bcrypt.compare(password, hash, function(err, isMatch){
if (err) console.log(err)
if (isMatch) {
return done(null, user)
} else {
return done(null, false)
}
});
}
module.exports.getUserById = function(id, callback){
Users.findAll({
where: {id: id}
});
}
我的路线代码,特别是我遇到问题的本地护照策略
var User = require("../models/users");
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function (username, password, done) {
User.getUserByUsername(username, function (user) {
if(!user){
return done(null, false, {message:'Incorrect username'})
}
})
User.comparePassword(password, user.password, function (err, isMatch) {
if(err) throw err;
if(isMatch){
return done(null, user);
}else{
return done(null, false, {message: 'Invalid password'});
}
})
}
));
答案 0 :(得分:0)
您的./models/user
类正在导出一个以connection
和DataTypes
作为参数的函数,但您没有将它们传入 - 连接应该通过。您无需致电connection.authenticate()
。
// new db connection
var connection = new Sequelize(
schema,
username,
password,
{
host: host,
dialect: dialect,
}
)
var DataTypes = // define DataTypes
// pass into User
var User = require("../models/users")(connection, DataTypes);