繁体   English   中英

Node.js护照本地注册上的同步调用

[英]Node.js Synchronous call on passport local signup

我一直在尝试与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;
  }


});

};

您需要在函数isEmailInUse中返回一个回调。 在此函数内部,您正在调用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
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM