accessing global function with javascript using mysql - javascript

I am trying to validate the user before accessing the content. I have declared function globally and passing it inside the body. When I run it , I am getting error has: user doesn't exist . Please let me know where I am going wrong.
function validate(user_id){
var user_id = db.query('select user_id from user WHERE user_id = ?', [user_id],
function(error,rows) {
if (user_id != user_id) {
return false;
} else {
return true;
}
});
}
router.post('/addcustomerskills', function(req,res) {
if (validate(user_id == true)) {
return true;
// my code should execute
}else {
response.success= false;
response.mssg = "User Doesn't Exist";
res.json(response);
}

function validate(user_id, req, res){
db.query('select user_id from user WHERE user_id = ?', [user_id], function(error,rows) {
if (error || rows.length === 0) {
var response = {}
response.success= false;
response.mssg = "User Doesn't Exist";
res.json(response);
} else {
// my code should execute
return true;
}
});
}
router.post('/addcustomerskills', function(req,res) {
validate(req.body.user_id, req, res);
})

Related

Trouble solving: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I'm working on a simple web app using node-pg and express.js with a login page and a dashboard that displays some data from a database.
The dashboard and all it's data loads fine initially using the following function after the user inputs their username and password:
const queryLogin = (request, response) => {
var username = request.body.username;
var password = request.body.password;
if (username && password) {
Promise.all([
pool.query('SELECT * FROM jobdesc WHERE complete=0 AND customer=$1 ORDER BY date_rec ASC LIMIT 10', ['somecustomer']),
pool.query('SELECT * FROM accounts WHERE email=$1 AND password=$2', [username, password],)
]).then(function([orderResults, results]) {
if (results.rows.length > 0) {
request.session.loggedin = true;
request.session.username = username;
var user = username;
var orderObj = orderResults.rows;
if (results.rows[0].account_type == 1) {
request.session.account_type = 1;
response.render('pages/index');
} else if (results.rows[0].account_type == 0) {
request.session.account_type = 0;
response.render('pages/dashboard', {
user: user,
orderObj: orderObj
});
} else {
console.log("Invalid Account Type");
}
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
}, function(error) {
throw error;
});
} else {
response.send('Please enter Username and Password!');
response.end();
}
}
The issue is that I have a link in my navbar that redirects to the dashboard (in the case that the user navigates to a different page and wants to return to the home page). When pressed I get the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
The route I use to try and redirect to the home page is: app.get('/home', con.launchDashboard)
And the code for the function is:
const launchDashboard = (request, response) => {
if (request.session.loggedin) {
Promise.all([
pool.query('SELECT * FROM jobdesc WHERE complete=0 AND customer=$1 ORDER BY date_rec ASC LIMIT 10', ['somecustomer'])
]).then(function([orderResults]) {
if (request.session.account_type == 1) {
return response.render('pages/index');
}
else if (request.session.account_type == 0) {
var user = request.session.username;
var orderObj = orderResults.rows;
return response.render('pages/dashboard', {
orderObj: orderObj,
user: user
});
}
})
} else {
response.render('pages/login');
}
response.end();
}
I'm unsure of why I am getting this error, I am confused with where I am setting headers after they are sent to the client.

How to wait for results inside an if statement in js?

I'm bulding a node.js backend for a webapp and when i submit a form, i do various validations. One of them is to check if an invitation already exists with the same email address.(isUserAlreadyInvited function)
I created a function for this, however when i call this, i guess the response is not that fast and it just moves to the next statement even if the check returns true. How
//Loop through emails one by one
var emails_to_invite = ["test#test.com","invalid.com"];
var response_items = [];
async.each(emails_to_invite,
function(email, callback){
//Response item
var response_item = {}
response_item.email = email;
//Validate
if(Joi.validate({ email: email }, apiSchema).error) {
response_item.error = "not valid email";
response_items.push(response_item);
callback();
} else if(email == user.email) {
response_item.error = "Sending an invitation to your own email is kinda dumb";
response_items.push(response_item);
callback();
} else if(isUserAlreadyInvited(email,user_id)) {
response_item.error = "already invited";
response_items.push(response_item);
callback();
} else {
sendInvitationEmail(email,user_id,null,null,function(invitation_code){
if(invitation_code) {
response_item.invitationCode = invitation_code;
} else {
response_item.error = "server error";
}
response_items.push(response_item);
callback();
});
};
},
function(err){
//Return response
res.status(200).send(response_items);
}
);
function isUserAlreadyInvited(email,invited_by) {
User.findOne({
email: email,
invited_by: invited_by
}, function(err, user) {
if(err) {
return false;
} else {
return true;
}
});
}
Two returns here:
function isUserAlreadyInvited(email,invited_by) {
User.findOne({
email: email,
invited_by: invited_by
}, function(err, user) {
if(err) {
return false;
} else {
return true;
}
});
}
are defined inside this function
function(err, user) {
if(err) {
return false;
} else {
return true;
}
}
and have nothing with return value of isUserAlreadyInvited().
Apparently your isUserAlreadyInvited() is an asynchronous function that needs to be treated asynchronously - it shall get callback function as a parameter. That callback shall be invoked in place of that function(err, user) {}

Node JS validation

I'm new to NodeJS, and have written a method to create a new user, but I need to validate the parameters passed. I'm attempting make sure that an email is not registered twice. This doesn't work, because it checks if the error array is empty before the self.emailExists() callback is completed, how do I fix this?
userSchema.statics.buildUser = function(email, name, cb) {
var self = this;
var user = new this();
var errors = [];
if (!validator.isEmail(email)) {
errors.push({
'err': -1,
'msg': 'Invalid email'
});
} else {
self.emailExists(email, function(exists) {
if (exists) {
errors.push({
'err': -1,
'msg': 'Email address is already in use'
});
} else {
user.email = email;
}
});
}
if (!validator.trim(name).length > 0) {
errors.push({
'err': -1,
'msg': 'Invalid name'
});
} else {
user.name = name;
}
if (errors.length != 0) {
cb(errors, null);
} else {
cb(false, user);
}
}
My emailExists method is:
userSchema.statics.emailExists = function(email, cb) {
var self = this;
self.count({email: email}, function (err, count) {
cb(count > 0);
});
}
You need to restructure your code to put the errors.length check in emailExists() callback. Try Async.js and Promises to manage asynchronous calls better

AngularJS javascript function gets stuck inside an else statement

I have this code whereby i want to check if code input data is the same in the local db. This code works fine until it gets to where i have marked as code hangs or stops here. Once the code gets to the condition it runs perfectly and assigns notifier to be true but it doesnt come out of that function and is stuck there hence the remaining part of the code is not executed. Can anyone explain to me why ? I am building an Ionic, AngularJS app.
function checklocalDB(localdb, result) {
var d= $q.defer();
var identifier = false;
var notifier = false;
// var f = function(localdb, result){
if(localdb === false) {
console.log("inside localdb false")
var insert_into_table = "INSERT INTO preferences(description, value) VALUES ('username','" + result[0].username + "'), ('token','" + result[0].token.toString() + "')";
$cordovaSQLite.execute(db, insert_into_table).then(function (res) {
console.log("executedd")
var updateDB = "UPDATE preferences SET value='true' WHERE description='registered'";
$cordovaSQLite.execute(db, updateDB).then(function (res) {
console.log("executed")
identifier = true;
notifier = true;
//d.resolve(identifier)
var query = "SELECT id, description, value FROM preferences";
$cordovaSQLite.execute(db, query).then(function (res) {
}, function (err) {
console.error(err);
});
}, function (err) {
console.error(err);
});
});
}
else {
console.log("inside localdb true")
var dbNew = null;
var query = "SELECT id, description, value FROM preferences";
console.log(localdb)
$cordovaSQLite.execute(db, query).then(function (res) {
console.log("hhhhhhhhhhhhhh")
console.log(res.rows.item(2).value)
console.log(result[0].username)
if(res.rows.item(2).value != result[0].username) {
console.log("username different")
$cordovaSQLite.deleteDB("loanstreet_partners.db");
dbNew = $cordovaSQLite.openDB("loanstreet_partners.db");
$cordovaSQLite.execute(dbNew, "CREATE TABLE IF NOT EXISTS preferences (id integer primary key, description string, value string)").then(function (res) {
console.log("done")
var insert_into_table = "INSERT INTO preferences (description, value) SELECT 'registered' as registered, 'false' as value UNION SELECT 'logged_in', 'false'";
$cordovaSQLite.execute(db, insert_into_table).then(function (res) {
console.log("1st")
var insert_into_table = "INSERT INTO preferences(description, value) VALUES ('username','" + result[0].username + "'), ('token','" + result[0].token.toString() + "')";
$cordovaSQLite.execute(db, insert_into_table).then(function (res) {
console.log("2nd")
identifier = true;
notifier = true;
var updateDB = "UPDATE preferences SET value='true' WHERE description='registered'";
$cordovaSQLite.execute(db, updateDB).then(function (res) {
}, function (err) {
console.error(err);
});
});
}, function (err) {
console.error(err);
});
}, function (err) {
console.error(err);
});
}
else {
notifier = true;
console.log("im here")
return notifier;
// ***code hangs or stops here***
}
}, function (err) {
console.error(err);
});
}
// ***this is never executed because it still remains false***
if(notifier === true) {
console.log(identifier)
console.log(notifier)
d.resolve(identifier)
}
return d.promise;
// watch identifier when value change then only resolve
//d.resolve(identifier)
//return d.promise;
}
Any help appreciated

Understanding Node.js processing order

I'm having problems understanding the processing order in Node.js.
My Problem:
I coded a little Application that saves a session in a cookie with the following properties:
session.email = email;
session.randomHash = randomHash;
The randomHash var is a random String that gets generated and saved to a db everytime the user logs in.
If a user with a session now wants to view a private page the method checkSession() gets called:
exports.checkSession = function(req, res) {
if(req.session) {
var User = mongoose.model("User", userSchema);
User.count({email: req.session.email, randomHash: req.session.randomHash}, function(err, count) {
if(count === 0) {
return false;
}
if(count === 1) {
return true;
}
});
}
else {
return false;
}
};
The method compares the randomHash of the cookie with the randomHash value of the Db.
This method is called in a route:
exports.init = function(req, res) {
if(hashing.checkSession(req, res)) {
res.render("controlpanel", {title: "Controlpanel", email: req.session.email});
}
else {
res.send("Sorry but you are not logged in. Go to /login");
}
};
Now there must be the problem.
Because of Nodes non-blocking style the method gets called but doesn't finish before the if-statement is executed.
What can i do about it?
The return value in your User.count callback is not the return value of checkSession. The User.count callback doesn't run until after checkSession has finished.
Pass a callback to checkSession and call it in User.count:
exports.checkSession = function(req, res, callback) {
if(req.session) {
var User = mongoose.model("User", userSchema);
User.count({email: req.session.email, randomHash: req.session.randomHash}, function(err, count) {
if(count === 0) {
callback(false);
}
if(count === 1) {
callback(true);
}
});
}
else {
callback(false);
}
};
And call it like:
exports.init = function(req, res) {
hashing.checkSession(req, res, function(result) {
if(result) {
res.render("controlpanel", {title: "Controlpanel", email: req.session.email});
}
else {
res.send("Sorry but you are not logged in. Go to /login");
}
});
};

Categories

Resources