Node.js护照本地注册同步呼叫

时间:2015-03-02 16:24:37

标签: javascript mysql node.js

我一直在尝试与Node.js相处,而我正努力学习一些核心内容。我的问题是在护照上我不知道如何进行同步通话。我想要的是:如果有一个用户已经注册了电子邮件,我不想创建它,生病一个flash消息,否则我将创建用户。我不确定如何在检查电子邮件唯一性后才创建用户。我在if语句中使用return true / false尝试了它,但它似乎没有。

我从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;
  }


});

};

1 个答案:

答案 0 :(得分:2)

您需要在函数isEmailInUse中返回回调。 在这个函数中,你正在调用运行对数据库的asyn调用的mysql.query。

将函数isEmailInUser更改为:

module.exports.isEmailInUse = function(req, callback){
    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 callback(null, true);
            }
            console.log('The solution is: ', rows);
            return callback(null, false);
        }
        else {
            console.log('Error while performing Query -> ' + err);
            return callback(err, false);
        }
    });
};

使用它:

IsEmailInUser(req, function(err, inUse){
    if(isUse){
        //create code
    }
    else {
        //send error to user
    }
});