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

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");
}
}
}
}
});

Related

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!

I am trying to create a login page for node.js, but I am encountering issues accessing the saved data from the database

Here is the code for creating the user to the database
const User = require('../database/models/User')
module.exports = (req, res) => {
User.create(req.body, (error, user) => {
if (error) {
return res.redirect('/auth/register')
}
res.redirect('/');
})
}
Here is the code for accessing the saved user to enable logging in
const User = require('../database/models/User');
const bcrypt = require('bcrypt');
module.exports = (req, res) => {
const { email, password } = req.body;
User.findOne({ email }, (error, user) => {
if(user) {
bcrypt.compare(password, user.password, (error, same) => {
if(same) {
req.session.userId = user._id
return res.redirect('/')
} else {
console.log('user not found')
res.redirect('/auth/login')
}
})
} else {
return res.redirect('/auth/login')
}
});
}
when I run the app and try to log in I always get an error in finding the user even when I create the user immediately and try logging in
In the Mongo Query Like this
let findQuery ={
email : req.body.email
};
User.findOne(findQuery, (error, user) => {
a change like this you will get a solution.

How to initiate session on signup with cookie-session and passport.js?

I have a /register router for signing up a user. I am using cookie-session (which is similar) instead of express-session for simplicity for now.
I am stuck on the part where I need to authenticate a user on sign up. I am confused about the functionality of req.sessions.save() and req.login(). I know req.login() is provided by passport.js, but I don't understand which one provides the req.session object.
I am new to passport.js and have read numerous articles, videos, and StackOverflow questions extensively to build up my knowledge. Honestly, the passport documentation has been quite a pain so far. I am still confused about how session initiation on signup should work. Many articles skipped the signup part. I thus request help on how to do it.
router.post('/register', (req, res, next) => {
console.log(req.body)
User.findOne({email: req.body.email}).then((currentUser) => {
if(currentUser){ // already exists
res.render('login')
} else { // if not, create user in our db
new User({
email: req.body.email
}).save().then((newUser) => {
passport.authenticate('local')(req, res, () => {
//>>>> //**This is where I don't know what to do**
req.session.save((err) => {
if (err) {
return next(err)
}
res.redirect('http://localhost:3000')
})
})
});
}
});
})
const express = require("express");
const router = express.Router();
const passport = require("passport");
router.post("/register", (req, res, next) => {
User.findOne({ email: req.body.email }).then((currentUser) => {
if (currentUser) { // already exists
res.render('login')
} else { // if not, create user in our db
new User({
email: req.body.email
}).save();
}
});
passport.authenticate("local", function (err, user, info) {
if (err) {
return res.status(400).json({ errors: err });
}
if (!user) {
return res.status(400).json({errors:"No user found."});
// or save User : new User({email: req.body.email}).save();
}
req.login(user, function (err) {
if (err) {
return res.status(400).json({ errors: err });
}
req.session.save((err) => {
if (err) {
return next(err)
}
res.redirect('http://localhost:3000')
});
return res.status(400).json({ success: `logged in ${user.id}` });
});
})(req, res, next);
});
module.exports = router;
passport.authenticate('local')(request, response, () => {
req.session.save((err) => {
if (err) {
return next(err)
}
res.redirect('http://localhost:3000')
})
}

Hashing password before update a user in mongoose

I create the user, hash his password and save on mongo. My problem begins when I try to update that user. For now, when I update the hash isn't generated, cause I really don't know how to do it.
The middleware to get the user that I'm talking about:
exports.userByID = function(req, res, next, id) {
User.findOne(
{
_id: id
},
function(err, user) {
if (err) {
return next(err);
} else {
req.user = user;
next();
}
}
);
};
The user controller, to update an user:
exports.update = async function(req, res, next) {
User.findByIdAndUpdate(req.user.id, req.body, function(err, user) {
if (err) {
return next(err);
} else {
res.json(user);
}
});
};
The pre 'save' on User's model:
UserSchema.pre("save", function(next) {
var user = this;
if (user.password) {
var md5 = crypto.createHash("md5");
user.password = md5.update(user.password).digest("hex");
console.log("Password após o save (hasheando):" + user.password);
}
next();
});
I'm using passport authentication ('local'). Already tried user.save() on the controller update:
user.save();
res.json(user);
But, without success.
This is may be because you are not storing the new_password in the mongo.
In update controller you have to do like this:
User.findByIdAndUpdate(req.user.id, req.body, function (err, user) {
if (err) {
return next(err);
} else {
user.password = req.body.new_password;
user.save(function (err, user) {
if (err) {
res.send("Error: ", err);
} else {
res.send("password updated successfully!");
}
})
}
});
Before saving the password just hash it and update it in DB. it will be something like below.
exports.update = async function(req, res, next) {
let { body} = req;
if(body['password']){
var md5 = crypto.createHash("md5");
body['password']= md5.update(body['password']).digest("hex");
}
let updateUser = await User.findByIdAndUpdate(req.user.id, body)
};

Query not working in Mongodb

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");
});

Resources