Query not working in Mongodb - node.js

I am using express.js with mongoose for signup. I use crypto for saving the user's password and am now working on the login section. However, when I post values via postman, I am getting the error "not exist" over and over again.
Here is my code:
app.post('/login', (req, res) => {
var User = require('./user.js');
User.findOne({ username: req.body.email }, function(err, user) {
if (err) {
console.log("error");
} else if (!user) {
console.log("not exist");
} else if(!user.validPassword(req.body.password)) {
console.log("not valid");
} else {
console.log("valid");
}
});
res.send("XYZ");
});

Related

Server is not rendering expected page. Can anyone tell what is wrong?

I'm new to programming... I trying to validate login details. But the expected output is not loading(took too much time to respond) below is my code...
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", function (req, res) {
const username = req.body.email;
const password = req.body.Password;
User.findOne({ email: username }, (err, foundUser) => {
if (err) {
console.log(err);
} else {
if (foundUser) {
if (foundUser.password === password) {
res.render("secrets");
}
}
}
});
});
If the login operation is successful the page should go to the secrets page. This is a course tutorial.
You never send a response in case of an error or if no user is found, which will result in a hanging request. You should do something like this:
User.findOne({ email: username }, (err, foundUser) => {
if (err) {
console.log(err);
// redirect to an error page, e.g.
res.render("someErrorPage");
} else {
if (foundUser && foundUser.password === password) {
res.render("secrets");
}else {
res.render("someErrorPage");
}
}
}
}
});

Express routes not sending response Heroku-Postgres code H12

I'm having an issue with my routes not sending responses to the frontend. I only have 3 routes so far, only two send responses, but neither are doing so. I am using node-postgres(pg). My register route seems to be working because when I register a user, it is reflected in the database. Here are the two routes in question.
// login
app.post('/api/v1/login', checkInput, async (req, res, next) => {
console.log(req.body)
try {
// find user
db.query(`SELECT * FROM users WHERE username = $1`, [req.body.username], async (err, user) => {
if (err) throw err;
// user not found
if (!user) {
res.send({message: 'error'});
} else {
// compare passwords
const matchedPassword = await bcrypt.compare(req.body.password, user.password);
// password doesn't match
if (!matchedPassword) {
res.send({message: 'error'});
} else {
// user found
req.session.user = user.username;
req.session.auth = true;
res.send({message: 'success'});
}
}
})
} catch (error) {
next(error);
}
});
// register
app.post('/api/v1/register', checkInput, async (req, res, next) => {
console.log(req.body)
try {
// check if user already exists
db.query(`SELECT username FROM users WHERE username = $1`, [req.body.username], (err, user) => {
if (err || user) {
res.send({message: 'error'});
}
});
// user doesn't exist so create user
// encrypt password
const salt = await bcrypt.genSalt(3);
const hashPassword = await bcrypt.hash(req.body.password, salt);
db.query(`INSERT INTO users (username, password) VALUES ($1, $2)`, [req.body.username, hashPassword], (err, user) => {
if (err) {
res.send({message: 'error'});
} else {
res.send({message: 'success'});
}
});
} catch (error) {
next(error);
}
});
Any help would be appreciated!

Cannot set property 'username' of null

Having an error where a logged in user will try to update their account username but run into an error. For the life of me I cannot figure out why it is sometimes (maybe 1/20 users run into this) unable to find the current user. User's can only access this page if logged in. The errors are:
throw er; // Unhandled 'error' event
TypeError: Cannot set property 'username' of null
The error seems to be happening here: user.username = req.body.username;
router.post("/updateAccount", function (req, res) {
if (req.user) {
User.findOne({username: req.body.currentUser}, function (err, user) {
if (err) {
return done(err);
}
user.username = req.body.username;
user.save(function (err) {
if (err) {
req.flash("error", "It looks like that email address is taken.");
res.redirect('back')
} else {
req.logout();
req.login(user, function (err) {
if (err) console.log('There was an account error' + err)
req.flash("success", "Your account has been created! Your username is " + user.username);
res.redirect('/results')
});
}
});
});
} else {
res.redirect('/results')
}
});
user will be null if no matching user can be found by the User.findOne({username: req.body.currentUser} query (as mentioned in the docs).
So you should add another check if that's the case and handle this appropriately:
User.findOne({username: req.body.currentUser}, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
// handle this case as user.username = req.body.username will fail
}
// ... rest of the code

Node.js - Check if user exists

I'm using NodeJS and passport to let users create an account before they can see results of a quiz they've just taken. My challenge is I need to confirm the username is available before the page refreshes because the user will lose their results if this happens.
Again: I need to verify the username is not taken prior to refreshing.
I think I'm close but it is not working. How would I change my code to handle this challenge?
Currently if the user name is taken it returns an error on trying to create an account and the user ends up on the /failpage as shown below.
app.post('/quiz', usernameToLowerCase, emailToLowerCase, function(req, res) {
User.findOne({
username: req.body.username
}, function(err, user) {
if (err) {
alert(err)
if (user) {
alert('this username is already taken. Please choose another.')
console.log('there was a user');
return false;
}
}
});
var user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
})
user.save(function(err) {
console.log('this is the problem' + ' ' + err)
if (err) {
return res.redirect('/failpage')
}
req.logIn(user, function(err) {
if (err) {
console.log(err);
}
console.log('all looks good')
res.redirect('/results');
});
});
});
Solved it with this if anyone else is trying to do the same thing:
in app.js
app.get('/usercheck', function(req, res) {
User.findOne({username: req.query.username}, function(err, user){
if(err) {
console.log(err);
}
var message;
if(user) {
console.log(user)
message = "user exists";
console.log(message)
} else {
message= "user doesn't exist";
console.log(message)
}
res.json({message: message});
});
});
In js
$('#usercheck').on('change', function() {
$.get('/usercheck?username='+$('#usernameValue').val().toLowerCase(), function(response) {
$('#usernameResponseHidden').text(response.message)
if ($('#usernameResponseHidden').html() === "user exists"){
$('#usernameResponse').text('That username is taken. Please pick another')
}
To solve your problem I think you need to routes. At least a app.get('/quiz') which returns a boolean on if the user exists or not. The section User.findOne can be sent in that route instead. You just need to make a request using ajax when he looses focus of the username field of your form, and display a notification if the name is available or not.

Getting out of sync server response

On a successful signup of a user I am currently seeing a mostly empty page with the text undefined. Redirecting to /app at the top.
UPDATE: I should also mention that after form submittal I am redirected to /users. So on /users I see the text mentioned above.
I think it is because of the req.redirect call being within the user.save callback but I am not sure what the fix is.
I am using mongoose for the ORM.
var User = require('../models/user');
module.exports = function(app) {
app.post('/users', function(req, res, next) {
var user = new User({
email: req.body.email,
password: req.body.password
});
user.save(function(err) {
if (err)
res.send(412, {message: err});
else
req.login(user, function(err) {
if (err !== undefined) return next(err);
res.redirect('/app', {
email: user.email,
id: user._id
});
});
});
});
};
It turns out that the req.login call has to be contained in a password.authenticate callback. The example on the site left that part out.
user.save(function(err) {
if (err)
res.send(412, {message: err});
else
passport.authenticate('local', function(err, user) {
if (err) { return next(err) }
if (!user) { return res.redirect('/login') }
req.login(user, function(err) {
if (err) { return next(err); }
return res.redirect('/app', { email:user.email, id:user._id });
});
})(req, res, next);
});

Resources