change password in nodejs, mongoDB with passport - node.js

I'm using JWT with Passport for authentication in my app, but I don't know how to change the password.
This is my login function:
function login(req, res, next) {
const userObj = {
email: req.body.email,
userType: req.body.userType
};
UserSchema.findOneAsync(userObj, '+password')
.then((user) => {
if (!user) {
const err = new APIError('User not found with the given email id', httpStatus.NOT_FOUND);
return next(err);
} else {
user.comparePassword(req.body.password, (passwordError, isMatch) => {
if (passwordError || !isMatch) {
const err = new APIError('Incorrect password', httpStatus.UNAUTHORIZED);
return next(err);
}
user.loginStatus = true;
user.gpsLoc = [19.02172902354515, 72.85368273308545];
const token = jwt.sign(user, config.jwtSecret);
UserSchema.findOneAndUpdateAsync({ _id: user._id }, { $set: user }, { new: true })
.then((updatedUser) => {
const returnObj = {
success: true,
message: 'user successfully logged in',
data: {
jwtAccessToken: `JWT ${token}`,
user: updatedUser
}
};
res.json(returnObj);
})
.error((err123) => {
const err = new APIError(`error in updating user details while login ${err123}`, httpStatus.INTERNAL_SERVER_ERROR);
next(err);
});
});
}
})
.error((e) => {
const err = new APIError(`erro while finding user ${e}`, httpStatus.INTERNAL_SERVER_ERROR);
next(err);
});
}
my user DB is like this.
import Promise from 'bluebird';
import mongoose from 'mongoose';
import httpStatus from 'http-status';
import APIError from '../helpers/APIError';
import bcrypt from 'bcrypt';
const UserSchema = new mongoose.Schema({
fname: { type: String, default: null },
lname: { type: String, default: null },
email: { type: String, required: true, unique: true },
password: { type: String, required: true, select: false },
});
UserSchema.pre('save', function userSchemaPre(next) {
const user = this;
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (hashErr, hash) => {
if (hashErr) {
return next(hashErr);
}
user.password = hash;
next();
});
});
} else {
return next();
}
});
UserSchema.methods.comparePassword = function comparePassword(pw, cb) {
const that = this;
bcrypt.compare(pw, that.password, (err, isMatch) => {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
I have made another function for reset password and matching checked old password is valid like login function, now I want to update new passport in DB. how will I do that?
Thanks a lot

I'm not sure what you're looking for here, but a changePassword function is just a simple update on UserSchema. Here is a sample:
function changePassword(req, res, next) {
// Init Variables
var passwordDetails = req.body;
if (req.user) {
if (passwordDetails.newPassword) {
UserSchema.findById(req.user.id, function (err, user) {
if (!err && user) {
if (user.authenticate(passwordDetails.currentPassword)) {
if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
user.password = passwordDetails.newPassword;
user.save(function (err) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.send({
message: 'Password changed successfully'
});
}
});
}
});
} else {
res.status(422).send({
message: 'Passwords do not match'
});
}
} else {
res.status(422).send({
message: 'Current password is incorrect'
});
}
} else {
res.status(400).send({
message: 'User is not found'
});
}
});
} else {
res.status(422).send({
message: 'Please provide a new password'
});
}
} else {
res.status(401).send({
message: 'User is not signed in'
});
}
};
Hope this helps!

You dont have to write any methods in schema. You can directly use ChangePassword function with schema like this
user.changePassword(req.body.oldpassword, req.body.newpassword, function(err)
{

Related

keeps getting "Illegal arguments: undefined, string at Object.bcrypt.hashSync"

I've been struggling with Bcrypt on my MERN project I'm trying to create an authentication system I'm trying to run tests on Postman and I'm not sure why do I keep getting the error: "Illegal arguments: undefined, string at Object.bcrypt.hashSync"
this is my postman request:
this is the Controller Code:
const config = require("../config/auth.config");
const db = require("../models");
const User = db.user;
const Role = db.role;
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
exports.signup = (req, res) => {
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
});
user.save((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (req.body.roles) {
Role.find(
{
name: { $in: req.body.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = roles.map((role) => role._id);
user.save((err) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
}
);
} else {
Role.findOne({ name: "user" }, (err, role) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = [role._id];
user.save((err) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({ message: "User was registered successfully!" });
});
});
}
});
};
exports.signin = (req, res) => {
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({ message: "Invalid Password!" });
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
req.session.token = token;
res.status(200).send({
id: user._id,
username: user.username,
email: user.email,
roles: authorities,
});
});
};
exports.signout = async (req, res) => {
try {
req.session = null;
return res.status(200).send({ message: "You've been signed out!" });
} catch (err) {
this.next(err);
}
};
The error message:
Illegal arguments: undefined, string at Object.bcrypt.hashSync wants to say that you're passing undefined as an argument to the hashSync function. We need to fix this error.
Take a closer look at this line where the error occurs:
password: bcrypt.hashSync(req.body.password, 8),
req.body.password is undefined, you can verify it by console.log(req.body.password). What's wrong is that you are sending data as URL parameters. So req.body is an empty object and req.body.password is undefined.
In Postman, select the Body tab, choose JSON format, then type your data as a JSON object. Then, in your code, use express.json() middleware to parse requests in JSON format. You'll have the desired output.
You can see my example request in Postman below:

