Data and salt arguments required error (authorization) - javascript

I'm a beginner in NodeJS and I've tried to make an authentication form using NodeJS + express. I want to make a validation for my password (when "confirmpassword" is different than "password" it should return nothing. Unfortunately, I keep getting "data and salt arguments required". I tried in different ways, to put some conditions, but I keep getting this error. Any ideas how I should make it work?
Here is the file user.js:
const pool = require('./pool');
const bcrypt = require('bcrypt');
function User() {};
User.prototype = {
find : function(user = null, callback)
{
if(user) {
var field = Number.isInteger(user) ? 'id' : 'username';
}
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result) {
if(err)
throw err
if(result.length) {
callback(result[0]);
}else {
callback(null);
}
});
},
create : function(body, callback)
{
var pwd = body.password;
var cpwd = body.confirmpassword;
// here i hash the pass
body.password = bcrypt.hashSync(pwd,10);
body.confirmpassword = bcrypt.hashSync(cpwd, 10);
if (body.password != body.confirmpassword){
callback(null);
}
else {
var bind = [];
for(prop in body){
bind.push(body[prop]);
}
let sql = `INSERT INTO users(username, fullname, password) VALUES (?, ?, ?)`;
pool.query(sql, bind, function(err, result) {
if(err) throw err;
callback(result.insertId);
});
}
},
login : function(username, password, callback)
{
this.find(username, function(user) {
if(user) {
if(bcrypt.compareSync(password, user.password)) {
callback(user);
return;
}
}
callback(null);
});
}
}
module.exports = User;
And the file pages.js:
const express = require('express');
const User = require('../core/user');
const router = express.Router();
const user = new User();
router.get('/', (req, res, next) => {
let user = req.session.user;
if(user) {
res.redirect('/home');
return;
}
res.render('index', {title:"My application"});
})
router.get('/home', (req, res, next) => {
let user = req.session.user;
if(user) {
res.render('home', {opp:req.session.opp, name:user.fullname});
return;
}
res.redirect('/');
});
router.post('/login', (req, res, next) => {
user.login(req.body.username, req.body.password, function(result) {
if(result) {
req.session.user = result;
req.session.opp = 1;
res.redirect('/home');
}else {
res.send('Username/Password incorrect!');
}
})
});
router.post('/register', (req, res, next) => {
let userInput = {
username: req.body.username,
fullname: req.body.fullname,
password: req.body.password
};
user.create(userInput, function(lastId) {
if(lastId) {
user.find(lastId, function(result) {
req.session.user = result;
req.session.opp = 1;
res.redirect('/home');
});
}else {
console.log('Error creating a new user ...');
}
});
});
router.get('/logout', (req, res, next) => {
if(req.session.user) {
req.session.destroy(function() {
res.redirect('/');
});
}
});
module.exports = router;

In userInput, you are not passing confirmpassword property.
let userInput = {
username: req.body.username,
fullname: req.body.fullname,
password: req.body.password
};
In create method, you are accessing it.
var cpwd = body.confirmpassword;
cpwd is null, and that's the reason for the error.
body.confirmpassword = bcrypt.hashSync(cpwd, 10);//**cpwd is null**
As per the docs, data is required argument and this cannot be null.
hashSync(data, salt)
data - [REQUIRED] - the data to be encrypted.
salt - [REQUIRED] - the salt to be used to hash the password.

Related

NodeJS pass Array from MongoDB to EJS file

