as a starting copypasteprogrammer I started to add some salting and hashing to my app. The creation of a new User works fine. But the authentication of a user/password in Postman gives me a hard time. I keep getting errors. Now a 500 internal service error. Who can give me a little advice?
Here the schema:
const userSchema = new Schema({
userName: { //email
type: String,
required: true,
unique: true,
trim: true
},
password: {
type: String,
required: true
}
});
// hashing and salting before saving
userSchema.pre('save', function (next) {
let user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
//generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
mongoose.model('User', userSchema);
Here the routes:
const express = require('express');
const router = express.Router();
const ctrlAuthFiles = require('../controllers/authFiles');
router
.route('/login')
.post(ctrlAuthFiles.userLogin);
module.exports = router;
Here the controller:
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const User1 = mongoose.model('User');
//fetch user and test password verification
const userLogin = function (req, res) {
if (req.body) {
User1
.findOne({ userName: req.body.username })
.exec((err, user) => {
if (!user) {
res
.status(404)
.json({
"message": "username or password not found"
});
return;
} else if (err) {
res
.status(404)
.json(err);
return;
}
});
User1.comparePassword(req.body.password, function (err, isMatch) {
if (err) throw err;
console.log(isMatch);
});
User1.methods.comparePassword = function (candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
if (err)
return cb(err);
cb(null, isMatch);
});
}
} else {
res
.status(404)
.json({
"message": "no username or password"
});
}
};
Related
This is the authentication passport code I have put it in passport.js:
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function (user, done) {
done(null, user._id);
});
passport.deserializeUser(function (id, done) {
User.findOne({_id: id}, function (err, user) {
done(err, user);
})
});
passport.use(new LocalStrategy({
usernameField: 'email'
},
function (username, password, done) {
User.findOne({email: username}, function (err, user) {
if (err) return done(err);
if (!user) {
return done(null, false, {
message: 'Incorrect username or password'
});
}
if (!user.validPassword(password)) {
return done(null, false, {
message: 'Incorrect username or password'
});
}
return done(null, user);
})
}
));
And this is the Schema code I am storing password in the form of salt and hash in mongoDB using mongoose queries:
var mongoose = require('mongoose');
var crypto = require('crypto');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
hash: String,
salt: String
});
userSchema.methods.setPassword = function(password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
};
userSchema.methods.validPassword = function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
return this.hash === hash;
};
module.exports = mongoose.model('User', userSchema);
This is the auth.js code for Login route:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var mkdirp = require('mkdirp');
var nodemailer = require('nodemailer');
var config = require('../config');
var transporter = nodemailer.createTransport(config.mailer);
router.route('/login')
.get(function(req, res, next) {
res.render('login', { title: 'Login your account'});
})
.post(passport.authenticate('local', {
failureRedirect: '/login'
}), function (req, res) {
res.redirect('/profile');
})
And below is the password change route I am trying to execute which is possibly not working. What I think is I need to update the hash and salt value into the database while user changes password successfully which I am unable to figure out how can I do it. Please help!!!!!!!!!!!!!!!
router.post('/api/changePassword', function(req,res,next){
req.checkBody('oldPass', 'Empty Password').notEmpty();
req.checkBody('newPass', 'Password do not match').equals(req.body.confirmPass).notEmpty();
var errors = req.validationErrors();
if (errors) {
console.log("Errors hain bhai");
console.log(errors);
res.render('settingsClient', {
oldPass: req.body.oldPass,
newPass: req.body.newPass,
confirmPass:req.body.confirmPass,
errorMessages: errors
});
}
else {
User.findOne({id: req.user.id}, function (err, data) {
console.log("came inside api changePassword else condition inside User.findOne");
if (err) {
console.log(err);
}
else {
data.setPassword(req.body.newPass, function(err,datas){
if(datas) {
data.save(function (err,datass) {
if (err) {
res.render('settingsClient', {errorMessages: err});
} else {
console.log("Hash and Salt saved");
}
});
}
else {
console.log("setPassword error"+ err);
}
});
}
})
}
})
Its not working/not updating the password values into the database. What could be the possible reason and mistake I might be doing?
Yeah! So I removed the callback funtion from the setPassword and tried with the promises way/route to solve this query:
Here I am posting the solution which is working fine now.
User.findOne(userObj).then(function(sanitizedUser) {
if (sanitizedUser) {
console.log("sanitizedUser.hash = "+ sanitizedUser.hash);
sanitizedUser.setPassword(req.body.newPass);
console.log("Password going to be changed successfully now")
sanitizedUser.save(function (err,data) {
if (err) {
res.render('register', {errorMessages: err});
} else {
console.log("Password changed successfully");
res.send('Password reset successful');
}
});
} else {
res.send('user does not exist');
}
}, function(err) {
console.error(err);
});
I've been starting to add user authentication into my app and when adding the login route, i've been getting the error "TypeError: cb is not a function". I know it is coming from my login route as all my other routes work fine.
I have tried researching the issue and trying a few fixes that i've found but none have worked. So i'm starting to believe i've messed up somewhere and I can't find where.
Login Route:
router.post('/login', function (req, res) {
User.findOne({ username: req.body.username }, function (err, user) {
if (err || user == null) {
console.log(err);
res.redirect('/login');
}
if (!user.comparePassword(req.body.password)) {
req.flash('invalidDetails', 'Wrong username or password!');
res.redirect('/login');
} else {
req.session.userId = user._id;
req.flash('loggedIn', 'User ' + req.body.username + ' has been logged in!');
return res.redirect('/');
}
});
});
User Model:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10;
var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
trim: true
},
username: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
required: true
}
});
UserSchema.statics.authenticate = function (email, password, callback) {
User.findOne({ email: email }).exec(function (err, user) {
if (err) {
return callback(err);
} else if (!user) {
var err = new Error('User not found.');
err.status = 401;
return callback(err);
}
bcrypt.compare(password, hash, function (err, result) {
if (result === true) {
return callback(null, user);
} else {
return callback();
}
});
});
};
UserSchema.pre('save', function (next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
var User = mongoose.model('User', UserSchema);
module.exports = User;
I'm expecting it to compare the password with the password that has been entered into the login form with the password that is stored in the database and log in the user if the password is correct or redirect back to the login page with the invalidDetails flash message if the password is incorrect.
But what i'm actually getting is the "TypeError: cb is not a function" error when trying to login.
You are not passing a callback that's why.
If you want a promise based method you can write something like this
AuthSchema.methods.comparePassword = function(candidatePassword) {
const currentPassword = this.password;
return new Promise((resolve, reject) => {
bcrypt.compare(candidatePassword, currentPassword, function(err, isMatch) {
if (err) return reject(err);
resolve(isMatch);
});
})
};
And now you can call that with await
I am trying to build an application using MEAN. On register, everything works fine, user will be introduced into database with the fields password and verify hashed. But on update, the password and verify won't be hashed anymore and they will be added into database as a plain text. How can I resolve this? (I don't have the frontend code yet, I used Postman to send the request)
This is what I have by now:
model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
var schema = new Schema({
firstname: { type: String, required: true },
lastname: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
verify: { type: String, required: true },
});
schema.pre('save', function (next) {
var user = this;
bcrypt.hash(user.password, 10, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
user.verify = hash;
next();
});
});
module.exports = mongoose.model('User', schema);
controller.js
var router = express.Router();
// register user
router.post('/register', function (req, res, next) {
addToDB(req, res);
});
async function addToDB(req, res) {
var user = new User({
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: req.body.password,
verify: req.body.verify
});
try {
doc = await user.save();
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
}
// update user
router.put('/:id', function (req, res, next) {
User.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) {
console.log('Error in user update: ' + JSON.stringify(err, undefined, 2));
return next(err);
}
res.json(post);
});
});
Update your Mongoose middleware to only hash the password if it has been modified (or is new) e.g.
schema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
user.verify = hash
next();
});
});
});
Because findByIdAndUpdate is a wrapper around findOneAndUpdate, better to use save so that the pre save hook is invoked
var _ = require('lodash');
// update user
router.put('/:id', function (req, res, next) {
// fetch user
User.findById(req.params.id, function(err, post) {
if (err) return next(err);
_.assign(post, req.body); // update user
post.save(function(err) {
if (err) return next(err);
return res.json(200, post);
})
});
});
I am trying to learn nodejs. registering api is working in postman but when I try to hit authenticate API, I get this error which in the terminal which says cast to objectId failed for value "john" at path "_id" for model User.
how to get rid of this error
this is my users.js
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) {
User.findById(username, callback);
}
module.exports.addUser = function(newUser, callback) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
})
})
}
module.exports.comparePassword = function(candidatePassport, hash, callback) {
bcrypt.compare(candidatePassport, hash, (err, isMatch)=> {
if (err) throw err;
callback(null, isMatch);
});
}
// router/users.js
this is the authenticate api code which is fetching username and password from req body
router.post('/authenticate', (req,res,next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUserName(username, (err,user)=>{
if(err) throw err;
if(!user) {
return res.json({success: false, msg: 'user not found'});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch) {
// const token = jwt.sign(user, config.secret, {
// expiration: 604800 // 1 week
// });
const token = jwt.sign({data: user}, config.secret, {
expiresIn: 604800
});
res.json({
success: true,
token: 'Bearer ' + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({success: false, msg: 'wrong password'});
}
})
})
})
this is passport.js which is inside config folder
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.fromAuthHeader();
// opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("jwt");
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secret;
passport.use(new JWTStrategy(opts, (jwt_payload, done)=> {
console.log(jwt_payload);
User.getUserById(jwt_payload.data._id,(err,user) => {
if (err) {
return done(err, false);
}
if(user) {
return done(null, user);
} else {
return done(null, false);
}
})
}));
}
//db screenshot
You're calling the wrong method getUserById here:
module.exports.getUserByUserName = function(username, callback) {
User.findById(username, callback);
}
Replace it with:
module.exports.getUserByUserName = function(username, callback) {
User.find({'username': username}, function(err, user) {
if(err) return callback(err);
return callback(null, user);
})
After some help of #veve, I am able to solve the error by this code
module.exports.getUserByUserName = function(username, callback) {
const query = {username: username}
User.findOne(query, callback);
}
I am trying to encrypt password on registration using mongoose and mongodb but pre function is not called at all.
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10;
var patientSchema = new Schema({
username: {type: String, trim: true, index: { unique: true }},
password: {type: String, required: true}
});
//====================== Middleware:Start==========================//
patientSchema.pre('save', function(next) {
console.log('pre called'); //This is not printed at all
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password along with our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
//======================Middleware:End===========================//
//======================API Routes:Start===========================//
router.route('/signup')
.post(function (req, res) {
console.log('post signup called', req.body);
var patients = new Patients({
username: req.body.username,
password: req.body.password
});
Patients.findOne({username: req.body.username}, function (err, user) {
if (err) {
console.log('user not found');
}
if (user) {
console.log("patient already exists");
res.json({message: 'patient already exists'});
} else {
//Saving the model instance to the DB
patients.save(function (err) {
if (err)
throw err;
console.log("user Saved Successfully");
res.json({message: 'user Saved Successfully'});
});
}
});
});
module.exports = router;
//======================API Routes:End===========================//
Inside the pre function, console.log('pre called'); is not printed at all. What am I missing here?
it might be solve your error.
const patients = new Patients({
username: req.body.username,
password: req.body.password
})
if(!patients) return res.json(patients)
patients.save((err,patients) => {
if(err) return res.json({status: 500, message: err})
return res.json({status: 200, user: patients})
})
Thank you.