The mysql query always returns undefined and I don't know whats wrongs. It used to work before I added the async await to the functions but that used to return an error in the terminal because bcrypt is an async function. Could someone help me with this? Here is my code
app.post('/login', async function(req, res) {
let username = req.body.username;
let password = req.body.password;
if (username && password) {
connection.query('SELECT username, password, email FROM accounts WHERE username = ?', [username], async function(err, result, fields) {
if (result.length > 0) {
try {
if(await bcrypt.compare(password, result.password)) {
req.session.loggedin = true;
req.session.username = username;
res.redirect('/');
}
else {
res.send('Incorrect Username and/or Password!');
}
}
catch (err) {
//res.status(500).send();
res.send('Something wrong happened');
console.log(err);
}
} else {
res.send('Incorrect Username and/or Password!');
}
res.end();
});
} else {
res.send('Please enter Username and Password!');
res.end();
}
});
Related
I am making a project where I am facing this error. What I wanted to do is that according to the condition it should redirect the server to the particular routes but getting this error.
routes.post("/check", (req, res) => {
console.log("/check");
// console.log(req.body);
username = req.body.username;
password = req.body.password;
console.log("Step 1");
console.log("Username:", username, "\n", "Password", password);
console.log(public);
for (let i in public) {
if (username === i && password === public[i]) {
console.log("Authenticated success");
res.redirect("/public");
} else {
res.redirect("/404");
}
}
res.redirect("/public");
});
Output is
/check
Step 1
Username: shivam2
Password 4321
{ shivam2: '4321', arjun2: 'dcba' }
Authenticated success
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
You should return in case of successful authentication:
routes.post("/check", (req, res) => {
console.log("/check");
// console.log(req.body);
username = req.body.username;
password = req.body.password;
console.log("Step 1");
console.log("Username:", username, "\n", "Password", password);
console.log(public);
for (let i in public) {
if (username === i && password === public[i]) {
console.log("Authenticated success");
return res.redirect("/public");
}
}
res.redirect("/404");
});
You're calling multiple redirects, one in each iteration of the loop, which causes the error. However, you don't need the loop at all - you can examine public[username] directly (logging removed for brevity's sake):
routes.post("/check", (req, res) => {
username = req.body.username;
password = req.body.password;
if (public[username] === password) {
console.log("Authenticated success");
res.redirect("/public");
} else {
res.redirect("/404");
}
});
I'm creating a simple api witch verify if the username and/or password are in the DB and if they are correct.
When I post correct data, it works. When I post a wrong password, it also works. But when I post a wrong username, my condition don't jump to the else. If the username is wrong, it means it is not in the DB. But here, it is like if it was in the DB, but he is not, so I get an error : " TypeError: Cannot read properties of undefined (reading 'Username') "
Here the code
app.post('/login', function(req, res) {
(async () => {
const bcrypt = require('bcrypt')
try {
username = req.query.username
password = req.query.password
let salt = await bcrypt.genSalt(10)
let hash = await bcrypt.hash(password, salt)
db_conn.getConnection( (err, conn) => {
if(err) throw err;
conn.query("SELECT * FROM mod803_appusers WHERE Username=? ", [username], (err, rows) => {
//Problem here : when I put a wrong password, it's ok, this condition works because there is a password, and if bcrypt.compare is true, it sends response, but if it's false, it sends 'Wrong password'.
//But if the Username is Wrong, it means there is no username in the DB. So here, I want this condition jump to the else : 'Incorrect username' but it doesn't.
if(rows[0]['Username'] && rows[0]['Password']) {
bcrypt.compare(password, rows[0]['Password'], function(err, result) {
if(result){
res.send({"table": rows});
} else {
res.send("Wrong password");
}});
} else {
res.send('Incorrect username');
}
})
})
} catch (error) {
console.log(error.message)
}
})()
})
Thanks
why is the console output is always found? any email or passwords i enter, the output is the same, even if they are not in the database
app.post("/login", (req, res) => {
const email = req.body.username
const password = req.body.password
User.find({ email: email, password: password }, function(err, userInfo) {
if (err) {
console.log("err")
} else {
if (userInfo) {
console.log("found")
} else {
console.log("not found")
}
}
});
})
Because User.find will return an array, even if there is no document matching your query it will return an empty array.
And in javascript, if you pass empty array in if the condition it passes
Use User.findOne or check if (userInfo.length > 0)
app.post("/login", (req, res) => {
const email = req.body.username
const password = req.body.password
User.findOne({ email: email, password: password }, function(err, userInfo) {
if (err) {
console.log("err")
} else {
if (userInfo) {
console.log("found")
} else {
console.log("not found")
}
}
});
})
I am trying to create a middleware to allow only admin access to certain routes in my node.js project. My middleware currently looks like this.
function adminAuth(req, res, next){
if(req.user.isAdmin){
return next();
} else {
res.redirect("/");
}
}
The issue is that req.user.isAdmin is never recognized even if the user data contains isAdmin: true. I believe that I need to define user.isAdmin in my passport strategy but I am not sure how to do it. Any help would be greatly appreciated!
here is my local strategy
(async function addUser() {
let client;
try {
client = await MongoClient.connect(url);
const db = client.db(dbName);
const col = db.collection('users');
const user = await col.findOne({ email });
debug('Found user by email');
debug(user);
if (!user) {
req.flash('error', 'The username or password is wrong');
done(null, false);
} else {
const match = await bcrypt.compare(password, user.password);
if (match) {
done(null, user);
} else {
req.flash('error', 'The username or password is wrong');
// we pass null because it did not error, just failed
done(null, false);
}
}
} catch (e) {
debug(e.stack);
}
client.close();
}());
}
));
};
Here is my passport.js
passport.serializeUser((user, done) => {
done(null, user.email);
});
passport.deserializeUser((email, done) => {
done(null, email);
});
};
Using Mongoose as an ODM with NodeJS, but not fully understanding how the error handling works. It works, but doesn't look right, and isn't in line with the documentation, so I'm worried that going down this road will haunt me later on.
For example, here is a basic signin route:
app.post('/signin', function(req, res){
var email = req.body.email;
var password = req.body.password;
mongoose.model('User').findOne({
email: email,
password: password
}, function(err, user){
if (err){
console.log('Database Error')
return res.json({error: 'Database Error'})
} else {
if (!user) {
console.log('User not found.');
return res.json({error: 'Email and/or password incorrect.'})
} else {
console.log('User ' + user.email + ' found. Logging in.');
res.json({
token: jwt.sign({}, 'top-secret', {subject: user}),
data: data[user]
})
}
}
})
})
I'm especially worried about:
if (err) {
//do something
} else {
if (!user){
//do something else
} else {
//log the user in
}
}
Haven't really used Mongo before today, but this feels like a lot of conditional error handling. Is there something that I'm not understanding properly here?
Was going to post as a comment but it was easier to paste this as an answer..
You can simplify the if-else nesting since you are returning at the end of each conditional, like so:
app.post('/signin', function (req, res) {
var email = req.body.email;
var password = req.body.password;
mongoose.model('User').findOne({
email: email,
password: password
}, function (err, user) {
if (err) {
console.log('Database Error');
return res.json({error: 'Database Error'});
}
if (!user) {
console.log('User not found.');
return res.json({error: 'Email and/or password incorrect.'});
}
console.log('User ' + user.email + ' found. Logging in.');
res.json({
token: jwt.sign({}, 'top-secret', {subject: user}),
data: data[user]
});
});
});