我想用express和Sequelize将用户注册到MySQL数据库。
首先,我应该确定我的客户端(AngularJS)将数据发布到我的routes.js(req.body包含我的数据)文件中:
var bodyParser = require('body-parser');
var passport = require('passport');
var session = require('express-session');
module.exports = function (app) {
//BodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//Passport
app.use(session({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.post('/registered', function (req, res) {
console.log(req.body);
res.end();
});
}
接下来,我为Sequelize创建了一个模型User:
module.exports = function (sequelize, Sequelize) {
var User = sequelize.define('user', {
id: {
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstname: {
type: Sequelize.STRING,
notEmpty: true
},
lastname: {
type: Sequelize.STRING,
notEmpty: true
},
email: {
type: Sequelize.STRING,
validate: {
isEmail: true
}
},
password: {
type: Sequelize.STRING,
allowNull: false
},
password_confirmation: {
type: Sequelize.STRING,
allowNull: false
}
});
return User;
}
现在,我想用sequelize创建一个用户进入我的数据库,所以我在那里有一个passport.js文件:
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport, user) {
var User = user;
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-registered', new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
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: 'That email is already taken'
});
} else
{
var userPassword = generateHash(password);
var data =
{
email: email,
password: userPassword,
firstname: req.body.firstname,
lastname: req.body.lastname
};
User.create(data).then(function(newUser, created) {
if (!newUser) {
return done(null, false);
}
if (newUser) {
return done(null, newUser);
}
});
}
});
}
));
}
哪个哈希密码并使用sequelize函数user.create()等..
已完成与数据库的连接,我的模型已正确加载,但我想将所有污染我的server.js文件的文件分开。
这就是为什么我创建了一个路径文件夹,其中包含我的所有处理数据的路径。
但我的问题是我不知道如何将我的passport.js用于我的routes.js文件。
请问好吗?