Am I sending JWT token correctly and is it being received and stored correctly? NodeJS backend & React frontend

I am very new to both nodeJS and React, and am currently trying to get my head around user authentication. I am able to register new users and login to my backend via postman/rapid api, but cannot login correctly via my react front end. Code below:
Front End Requests
import axios from 'axios'
import {AuthModel, UserModel} from './_models'
const API_URL = process.env.REACT_APP_API_URL
export const GET_USER_BY_ACCESSTOKEN_URL = `${API_URL}/auth/signin`
export const LOGIN_URL = `${API_URL}/auth/signin`
export const REGISTER_URL = `${API_URL}/auth/signup`
export const REQUEST_PASSWORD_URL = `${API_URL}/forgot_password`
// Server should return AuthModel
export function login(email: string, password: string) {
return axios.post<AuthModel>(LOGIN_URL, {
email,
password,
})
}
// Server should return AuthModel
export function register(
email: string,
firstname: string,
lastname: string,
password: string,
password_confirmation: string
) {
return axios.post(REGISTER_URL, {
email,
firstname: firstname,
lastname: lastname,
password,
password_confirmation,
})
}
// Server should return object => { result: boolean } (Is Email in DB)
export function requestPassword(email: string) {
return axios.post<{result: boolean}>(REQUEST_PASSWORD_URL, {
email,
})
}
export function getUserByToken(token: string) {
return axios.post<UserModel>(GET_USER_BY_ACCESSTOKEN_URL, {
api_token: token,
})
}
Backend:
const jwt = require("jsonwebtoken");
const config = require("../config/auth.config.js");
const db = require("../models");
const User = db.user;
const Role = db.role;
verifyToken = (req, res, next) => {
let token = req.session.token;
if (!token) {
return res.status(403).send({ message: "No token provided!" });
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "Unauthorized!" });
}
req.userId = decoded.id;
next();
});
};
isAdmin = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "admin") {
next();
return;
}
}
res.status(403).send({ message: "Require Admin Role!" });
return;
}
);
});
};
isModerator = (req, res, next) => {
User.findById(req.userId).exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
Role.find(
{
_id: { $in: user.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "moderator") {
next();
return;
}
}
res.status(403).send({ message: "Require Moderator Role!" });
return;
}
);
});
};
const authJwt = {
verifyToken,
isAdmin,
isModerator,
};
module.exports = authJwt;
const config = require("../config/auth.config");
const db = require("../models");
const User = db.user;
const Role = db.role;
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
exports.signup = (req, res) => {
const user = new User({
username: req.body.email,
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
});
user.save((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (req.body.roles) {
Role.find(
{
name: { $in: req.body.roles },
},
(err, roles) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = roles.map((role) => role._id);
user.save((err,data) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res.send({message: "User registered successfully?"});
});
}
);
} else {
Role.findOne({ name: "user" }, (err, role) => {
if (err) {
res.status(500).send({ message: err });
return;
}
user.roles = [role._id];
user.save((err,data) => {
if (err) {
res.status(500).send({ message: err });
return;
}
var token = jwt.sign({ id: data._id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
// This is what I mean
req.session.token = token;
res.status(200).send({
id: user._id,
username: user.username,
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
});
//res.send({message: "User registered successfully? No 2"});
});
});
}
});
};
exports.signin = (req, res) => {
User.findOne({
username: req.body.email,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({ message: "Invalid Password!" });
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
req.session.token = token;
res.status(200).send({
id: user._id,
username: user.username,
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
roles: authorities,
});
});
};
exports.signout = async (req, res) => {
try {
req.session = null;
return res.status(200).send({ message: "You've been signed out!" });
} catch (err) {
this.next(err);
}
};
exports.allAccess = (req, res) => {
res.status(200).send("Public Content.");
};
exports.userBoard = (req, res) => {
res.status(200).send("User Content.");
};
exports.adminBoard = (req, res) => {
res.status(200).send("Admin Content.");
};
exports.moderatorBoard = (req, res) => {
res.status(200).send("Moderator Content.");
};
Any guidance would be greatly appreciated!

