How to insert signup data in node js - node.js

exports.signup = function (req, res) {
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
// Init user and add missing fields
var user = new User(req.body);
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;
// Then save the user
user.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
};
I am not understood the meaning of the below 2 lines in my code
1) delete req.body.roles;
2) req.login(user, function (err) {
an any one please give me the valid explanantion

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!

Node JS express JS app User not getting redirected

Whenever I try and redirect the user to the dashboard, the server receives the get request to the dashboard page but the user's page does not get redirected. It remains on the login page, the cookie is received by the user.
This is the login function that sends the session key cookie and the redirection to the dashboard.
app.post('/login', function(req, res){
var email = req.body.email;
var password = req.body.password;
User.findOne({'email' : email}, function(err, user){
if (err)
{
console.log(err);
}
if (user)
{
var hash = user.password;
if (passwordManagement.verifyPassword(password, hash))
{
var newSession = webSession.generateKey(email)
webSession.SessionKeys.push(newSession);
res.cookie('session', newSession.key);
return res.redirect(303, '/dashboard');
}
else
{
res.cookie('session', 'logErr');
return res.redirect(303, '/login');
}
}
else
{
res.cookie('session', 'logErr');
return res.redirect(303, '/login');
}
})
});
This is the dashboard call that should occur when the user is redirected from the login POST method.
app.get('/dashboard', function(req, res){
var sessionKey = req.cookies.session
if (sessionKey != undefined)
{
var email = webSession.findEmailFromSessionKey(sessionKey);
if (email)
{
User.findOne({'email' : email}, function(err, user){
if (err)
{
console.log(err);
}
if (user)
{
fs.readFile(process.cwd() + '/Web Pages/Public/Logged/Dashboard.html', 'utf8', function(err, data){
if (err) {console.log('FS READ Dashboard Error:\n' + err)}
else
{
data = webSession.generateDashboard(user, data);
fs.writeFile('temp.html', data, function(err){
if (err) {console.log('FS WRITE Dashboard Error:\n' + err)}
else
{
console.log('Sending DASHBOARD file');
res.sendFile(process.cwd() + '/temp.html', function(err){
if (err) {console.log('RES Dashboard Error:\n' + err)}
else
{
fs.unlink(process.cwd() + '/temp.html', function(err){
if (err) {console.log('FS UNLINK Dashboard Error:\n' + err)};
});
}
});
}
})
}
});
}
else
{
res.cookie('session', '');
return res.redirect('/login');
}
})
}
else
{
res.cookie('session', '');
return res.redirect('/login');
}
}
else
{
res.cookie('session', '');
return res.redirect('/login');
}
});

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

how to return a value or string from call back function in Nodejs, mongooose

I have a function that is inserting user credentials. I want to return value from a call back function...
var router = require('express').Router();
var User = require('../Models').users;
// function calling here
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body);
res.send(result);
});
module.exports = router;
//implemetation of function
userSchema.statics.signUp = function signUp(obj) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
return user.save(function (err, newuser) {
if (err)
{
return 'Error occured during insertion..';
} else
{
return 'You have sign up successfully...';
}
});
}
I want to return the response as a string but it showing undefined. How should it be done?
var router = require('express').Router();
var User = require('../Models').users;
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body, function(err, result){
if(err){
}
else{
res.send(result)
}
});
});
userSchema.statics.signUp = function signUp(obj, callabck) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
user.save(function (err, newuser) {
if (err)
{
callback( 'Error occured during insertion..');
} else
{
callback(null, newuser);
}
});
}
Use the callback i.e.
var router = require('express').Router();
var User = require('../Models').users;
// function calling here
router.post('/signup', function (req, res)
{
User.signUp(req.body,function(err,result){
res.send(result);
});
});
module.exports = router;
//implemetation of function
userSchema.statics.signUp = function signUp(obj,callback) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
return user.save(function (err, newuser) {
if (err)
{
callback('Error occured during insertion..',null);
} else
{
callback(null,'You have sign up successfully...');
}
});
}
Because of async nature .. Try this:
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body, function(err, result){
if(err){}
else{res.send(result)}
});;
});
userSchema.statics.signUp = function signUp(obj, callabck) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
user.save(function (err, newuser) {
if (err)
{
callback( 'Error occured during insertion..',null);
} else
{
callback (null, 'You have sign up successfully...');
}
});
}

Send variables to layout

I'm learning how to build web applications using Node.js and express, so I'm really noob yet.
So, I have some questions here. I'm building a landing page, and all the informations that I'm getting from my Database (in mysql) will appear in a single page.
I'm sending values from my database, to my layout, built in Jade.
And I created multiple functions to get specific data, here an example:
function getUser(username, userId, callback) {
connection.query('SELECT * FROM users WHERE user_id = ?', userId, function(err, result) {
if (err)
callback(err, null);
else
var callBackString = {};
callBackString.value1 = result[0].user_email;
callBackString.value2 = result[0].user_name;
callback(null, callBackString);
});
}
When the user tries to login I check if the user exists to change the layout and send to the layout some important values:
router.post('/login', function(req, res) {
connection.query('SELECT user_id FROM users WHERE user_email = ? AND user_password = ?', [req.body.login, req.body.password], function(err, results) {
if (err) throw err;
if (results[0]) {
userId = results[0].user_id;
getUser("username", userId, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
res.render('logged_in', {
email: data.value1,
username: data.value2,
});
res.end();
}
});
} else {
res.render('index', {
validation: "failed"
});
}
});
});
I'm only calling one function here (getUser()), and when I call this function, the layout changes, and I send some values.
But now I would like to create a new function called getPosts(), to get informations from a different table, and send it to the layout too, like I did when i called the function getUser()
I tried to do something like this but I had no success, when I call the variables outside the scope I keep getting "undefined".
router.post('/login', function(req, res) {
connection.query('SELECT user_id FROM users WHERE user_email = ? AND user_password = ?', [req.body.login, req.body.password], function(err, results) {
if (err) throw err;
if (results[0]) {
userId = results[0].user_id;
getUser("username", userId, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
email = data.value1;
username = data.value2;
}
});
getPosts("posts", 1, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
postName = data.value1;
postText = data.value2;
}
});
res.render('logged_in', {
email: email,
username: username,
pstname: postName,
psttxt: postText
});
res.end();
} else {
res.render('index', {
validation: "failed"
});
}
});
});
What do I need to change on my code? Thank you.
You should read about asynchronization in node.js so if you change your code as bellow it may work:
router.post('/login', function(req, res) {
connection.query('SELECT user_id FROM users WHERE user_email = ? AND user_password = ?', [req.body.login, req.body.password], function(err, results) {
if (err) throw err;
if (results[0]) {
userId = results[0].user_id;
getUser("username", userId, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
email = data.value1;
username = data.value2;
getPosts("posts", 1, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
postName = data.value1;
postText = data.value2;
res.render('logged_in', {
email: email,
username: username,
pstname: postName,
psttxt: postText
}
});
}
});
} else {
res.render('index', {
validation: "failed"
});
}
});
});

Resources