lundi 2 mars 2015

Node.js Synchronous call on passport local signup


I've been trying to get along with Node.js and I'm struggling to learn a few core things. My problem is in passport I dont know how to make a synchronous call. What I want is: If there is a user with the signup email already, I dont want to create it, ill throw a flash message, otherwise i'll create the user. I'm not sure how to only create the user after the check up for the email uniqueness. I tried it with return true/false in a if statement but it just doesn't seem right.


I adapted my code from scotch.io's passport tutorial.



// 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;
}


});

};




Aucun commentaire:

Enregistrer un commentaire