Hi I need help figuring out how to get my string entry in my database into a variable. All of my code works and if I copy and paste the exact string from my database into my bcrypt compare call it works perfectly. Basically my problem is that my variable "compare" prints out as
[{"password": "$2a$10$eilJb6SGKSSQm2b.U5tj.ut4o8.oHyJNVhbkpjcpeomCj4GlMEyqC"}]
but I just need
"$2a$10$eilJb6SGKSSQm2b.U5tj.ut4o8.oHyJNVhbkpjcpeomCj4GlMEyqC". Any ideas?
account.on("end", function(result) {
if(result.rows.length > 0){
console.log("found account: ");
console.log(JSON.stringify(result.rows, null, " "));
//turn the db entry into a string
compare = JSON.stringify(result.rows, null, " ");
//compare the hashed password from database to parameter for password change
bcrypt.compare(password, compare, function(err, res) {
console.log("res result: " + res);
if(res){
console.log("passwords are same");
//new query updating the password in the db
if(person=="s"){
//update db
client.query('UPDATE students SET password=($2) WHERE email=($1)',
[req.body.email, hash_new]);
console.log("changed students password");
} else {
//update db
client.query('UPDATE teachers SET password=($2) WHERE email=($1)',
[req.body.email, hash_new]);
console.log("changed teacher password");
}
} else {
console.log("passwords are not the same");
}
});
} else {
console.log("account not found!");
}
});
Instead of
compare = JSON.stringify(result.rows, null, " ");
try
compare = result.rows[0].password;
You don't need the JSON string but the JavaScript value.
Related
I am new to node.js and I try to render different pages based on some conditions, however, I sometimes meet the problem "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client", I think this is because of the asynchronous behavior of node.js. How can I fix this problem?
I tried setTimeout but I think that's not the right way to do that.
The following part is the section where I met this issue:
/*
signup err code:
0 stand for no errors,
1 stand for confirmPassword and password not match
2 stand for user already exist
*/
app.post('/signup',(req, res) => {
//initialize the signupErr to be 0
signupErr = 0;
//get the data from the post request
let username = req.body.username;
let email = req.body.email;
let password = req.body.password;
let confirmPassword = req.body.confirmPassword;
let organization = req.body.organization;
/*first check the twice entered password, if not match set error number to 1 for the server to render the corresponding error message*/
if (password!=confirmPassword){
signupErr = 1;
res.redirect('/signup');
}
//form the query to consult the database to check if user exists
let queryUsername = "SELECT password FROM User WHERE Username = " + "'" + username + "'";
let queryEmail = "SELECT email FROM User WHERE Email = " + "'" + email + "'";
// check if username exists
connection.query(queryEmail,(err,results) => {
if(err){
console.log("Errore login: " + err);
} else if(results.length!=0) {
signupErr = 2;
res.redirect('/signup');
}
});
//check if email exists
connection.query(queryUsername,(err,results) => {
if(err){
console.log("Errore login: " + err);
} else if(results.length!=0) {
signupErr = 2;
res.redirect('/signup');
}
});
// form the insertion query if no err found
let queryInsert = "INSERT INTO `PIA`.`User` (`Username`, `Email`, `Password`,`Organization`) VALUES ('"+username +"', '"+ email +"', '"+password +"', '"+organization + "')";
// insert the data into the database
connection.query(queryInsert,(err,results) => {
if(err){
console.log("Errore login: " + err);
} else{
console.log("Inserted");
res.render('main');
}
});
});
The insertion part will still run sometime after the redirect.
I'll be really grateful if you can give me any ideas on how to solve that.
I'm trying to update objects in an array from my Mongo database and saving the updated values back to the database. However, after calling save on the data I changed, nothing gets updated to the database.
router.post('/:poll*', (req, res)=>{
var url = '/poll' + req.url;
Poll.findOne({link: url}, (err, data)=>{
if(err){
throw err;
}
else{
var theValue;
for(var key in req.body){
if(key === 'opt'){
theValue = req.body[key];
}
}
var voteCount;
if(data.voters[0] == null){
data.voters[0] = {};
data.voters[0][req.user.username] = theValue;
data.options[0][theValue] = data.options[0][theValue] + 1;
}
else{
if(data.voters[0][req.user.username] != theValue){
var previous = data.voters[0][req.user.username];
data.voters[0][req.user.username] = theValue;
data.options[0][theValue] = data.options[0][theValue] + 1;
if(previous){
data.options[0][previous] = data.options[0][previous] - 1;
}
}
}
}
console.log(data.voters)
data.save(function(err){
if(!err){
console.log('saved');
}
else{
console.log('error');
}
});
res.send("Your input has been submitted.");
});
});
I also put console.log(data that I've changed) right before the (data that I've changed).save(function( ...)) code.
What can I do to fix this?
EDIT (HOW I SOLVED THIS):
It appears that Mongo does not save my array when I access the array and modify them like:
data.voters[0][username] = value;
Instead I resorted to popping out the object, modifying it, and then pushing it back in. Now I see the values being properly saved/updated in the database.
Aka something like:
var obj = data.voters.pop();
obj[username] = value;
data.voters.push(obj);
Anyone know why this happens?
Im trying to get the rowid from the database where there is someone with the same username from the guy who just wrote a message. The code works when I change
WHERE creator` =${member.username} to WHERE matchid =` ${matchid}.
It gets me the rowid from that match. But I want to get the rowids from where the user is the creator. (I checked my db and on the creator column there is the name of the username Boanak). The error that im getting is this: { Error: SQLITE_ERROR: no such column: Boanak errno: 1, code: 'SQLITE_ERROR' }.
My code:
var getMatchid = function(client, message, callback) {
//let matchid = parseInt(args.join(' '));
let member= message.member.user;
var db = new sqlite3.Database('Matches');
db.serialize(function() {
db.all(`SELECT rowid
FROM Match
WHERE creator =`+${member.username}, function(err, allRows){
if(err) {
//console.log(err);
callback(err, null);
}
else {
callback(null, allRows);
}
db.close();
});
});
}
getMatchid(client, message, function(err, data){
if (err) {
console.log(err);
}
else if (data && data.length) {
message.channel.send(`Match ${data[0].rowid} found`);
}
else {
message.channel.send("That match ID doesnt exist.");
}
});
You need to encapsulate your variable in a string. You're also using template literals, so you can put the expression directly inside.
`SELECT rowid
FROM Match
WHERE creator = "${member.username}"`
I'm trying to build a custom validator for my express application. Here it is
app.use(validator({
customValidators:{
isAvalible:function(userName){
console.log("userName as param = " + userName)
//if username is not present in database return True else False
var query = user.where({userName:userName})
query.findOne(function(err,user){
if(err){
console.log("error occured in findOne()")
return handleError(err)
}
if(user){
console.log("user = " + user)
if(user == null){
return true
}
else{
return false
}
}
})
console.log("returning")
return true;
}
}
}));
It's functionality is to check if a userName inserted into a registration form is alredy in use by some other user.
Query.findOne() is an async function i belive, thus the above function logs me "userName" and immediatly after "returning". It dosent even enter the findOne()'s callback, thus results are not set properly. How could i fix this behaviour?
So I want to search for items in my database using mongoose .find() function.
In my router I have this code to get certain items from the url.
For example;
mydomainname.com/market?type=1&name=hi&stats=123
...?type=123&name=&...
var type = req.query.type;
var name= req.query.name;
var stats= req.query.stats;
Model.find({type: type, name: name, stats: stats})
.exec(function(err, model){
if(err){
console.log("error")
}else{
res.render('*jade*', {models: JSON.stringify(model)})
}})
This works fine, but when there is no query value in the url(as seen above) the query value will be set to ''. Which then sorts away every item I have on my database because there is none with exmaple name = '';
I have search around but I have not find any help so if any would be able to give me tip I would be grateful!
You could create your find() query object based on the value of the request query parameters. The following example checks for the name field if it has an empty string value, remove the property from the query and then use the final query object as your find() filter:
var q = req.query;
if (q.name === '') {
delete q.name;
}
// carry out further checks
Model.find(q)
.exec(function(err, model){
if(err){
console.log("error");
}else{
res.render('*jade*', {models: JSON.stringify(model)});
}
})
Try this
var q = req.query;
var data ={};
if (q.name !=null) {
data.name = q.name;
}
else if (q.type !=null){
data.type = q.type;
}
else if (q.stats !=null){
data.stats = q.stats;
}
else{
data={};
}
Model.find(data)
.exec(function(err, model){
if(err){
console.log("error");
}else{
res.render('*jade*', {models: JSON.stringify(model)});
}
})