Am developing application using Nodejs with MySQL..
For login Authentication am using passportJS.
There are two login in this application one for admin and another one for customer. so seperate tables is there are USERS and REGISTERS.
passport.serializeUser(function(user, done) {
done(null, {
id : user.id,
isAdmin : user.isAdmin // or some other property/check
});
});
// used to deserialize the user
passport.deserializeUser(function(user, done) {
var table = user.isAdmin ? 'register' : 'users';
connection.query('select * from ?? where id = ?', [ table, user.id ], function(err, rows) {
if (err) {
return done(err);
} else if (! Array.isArray(rows) || ! rows.length) {
return done();
} else {
return done(null, rows[0]);
}
});
});
In deserializeuser if i logging In with customer id...its checking with user table for same id...so am getting wrong data
Question Updated:
Local-Login for Admin
passport.use('local-login', 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) { // callback with email and password from our form
connection.query("select * from users WHERE email = '" + email + "'",function(err,rows){
if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
if (!( rows[0].password == password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, rows[0]);
});
}));
Customer-Login
passport.use('customer-login', new LocalStrategy({
usernameField : 'mobile',
passwordField : 'otp',
passReqToCallback : true
},
function(req, mobile, otp, done) {
connection.query("select * from register WHERE mobile = '" + mobile + "'",function(err,rows){
if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
if (!( rows[0].otp == otp))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
console.log(rows);
return done(null, rows[0]);
});
}));
For admin am using email as username for login
For customer am using mobile number for login
register
users
You don't have to serialize just the user id in serializeUser, it can also be an object that contains (for instance) the admin status (from your database contents, it looks like cust_code only exists for regular users, so we can use that to check if a user is an admin or not):
passport.serializeUser(function(user, done) {
done(null, {
id : user.id,
isAdmin : user.cust_code === undefined // this does require that `cust_code`
// is defined for all regular users.
});
});
This obviously assumes that the user document contains something that reflects if the user is an admin or not.
Using that object in deserializeUser you can determine which table to query:
passport.deserializeUser(function(user, done) {
var table = user.isAdmin ? 'users' : 'register';
connection.query('select * from ?? where id = ?', [ table, user.id ], function(err, rows) {
if (err) {
return done(err);
} else if (! Array.isArray(rows) || ! rows.length) {
return done();
} else {
return done(null, rows[0]);
}
});
});
Related
No matter what I change the user login will keep redirecting to failure instead of success. I don't know if I'm missing something or if I did something wrong. I tried to read the documentation for passport but, I found it pretty confusing. Here is my github link if you need to see the rest of the code. The node files are in app.js and passport-config.js.The sign up part of the website is working. https://github.com/gego144/to-do-list-website/tree/main
const customFields = {
usernameField: 'email',
passwordField: 'password'
}
const verifyCallback = (username, password, done) => {
user_exists = userName_Checker(username), function (err, user) {
if (err) { return done(err); }
if (userName_Checker(username) == false) {
console.log('wrong user');
return done(null, false, { message: 'Incorrect username.' });
}
if (password_finder(username, password)) {
console.log('wrong pass');
return done(null, false, { message: 'Incorrect password.' });
}
console.log('wtf');
return done(null, user);
};
;
}
const strategy = new LocalStrategy(customFields, verifyCallback);
passport.use(strategy);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// function that checks to see if the users email is in the database
function userName_Checker(email_name){
var sql = "select * from info where email = ?";
var user_email = [[email_name]];
db.query(sql, [user_email],function (err,result){
if (err) throw err;
var not_unique = result.length;
if(not_unique == 0){
return false;
}
else{
return true;
}
}
)}
// function that checks to see if the password in the database matches with the email
function password_finder(email_name, pass){
var sql = "SELECT password FROM info WHERE email = ?";
var user_email = [[email_name]];
db.query(sql, [user_email],function (err,result){
if (err) throw err;
bcrypt.compare(result, pass, function(err, res){
if(err){ throw err};
if(res){
return true;
}
else{
return false;
}
})
}
)}
My post method in my other file.
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect:'/index.html',
failureFlash: true
}))
Edit 1.
I just want to mention that the console.logs you see in verify Callback all don't log anything for some reason too.
The problem might be in the serialization logic.
In passport.serializeUser, you are passing in the whole user object, but when deserializing you are passing the id
Though I am not using SQL, the logic should be similar.
So the code should be something like this:
// Session
// Pass in user id => keep the session data small
passport.serializeUser((id, done) => {
done(null, id);
});
// Deserialize when needed by querying the DB for full user details
passport.deserializeUser(async (id, done) => {
try {
const user = await User_DB.findById(id);
done(null, user);
} catch (err) {
console.error(`Error Deserializing User: ${id}: ${err}`);
}
});
// Export the passport module
module.exports = (passport) => {
passport.use(new LocalStrategy({ usernameField: 'email', }, async (email, password, done) => {
try {
// Lookup the user
const userData = await User_DB.findOne({ email: email, }, {
password: 1, }); // Return the password hash only instead of the whole user object
// If the user does not exist
if (!userData) {
return done(null, false);
}
// Hash the password and compare it to the hash in the database
const passMatch = await bcrypt.compare(password, userData.password);
// If the password hash does not match
if (!passMatch) {
return done(null, false);
}
// Otherwise return the user id
return done(null, userData.id);
} catch (err) {
passLog.error(`Login Error: ${err}`);
}
}));
};
These options for passport seems to malfunction a lot or exhibit weird behaviors, so I suggest you handle the redirection logic like in my controller.
{ successRedirect: '/good',
failureRedirect: '/bad' }
Login controller logic:
(I am omitting the code here for session storage and made some modifications, but this code should work for what you need)
const login = (req, res, next) => {
//Using passport-local
passport.authenticate('local', async (err, user) => {
//If user object does not exist => login failed
if (!user) { return res.redirect('/unauthorized'); }
//If all good, log the dude in
req.logIn(user, (err) => {
if (err) { return res.status(401).json({ msg: 'Login Error', }); }
// Send response to the frontend
return res.redirect('/good');
});
});
})(req, res, next);
};
The actual route:
// Import the controller
const {login} = require('../controllers/auth');
// Use it in the route
router.post('/auth/login', login);
I build a simple web application where the user has notes. I want the user to be able to sign in with a google account as well, but the user didn't save into the database. The local login works but the social login doesn't. Wherever I searched I only found a solution in which mongodb was used. What is the correct way with mysql?
Here is my passport.js file:
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((req, user, done) => {
conn.query("SELECT * FROM user WHERE id = ? OR facebook_id = ? OR google_id", [user.id,
user.facebook_id, user.google_id], (err, rows) => {
if (err) {
console.log(err);
return done(null, err);
}
done(null, user);
});
});
passport.use(new GoogleStrategy({
clientID: configAuth.googleAuth.clientID,
clientSecret: configAuth.googleAuth.clientSecret,
callbackURL: configAuth.googleAuth.callbackURL,
passReqToCallback: true,
profileFields: configAuth.googleAuth.profileFields
},
function (req, accessToken, refreshToken, profile, done) {
process.nextTick(function () {
conn.query("SELECT * FROM user WHERE google_id = ?", [profile.id], (err, user) => {
if (err) {
return done(err);
} else if (user) {
return done(null, user);
} else {
let newUser = {
google_id: profile.id,
google_token: accessToken,
google_email: profile.emails[0].value,
google_name: profle.name.givenName + ' ' + profile.name.familyName
};
conn.query("INSERT INTO user (google_id, google_token, google_email, google_name) VALUES (?, ?, ?, ?)",
[newUser.google_id, newUser.google_token, newUser.google_email, newUser.google_name], (err, rows) => {
if (err) {
console.log(err);
}
return done(null, newUser);
})
}
});
});
}
));
And here are the routes:
app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/auth/google/callback', passport.authenticate('google', {
successRedirect: '/main',
failureRedirect: '/'
}));
I can log in, I didn't receive an error message, but if I want to assign a new note to the user it doesn't add it because it doesn't save the user to the database.
I think you forget to put ? after the google_id.
Example:
google_id=?
I am fairly new to node and I am trying to create a simple login/signup system with passportjs. I have my passport configuration file in which i pass the passport object as a parameter as you can see below.
My passport configuration file:
var LocalStrategy = require('passport-local').Strategy;
var User = require('./../models/user');
var mysql = require('./../database/mysql_setup');
var mysqlPool = mysql.pool;
// expose this function to our app using module.exports
module.exports = function(passport) {
mysqlPool.getConnection(function(error, connection) {
if (error) throw error;
connection.query('USE vidyawxx_build2');
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and deserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.username);
});
// used to deserialize the user
passport.deserializeUser(function(username, done) {
connection.query("SELECT * FROM `"+mysql.dbSpecs.prefix+"users` WHERE username = " + connection.escape(username), function(err,rows){
done(err, rows[0]);
});
});
// =========================================================================
// 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 : 'username',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// find a user whose username is the same as the forms username
// we are checking to see if the user trying to login already exists
connection.query("SELECT * FROM `"+mysql.dbSpecs.prefix+"users` WHERE `username` = "+connection.escape(username),function(err,rows){
if (err)
return done(err);
if (rows.length) {
return done(null, false, req.flash('error', 'This username is already in use.'));
} else {
// if there is no user with that username
// create the user
var newUserMysql = new User(username, password);
newUserMysql.generateHash(function(error, hash) {
if(error) {
return done(error);
}
var insertQuery = "INSERT INTO `"+mysql.dbSpecs.prefix+"users` ( username, password ) values (" + connection.escape(newUserMysql.username) +",'"+ hash +"')";
connection.query(insertQuery,function(err,rows){
if(err) {
return done(error);
}
return done(null, rows);
});
});
}
});
}
));
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// 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-login', new LocalStrategy({
// by default, local strategy uses username and password
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) { // callback with email and password from our form
connection.query("SELECT * FROM `"+mysql.dbSpecs.prefix+"users` WHERE `username` = " + connection.escape(username), function(err,rows){
if (err) {
return done(err);
}
if (rows.length === 0) {
return done(null, false, req.flash('error', 'Oops! Wrong username or password.')); // req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
var newUser = new User(username, password);
newUser.compareHash(function(error, result) {
if(result) {
return done(null, rows[0]);
} else {
return done(null, false, req.flash('error', 'Oops! Wrong username or password.')); // create the loginMessage and save it to session as flashdata
}
});
});
}
));
connection.release();
});
};
My problem lies in the fact that if my mysql server is down for any reason, the error is thrown in my first line. I want to be able to redirect my users to a simple page that gives him a message like "Something is wrong with the database, please try later". The thing is, when i throw the error, my app just shuts down giving any visitor the ERR_CONNECTION_REFUSED response.( I am currently working this locally.
This is my app.js file:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var passport = require('passport');
var passportConfig = require('./config/passport');
var session = require("express-session");
var flash = require("connect-flash");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
passportConfig(passport);
app.use(session({
secret: "aPa1fgOed(&fjkKLN34%#$lpv##",
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1000*60*15 } //15 minutes in milliseconds
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//create local vaariables for all our templates to use
app.use(function(req, res, next) {
res.locals.errors = req.flash("error");
res.locals.infos = req.flash("info");
res.locals.successes = req.flash("success");
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
That being said, since the error is thrown in my passport-config file, which doesnt follow the middleware convention of having a req, res and next params, how can i redirect my users to a page like the one mentioned above gracefully ?
Just to be sure, I will say this again, this concerns only mysql connection errors. I know that i can return other errors through my passport-config methods by using done(), but database connection errors occur outside the functions with a done param.
Thanks in advance
Looks like after some digging around the only workaround I could think of is incorporating the queries inside the passport configuration methods so that I could pass back any database connection error through the done() function;
This is my modified passport config file
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
var User = require('./../models/user');
var mysql = require('./../database/mysql_setup');
var mysqlPool = mysql.pool;
// expose this function to our app using module.exports
module.exports = function(passport) {
//connection.query('USE vidyawxx_build2');
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and deserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.username);
});
// used to deserialize the user
passport.deserializeUser(function(username, done) {
mysqlPool.getConnection(function(dbError, connection) {
if(dbError) {
return done(dbError);
}
connection.query("SELECT * FROM `"+mysql.dbSpecs.prefix+"users` WHERE username = " + connection.escape(username), function(err,rows){
if(err) {
done(err);
connection.release();
return;
}
connection.release();
done(err, rows[0]);
});
});
});
// =========================================================================
// 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 : 'username',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// find a user whose username is the same as the forms username
// we are checking to see if the user trying to login already exists
mysqlPool.getConnection(function(dbError, connection) {
if(dbError) {
return done(dbError);
}
connection.query("SELECT * FROM `"+mysql.dbSpecs.prefix+"users` WHERE `username` = "+connection.escape(username),function(err,rows){
if (err) {
connection.release();
return done(err);
}
if (rows.length) {
connection.release();
return done(null, false, req.flash('error', 'This username is already in use.'));
} else {
// if there is no user with that username
// create the user
var newUserMysql = new User(username, password);
newUserMysql.generateHash(function(error, hash) {
if(error) {
connection.release();
return done(error);
}
var insertQuery = "INSERT INTO `"+mysql.dbSpecs.prefix+"users` ( username, password ) values (" + connection.escape(newUserMysql.username) +",'"+ hash +"')";
mysqlPool.query(insertQuery,function(err,rows){
if(err) {
connection.release();
return done(error);
}
connection.release();
return done(null, rows);
});
});
}
connection.release();
});
});
}
));
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// 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-login', new LocalStrategy({
// by default, local strategy uses username and password
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) { // callback with email and password from our form
mysqlPool.getConnection(function(dbError, connection) {
if(dbError) {
return done(dbError);
}
connection.query("SELECT * FROM `"+mysql.dbSpecs.prefix+"users` WHERE `username` = " + connection.escape(username), function(err,rows){
if (err) {
connection.release();
return done(err);
}
if (rows.length === 0) {
connection.release();
return done(null, false, req.flash('error', 'Oops! Wrong username or password.')); // req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
var newUser = new User(username, password);
newUser.compareHash(function(error, result) {
if(result) {
connection.release();
return done(null, rows[0]);
} else {
connection.release();
return done(null, false, req.flash('error', 'Oops! Wrong username or password.')); // create the loginMessage and save it to session as flashdata
}
});
});
});
}
));
};
I am trying to build a user signup api using Passport, MySql, NodeJS and Sequelize. The only problem that i face is that when a user has signed up once and he tries to sign up again with the same email user is thrown a 401 Unauthorized Error instead of the user object. When i tried to debug the same the response that i was getting from the server was this
[object SequelizeInstance:users]. The files have been mentioned below. Thanks a tonnn in advance!!!.
Passport.js file:
var LocalStrategy = require('passport-local').Strategy;
var mysql = require('mysql');
var Model = require('../models/models.js');
// 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) {
connection.query("select * from users where id = " + id, function(err, rows) {
done(err, rows[0]);
});
});
// =========================================================================
// 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) {
Model.User.findOne({
where: {
email: email
}
}).then(function(user) {
if (user == null) {
Model.User.create({
email: email,
password: password
}).then(function(user) {
return done(null, user);
}).catch(function(err) {
return done(null, err);
});
} else {
return done(null, false);
}
})
}));
};
The Signup api:
router.post('/signup', passport.authenticate('local-signup'), function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
console.log(req.user);
if(req.user){
res.send({
success: true,
response: 'signup successful'
});
} else {
res.send({
success: false,
response: 'Email already in use'
});
}
});
The User model is:
//models/users.js
var Sequelize = require('sequelize')
var attributes = {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
created_by: {
type: Sequelize.INTEGER
}
}
var options = {
// Add the timestamps attributes (updatedAt, createdAt)
timestamps: true,
// don't delete database entries but set the newly added attribute deletedAt
// to the current date (when deletion was done). paranoid will only work if
// timestamps are enabled
paranoid: true,
// don't use camelcase for automatically added attributes but underscore style
// so updatedAt will be updated_at
underscored: true,
// disable the modification of table names; By default, sequelize will automatically
// transform all passed model names (first parameter of define) into plural.
// if you don't want that, set the following
freezeTableName: true,
// define the table's name
tableName: 'users'
}
module.exports.attributes = attributes
module.exports.options = options
The automated table creation model script is:
// models/models.js
var UserMeta = require('./users.js'),
connection = require('./index.js')
var User = connection.define('users', UserMeta.attributes, UserMeta.options)
// force: true will drop the table if it already exists
User.sync({
force: true,
match: /_servernew$/
}).then(function() {
// Table created
return User.create();
});
// you can define relationships here
module.exports.User = User;
So i came up with the solution. The following code needs to be changed.
router.post('/signup', function(req, res, next) {
passport.authenticate('local-signup', function(err, user, info) {
if(user){
req.logIn(user, function(err) {
if (err) {
return next(err);
} else {
res.send({
success: true,
response: 'signup successful'
});
}
});
}
if(!user){
res.send({
success: false,
response: 'Authentication Failed'
});
}
if(err){
res.send({
success: false,
response: 'Authentication failed'
})
}
})(req, res, next);
});
and the passport.js code should be like this.
// =========================================================================
// 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) {
Model.User.findOne({
where: {
email: email
}
}).then(function(user, err) {
console.log('I entered'+user);
console.log('I entered'+err);
if(err) {
console.log(err);
return done(null, false);
}
if(user == null) {
Model.User.create({
email: email,
password: password
}).then(function(user) {
return done(null, user);
}).catch(function(err) {
return done(null, err);
});
}
if(user){
return done(null, false);
}
})
}));
It will work just like a charm :D.
I'm fairly new to nodejs and callbacks. Here is my problem, using passportJS's LocalStrategy and node-mysql :
exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {
//get data from the request
var data = {
username: username,
email: req.body.email,
password: password
};
console.log('data : ', data);
//Hash passwords
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(password, salt, null, function(err, hash) {
// Store hash in your password DB.
if (err) return next(err);
data.password = hash;
//insertion
connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
if (err) {
console.log(err);
return next("Mysql error, check your query");
}
return done(null, rows[0]);
});
});
});
});
I'm trying to return rows[0] containing all the data, but i don't know how should i implement the SELECT command ? Is it before or after the callback for the insertion ? For the moment, rows[0] is naturally undefined.
what about using async.waterfall?
I solve similar problem.
insert query
get auto_incremnet number from rows[0]
select query
website of async here
https://github.com/caolan/async#waterfall
Also, as bcrypt is asyncronous,
data,password = hash
this code doesn't work properly.
I want to execute same type of code for yours but I can't.
So, I use bcrypt in Sync and pass the hash to query.
Here is my solution :
exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {
//get data from the request
var data = {
username: username,
email: req.body.email,
password: password
};
//Hash passwords
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return done(err);
}
// Store hash in your password DB.
bcrypt.hash(password, salt, null, function(err, hash) {
if (err) {
return done(err);
}
data.password = hash;
//insertion
connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
if (err) {
return done(null, false, {
message: 'Mysql error, check your query !'
});
}
// to return all the info in rows[0]
connection.query('SELECT * FROM USERS WHERE email = ?', data.email, function(err, rows) {
if (err) {
return done(null, false, {
message: 'Email not found !'
});
}
return done(null, rows[0]);
});
});
});
});
});