Cannot set headers after they are sent to the client error is showing

Error is showing if a user is already exiting. The error is not showing if the user does not exist in the database
Plz tell me if there is any better way to check the username thank you in advance
exports.updateUser = async(req, res) => {
if (req.body.userId === req.params.id) {
if (req.body.userName || req.body.email) {
await User.findOne({
$or: [{
email: req.body.email
}, {
username: req.body.userName
}]
}).exec((err, user) => {
if (err) {
return res.status(500).json(err);
} else if (user) {
if (user.username === req.body.userName) {
return res.status(400).json({ error: "User Name already exists" });
//err = "User Name already exists";
} else {
return res.status(400).json({ error: "Email already exists" });
}
}
})
}
if (req.body.password) {
const salt = await bcrypt.genSalt(10);
req.body.password = await bcrypt.hash(req.body.password, salt);
}
await User.findByIdAndUpdate(
req.params.id, { $set: req.body }, { new: true }
).exec((err, user) => {
if (err) {
return res.status(500).json(err);
}
if (user) {
return res.status(200).json("User Updated successfully!"); // here error is showing.
}
});
} else {
res.status(401).json("You can update only your account!");
}
};
Don't send response inside exec, because if after sending response it'll execute rest of the code and try to send a response but response is already sent.
exports.updateUser = async (req, res) => {
try {
if (req.body.userId === req.params.id) {
if (req.body.userName || req.body.email) {
await User.findOne({
$or: [
{
email: req.body.email,
},
{
username: req.body.userName,
},
],
}).exec((err, user) => {
if (err) {
throw {
code: 400,
error: err,
};
} else if (user) {
if (user.username === req.body.userName) {
throw {
code: 400,
error: { error: "User Name already exists" },
};
}
throw {
code: 400,
error: "Email already exists",
};
}
});
}
if (req.body.password) {
const salt = await bcrypt.genSalt(10);
req.body.password = await bcrypt.hash(req.body.password, salt);
}
await User.findByIdAndUpdate(
req.params.id,
{ $set: req.body },
{ new: true }
).exec((err, user) => {
if (err) {
throw {
code: 500,
error: err,
};
}
if (user) {
return res.status(200).json("User Updated successfully!"); // here error is showing.
}
});
} else {
throw {
code: 401,
error: "You can update only your account!",
};
}
} catch (e) {
res.status(e.code).json(e.error);
}
};

MongoDB find always returning true when something doesnt exist (even on an empty database)

app.post('/sign-up', function (req, res) {
let emailValid = validator.validate(req.body.email);
let consent = req.body.consent ? true:false
if(emailValid && consent) {
const user = new UserModel({
name: req.body.firstName,
surname: req.body.surname,
email: req.body.email
})
UserModel.find({'email': req.body.email}, function(notFound, found) {
if(notFound) {
user.save().then(item => {
console.log('Saved successfully!');
res.render('submitSuccess', {data: req.body});
}).catch(err => {
res.status(400).render('404');
})
} else if(found) {
console.log('Exists');
res.status(404).render('submitSuccess', {data:req.body});
}
else {
res.status(404).render('404');
}
});
}
});
The intended functionality here is that if someone submits an email to the database that already exists, it does not then save a duplicate. However, it seems that found is returning true everytime, therefore nothing is getting saved.
Run this code:
app.post('/sign-up', function (req, res) {
let emailValid = validator.validate(req.body.email);
let consent = req.body.consent ? true : false
if (emailValid && consent) {
const user = new UserModel({
name: req.body.firstName,
surname: req.body.surname,
email: req.body.email
})
UserModel.find({ 'email': req.body.email }, function (err, found) {
if (err) {
console.error(err);
res.status(500).end();
return;
}
if (found.length == 0) {
user.save().then(item => {
console.log('Saved successfully!');
res.render('submitSuccess', { data: req.body });
}).catch(err => {
res.status(400).render('404');
})
} else {
console.log('Exists');
res.status(404).render('submitSuccess', { data: req.body });
}
});
}
});
What's in the err?

