1
我一直在努力與Node.js相處,並且我努力學習一些核心內容。我的問題是護照我不知道如何進行同步呼叫。我想要的是:如果有用戶使用註冊電子郵件,我不想創建它,不會拋出閃光消息,否則我會創建用戶。我不確定如何在檢查電子郵件唯一性後才創建用戶。我在if語句中使用return true/false來嘗試它,但它看起來不正確。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)我應該通過變量 「犯錯」 的isEmailInUse而不是null? – FPJ 2015-03-02 22:36:39
我更改了示例代碼以返回「err」變種。取決於你想要做什麼,返回err var或不。我相信第一個參數是錯誤是nodejs慣例。 – 2015-03-02 22:52:14