i'm trying to make an option tag for every item which is in my Array in MongoDB. I have tried some ways but EJS throws me everytime the same error "gate is not defined"..
Here is my function in my route:
router.post('/neueBuchung_spediteur', (req, res) => {
User.findOne({username: req.user}, function (err, user) {
res.render('neueBuchung_spediteur', {
gate: user.gate
});
});
And this is my EJS function:
<select id="torauswahl" name="torauswahl" style="padding:10px;font-size: large; width: 300px">
<% for (var i = 0; i < gate.length; i++){%>
<option value="<%=gate[i]%>"><%=gate[i]%></option>
<%}%>
</select>
thats my full JS file for understanding the logic:
const express = require('express');
const router = express.Router();
// Load Buchung model
const Buchung = require('../DB/models/Buchung');
const User = require('../DB/models/User');
const Tor = require(('../DB/models/Tor'));
const { ensureAuthenticated } = require('../DB/config/auth');
const passport = require('passport');
//Startseite Breuninger
router.get ('/startseite_breuninger', ensureAuthenticated, (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('startseite_breuninger',{
vorname: req.user.vorname,
buchungen: buchungen || []
});
});
});
//startseite Spedi
router.get ('/startseite_spediteur', ensureAuthenticated, (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('startseite_spediteur',{
buchungen: buchungen || []
});
});
});
//Buhchungsübersicht mitarbeiter
router.get('/buchungsuebersicht', (req, res) => res.render('buchungsuebersicht'));
//Buhchungsübersicht spedi
router.get('/neueBuchung_spediteur', (req, res) => res.render('neueBuchung_spediteur'));
//torauswahl spedi
router.get ('/torauswahl', (req, res) => {
Buchung.find(function (err, buchungen) {
if (err)
return res.send(err);
res.render('torauswahl',{
buchungen: buchungen || []
});
});
});
//torverwaltung mitarbeiter
router.get ('/torverwaltung', (req, res) =>{
Tor.find(function (err, tor) {
if (err)
return res.send(err);
res.render('torverwaltung',{
tor: tor || [],
});
});
});
//Update Benutzerdaten Breuni
router.post('/update_detailansicht_breuninger',(req,res) =>{
const username = req.body.username;
const telefon = req.body.telefon;
const email = req.body.email;
User.update({username: username}, telefon);
res.render('detailansicht_breuninger');
});
//insert
//insert
router.post('/neueBuchung_spediteur',ensureAuthenticated,(req, res) => {
const {sendungsstruktur, datepicker, timepicker1, timepicker2, sendungen, EUP, EWP, pakete, bemerkung, teile } = req.body;
var user = req.user;
if (errors.length > 0) {
User.findOne({ username: req.user}, function (err, user) {
console.log(JSON.stringify(req.user));
if (err) { throw err; }
if (user) {
res.render('neueBuchung_spediteur', {
gate: user.gate || []
});
}
});
}
const newBuchung = new Buchung({
sendungsstruktur,
datepicker,
timepicker1,
timepicker2,
sendungen,
EUP,
EWP,
pakete,
bemerkung,
teile
});
newBuchung.save()
.then(buchung =>{
res.send('saved')
})
.catch(err=>console.log(err));
console.log(newBuchung)
});
router.post(
'/login',
passport.authenticate('local', {
failureRedirect: '/login'
}), (req, res) => {
if (req.user.admin == "spediteur") {
res.redirect('/buchungen/startseite_spediteur');
} else {
res.redirect('/buchungen/startseite_breuninger');
}
});
module.exports = router;
Im thankful for any help :)
I think the issue is that req.user is undefined. Can you try logging req.user during your route function?
router.post('/neueBuchung_spediteur', (req, res) => {
User.findOne({username: req.user}, function (err, user) {
console.log(JSON.stringify(req.user))
res.render('neueBuchung_spediteur', {
gate: user.gate
});
});

Update user information

Tried this for updating user information , only phone number but it's not getting update.
router.post('/edit', checkAuth, function (req, res, next) {
console.log(req.userData.userId)
User.update({_id: req.userData.userId}, {$set:req.userData.phoneNo}, function (err){
if (err) {
console.log(err);
}
res.status(200).send(req.userData);
});
});
My user controller const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
And then I am authenticating by passing jwt on this field
phoneNo: user[0].phoneNumber
The auth-token verifies and decode the fields
const token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, process.env.JWT_KEY)
req.userData = decoded;
Update is not working and getting error message Invalid atomic update value for $set. Expected an object, received string .
first of all, you should use PATCH-method - because you are updating only one item in existed object, in body you should send id of user and new value of certain value. If you use mongoose you can try it
User.findOneAndUpdate({ _id: id }, updatedItem, { new: true }, (err, doc) => {
if (err) return res.send(err.message)
if (doc) return res.send(doc);
})
const id = req.body._id;, if you dont use mongoose you should try findAndModify method
Your code
User.update({_id: req.userData.userId}, {$set:req.userData.phoneNo}
Correct code:
User.update({_id: req.userData.userId}, {$set:{phoneNumber:req.userData.phoneNo}}
Try this method:
User.findByIdAndUpdate(req.userData.userId, { $set:{phoneNumber:req.userData.phoneNo}}, { new: true }, function (err, user) {
if (err) console.log(err);
res.send(user);
});

Authentication using Token , passport jwt , Express

I'm working on this little project and i'm having difficulties , Everything works fine in my api except that when i want to authenticate a user using a token , it says "unauthorized". any help would be much appreciated.
this is my passport.js file :
const jwtStrategy = require('passport-jwt').Strategy;
const extractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');
module.exports = function(passport){
let opts = {};
opts.jwtFromRequest =
extractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
passport.use(new jwtStrategy(opts, function(jwt_payload, done)
{
User.getUserById(jwt_payload.data._id, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
And this is my user.js file (i think that the fault is in the getUserById function :
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
//User schema
const userSchema = mongoose.Schema({
name: {
type: String
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true,
}
});
const User = module.exports = mongoose.model('User', userSchema);
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback){
const query = {username: username}
User.findOne(query, callback);
}
module.exports.addUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.password,salt,function(err, hash){
if(err) throw err;
newUser.password= hash;
newUser.save(callback);
});
});
}
module.exports.comparePassword = function (candidatePassword,
hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch);
});
}

Why is my Node.js INSERT giving me a Rethrow non-MySQL errors, Error: ER_PARSE_ERROR: you have an error in your MySQL syntax?

All I'm trying to do is INSERT the values from post into my user table. This has worked before but now I'm getting the error in the title. Any help would be appreciated.
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var empty = require('is-empty');
var Password = require('node-php-password');
router.post('/', function(req, res, next) {
var firstName = req.body.first;
var lastName = req.body.last;
var username = req.body.username;
var password = req.body.password;
var permission = 2;
db.query('SELECT username FROM user WHERE username = ?', [username], function (err, result) {
if (err) throw err;
if (!empty(result)) {
console.log('Taken');
} else {
var hash = Password.hash(password, "PASSWORD_DEFAULT");
var post = {
first: firstName,
last: lastName,
username: username,
password: hash,
permission: permission
};
db.query('INSERT INTO user SET = ?', post, function (err, result) {
if (err) throw err;
console.log('ok');
});
}
res.redirect('/');
});
});
module.exports = router;

NodeJS and Mongodb findOneAndUpdate

I need help to figure this out. The update function is called to reset a password on database. I got this error.
TypeError: Cannot read property 'password' of undefined
module.exports.update = function (token, req, res) {
User.findOneAndUpdate({resetPasswordToken: token, password: req.body.password, resetPasswordExpires: {$gt: Date.now()}}, function(err) {
if (err) throw err;
return res.sendStatus(200);
console.log(User);
});
}
router.post('/forgot', function (req, res) {
var password = req.body.passwordnew;
var password2 = req.body.passwordnew2;
var update = User.update(password, password2, function (err, user) {
//userToken = token;
if (!update) {
console.log("token2 = " + req.params.resetPasswordToken);
req.flash('error', 'Password reset token is invalid or has expired.');
return res.redirect('forgot');
}
else {
user.save(function (err) {
user.password = password;
user.password2 = password2;
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
});
console.log("save new password");
}
});
//}
})
when you use update method of mongoose 1st parameter will be query( by which you can find that doccument in collection) and 2nd will be what you want to update ..
So what query you make is not make sense , it will be like :
var userId=user; //mongoId
var newPassWord=req.body.passwordnew;
User.update({_id:userId}, {password:newPassWord}, callbackFunction);
this will update password of that perticular user.
Thanks

Categories