passportjs user object does not return password for compare password

I have an issue that I am not getting an idea that why user stored object does not return password in validatePassword function in model/user.js. I followed all steps described in passportjs official documentation.
I used localstategy of passportjs for signin. When I compare email it always compare but when I tried to execute validate password and use this.password or as a argument it always blank and that is why my password is not compare.
I got all user schema information but I does not get password in user object so I am not able to compare it.
Can anyone tell how could I get out of this issue?
Console Log
root#wk11:/var/www/html/mytripmean/trunk# nodejs server.js
Mytrip is listening on port 1000
MongoDB connection successful
---- User Information ----
myemail#gmail.com
Password##123
{ message: 'Incorrect password.' }
not user:
false
[Error: Illegal arguments: string, undefined]
/var/www/html/mytripmean/trunk/app/data/models/user.js:105
throw err;
^
Error: Illegal arguments: string, undefined
at Error (<anonymous>)
at Object.bcrypt.compare (/var/www/html/mytripmean/trunk/node_modules/bcryptjs/dist/bcrypt.js:250:42)
at model.userSchema.methods.validPassword (/var/www/html/mytripmean/trunk/app/data/models/user.js:102:12)
at Query.<anonymous> (/var/www/html/mytripmean/trunk/app/data/routes/user.js:222:27)
at /var/www/html/mytripmean/trunk/node_modules/kareem/index.js:177:19
at /var/www/html/mytripmean/trunk/node_modules/kareem/index.js:109:16
at process._tickCallback (node.js:448:13)
models/user.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
, randtoken = require('rand-token')
, bcrypt = require("bcryptjs");
var userSchema = new Schema({
// _Id: objectId,
social_id: {
type: String, //(Social id of facebook/twitter)
required: false,
unique: false
},
social_media: {
type: String, //(facebook/twitter)
required: false,
unique: false
},
link_id: {
type: String, //will be dispalying as user reference in url
required: true,
unique: true
},
nick_name: {
type: String, // Unique Nickname for signup
required: true,
unique: true
},
email: {
type: String, // Unqiue Email for signup
required: true,
unique: true
},
password: {
type: String, // Password
required: true,
select: false
},
user_type: {
type: Number, // 1: SuperAdmin, 2: Admin, 3: SiteUser, 4: Restaurant
required: true
}, //reason_to_close: String, // Close Account
is_active: {
type: Number, // -1: pending to activation, 0: inactive, 1: active,
required: true
},
is_close: {
type: Number, // -1: pending to close/Undecided, 0: closed , 1: open/ not close,
required: true
},
is_online: {
type: Number, // 0: Offline, 1: Online
required: true
},
created_at: {
type: Date,
default: Date.now
}, // Registration date
updated_at: {
type: Date, // Registration activation date / user update date
default: Date.now
}
}, {collection: 'user'});
// Password verification
userSchema.methods.validPassword = function (candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
console.log(err);
if (err) {
throw err;
}
callback(null, isMatch);
});
};
var User = module.exports = mongoose.model("User", userSchema);
module.exports.checkEmail = function (callback) {
return this.model('User').count({email: this.email}, callback);
};
module.exports.validateEmailOrNickname = function (username, callback) {
var orCondition = [{nick_name: username}, {email: username}];
//return this.model("user").findOne().or(orCondition);
return this.model("User").find({$or: orCondition}, callback);
};
module.exports.getUserById = function (id) {
User.findById(id, callback);
};
module.exports.createUser = function (user, callback) {
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(user.password, salt, function (err, hash) {
user.password = hash;
user.save(callback);
});
});
};
routes/user.js
var express = require('express');
var router = express.Router();
var bcrypt = require("bcryptjs")
var User = require('../models/user');
var UserProfile = require('../models/userProfile');
var UserSignupToken = require('../models/userSignupToken.js');
var IpLogger = require('../models/ipLogger.js');
var passport = require("passport");
var localStrategy = require("passport-local"), Startegy;
router
.route('/api/user/register')
.post(
function (req, res, next) {
var user_, userData_;
userData_ = {
link_id: req.body.manLinkId,
nick_name: req.body.txtNickname,
email: req.body.txtEmail,
password: req.body.manPassword,
user_type: req.body.manUserType,
is_active: req.body.manIsActive,
is_close: req.body.manIsClose,
is_online: req.body.manIsOnline
};
user_ = new User(userData_);
user_.validate(function (err) {
if (err) {
} else {
//check recaptch is validate or not
var request = require('request');
request
.post({
url: 'http://www.google.com/recaptcha/api/verify',
form: {
privatekey: process.env.RECAPTCHA_PRIVATE_KEY,
remoteip: req.connection.remoteAddress,
challenge: req.body.captcha.challenge,
response: req.body.captcha.response
}
}, function (err, httpResponse, body) {
if (body.match(/false/) === null) {
//Recaptcha validated
User.createUser(user_, function (err, data) {
if (err) {
console.log("stpe 1:");
console.log(err);
res.json({status: 0, message: 'User having an error on stage 1'});
} else {
res.locals.user = data;
//res.json({error:1, message: 'User saved'});
next();
}
});
//res.json({ "captchaError": true });
} else {
res.json({"captchaError": false});
}
});
}
});
},
function (req, res, next) {
var userProfileData_, userProfile_;
userProfileData_ = {
user_id: res.locals.user.id,
link_id: res.locals.user.link_id,
full_name: req.body.txtFullname,
is_active: -1
};
userProfile_ = new UserProfile(userProfileData_);
userProfile_.save(function (err, data) {
if (err) {
console.log("stpe 2:");
console.log(err);
res.json({status: 0, message: 'User having an error on stage 2'});
} else {
//res.json({error:1, message: 'User profile generated'});
next();
}
});
},
function (req, res, next) {
var userSignupTokenData_, userSignupToken_;
userSignupTokenData_ = {
user_id: res.locals.user.id,
link_id: res.locals.user.link_id,
is_active: -1
};
userSignupToken_ = new UserSignupToken(userSignupTokenData_);
userSignupToken_.save(function (err, data) {
if (err) {
console.log("stpe 3:");
console.log(err);
res.json({status: 0, message: 'User having an error on stage 3'});
} else {
//res.json({error:1, message: 'User signup token generated'});
next();
}
});
},
function (req, res, next) {
var ipLoggerData_, ipLogger_, client_IP;
ipLoggerData_ = {
user_id: res.locals.user.id,
link_id: res.locals.user.link_id,
client_ip: req.ip,
activity: "signup"
};
ipLogger_ = new IpLogger(ipLoggerData_);
ipLogger_.save(function (err, data) {
if (err) {
console.log("stpe 4:");
console.log(err);
res.json({status: 0, message: 'User having an error on stage 4'});
} else {
res.json({status: 1, message: 'user saved'});
}
});
}
);
//Check unique validation
router
.route('/api/user/authenticate')
.post(
function (req, res, next) {
console.log("---- User Information ----");
console.log(req.body.txtSigninEmail);
console.log(req.body.txtSigninPassword);
passport.authenticate('local', function (err, user, info) {
console.log(info);
if (err) {
console.log(err);
return next(err);
}
if (!user) {
console.log("not user:");
console.log(user);
return res.status(401).json({
err: info
});
}
req.login(user, function (err) {
if (err) {
return res.status(500).json({
err: 'could not login user'
});
}
res.status(200).json({
status: 'login successful'
});
});
})(req, res, next);
});
router
.route('/api/user/checkEmail')
.post(
function (req, res) {
User.count({email: req.body.txtSigninPassword}, function (err, user) {
if (err) {
// console.log("error false");
res.json(false);
} else {
// console.log("data");
// console.log(user);
res.json({"status": user > 0 ? false : true});
}
});
});
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use('local', new localStrategy(
{
usernameField: 'txtSigninEmail',
passwordField: 'txtSigninPassword'
},
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.'});
}
if (!user.validPassword(password)) {
return done(null, false, {message: 'Incorrect password.'});
}
return done(null, user);
});
}
));
module.exports = router;
After 2 hours of efforts I found answer of my question. In my User model password field, I set property "select:false", due to that I always get a password as blank.
Older:
var userSchema = new Schema({
password: {
type: String, // Password
required: true,
select: false
},
}
After re-setting select: true it works fine.
Updated:
var userSchema = new Schema({
password: {
type: String, // Password
required: true,
select: true
},
}

Resources