Я пытался совместить с Node.js, и я изо всех сил стараюсь изучить несколько основных вещей. Моя проблема в паспорте. Я не знаю, как сделать синхронный звонок. Я хочу, чтобы: Если у пользователя есть уже зарегистрированный адрес электронной почты, я не хочу его создавать, плохо бросаю флеш-сообщение, иначе я создам пользователя. Я не уверен, как создать пользователя только после проверки уникальности электронной почты. Я попробовал это с возвратом true/false в выражении if, но это просто не кажется правильным.Node.js Синхронный вызов в местном паспорте паспорта
Я адаптировал свой код из учебника паспортного пособия scotch.io.
// passport.js
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../app/models/user');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
if(!User.isEmailInUse(req)){
var newUser = {};
//create the user
User.createUser(req, newUser),
function(){
console.log('function ception ' + newUser)
if(newUser){
return done(null, newUser, req.flash('signupMessage', 'Great success!'));
}else{
return done(null, false, req.flash('signupMessage', 'An error has occurred.'));
}
};
console.log('what now?');
}else{
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
}
}));
};
// user.js
var mysql = require('../../config/database.js').mysql;
var bcrypt = require('bcrypt-nodejs');
// Create user.
module.exports.createUser = function(req, res){
var input = JSON.parse(JSON.stringify(req.body));
var salt = bcrypt.genSaltSync(10);
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
// create the user
var newUserMysql = {
email: input.email,
password: bcrypt.hashSync(input.password, salt, null), // use the generateHash function in our user model
isActive: 1,
createdAt: datetime
};
var insertQuery = "INSERT INTO tUsers (usrEmail, usrPassword, usrIsActive, usrCreatedAt) values (?,?, ?, ?)";
console.log('about to run insert into');
mysql.query(insertQuery,[newUserMysql.email, newUserMysql.password, newUserMysql.isActive, newUserMysql.createdAt],function(err, rows) {
if(!err){
newUserMysql.id = rows.insertId;
console.log('returning user');
res = newUserMysql;
}else{
console.log(err);
res = null;
}
});
};
module.exports.isEmailInUse = function(req){
var input = JSON.parse(JSON.stringify(req.body));
var selectQuery = "SELECT * FROM tUsers WHERE usrEmail = ?";
var query = mysql.query(selectQuery, [input.email], function(err, rows, fields) {
console.log(query.sql);
if (!err){
if(rows > 0){
return true;
}
console.log('The solution is: ', rows);
return false;
}
else
{
console.log('Error while performing Query -> ' + err);
return false;
}
});
};
в аргументе ERR функции (эээ, InUse) я должен передать переменную "ERR" в isEmailInUse вместо null? – FPJ
Я изменил образец кода, чтобы вернуть var. в зависимости от того, что вы хотите сделать, верните err var или нет. Я считаю, что первым аргументом является ошибка nodejs. –