Node JS Authentications with passport-jwt unauthorized - node.js

Im trying to setup my Node JS API.
I have a User model :
// Dependencies
var restful = require('node-restful');
var mongoose = restful.mongoose;
var bcrypt = require('bcrypt');
// Schema
var userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true},
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required: true},
},
{
timestamps: true
});
// Saves the user's password hashed
userSchema.pre('save', function (next) {
var user = this;
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
} else {
return next();
}
});
// Use bcrypt to compare passwords
userSchema.methods.comparePassword = function(pw, cb) {
bcrypt.compare(pw, this.password, function(err, isMatch) {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
module.exports = restful.model('Users', userSchema);
I want to use passport with jwt for authentication :
// Dependencies
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var config = require('../config/database');
// Load models
var User = require('../models/user');
// Logique d'authentification JWT
module.exports = function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('JWT');
opts.secretOrKey = config.secret;
opts.audience = 'localhost';
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findById(jwt_payload._id, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
Company.findById(jwt_payload._id, function(err, company) {
if (err) {
return done(err, false);
}
if (company) {
done(null, company);
} else {
done(null, false)
}
});
}));
};
And my route for authentication :
// User
router.post('/users/login', (req, res) => {
User.findOne({
email: req.body.email
}, (err, user) => {
if (err) throw err;
if (!user) {
res.json({success: false, message: 'Authentication failed. User not found.'});
} else {
// Check if passwords matches
user.comparePassword(req.body.password, (err, isMatch) => {
if (isMatch && !err) {
// Create token if the password matched and no error was thrown
var token = jwt.sign(user, config.secret, {
expiresIn: 10080 // in seconds
});
res.json({success: true, token: 'JWT ' + token, user: {
id: user._id,
username: user.username,
email: user.email
}});
} else {
res.json({success: false, message: 'Authentication failed. Passwords did not match.'});
}
});
}
});
});
Everything work great on postman.
The token is correctly generated and signed with user's informations.
But i have a problem with the authentication on a protected route :
router.get('/users/profile', passport.authenticate('jwt', { session: false }), function(req, res) {
res.send('It worked! User id is: ' + req.user._id + '.');
});
Everytime, it gives me an "Unauthorized 401" Error.
I really dont know where is the problem, i think the problem is around jwtFromRequest, i also tried with Bearer but it also doesn't work...

I think a good option to avoid this kind of problems is to start from a base project that uses this authentication strategy, and after you have that working, modify it with your functionality.
Here you have an example with jwt authentication strategy and Refresh token implementation: https://solidgeargroup.com/refresh-token-autenticacion-jwt-implementacion-nodejs?lang=es

Related

How can I add the feature of 'Change Password' in nodejs with passport authentication and passport-local package?

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

Express/Passport creating session but not sending cookie to front end

right now I have a react and node.js project running.
Client side(react app) - http://localhost:3000
Server side(Node.js) - http:..localhost:5000
I am currently trying to implement the user authentication session. So far, it will send the username, password, and email(when registering) to the server. The server will then parse the data and attempt to register/login the user. The user credential is stored in an MongoDB atlas database. If it is successful, it will send the info back to the server.
After a successful authentication, the server is supposed to create a session and cookie pair. The session will be stored and the cookie will be sent to the client. However, the latter part isn't happening. I know the session is being created successfully as it is stored in another database in the MongoDB, but no matter what I do, I can't seem to get the cookie to the front end.
UserModel
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const passportLocalMongoose = require('passport-local-mongoose');
const bcrypt = require('bcrypt');
const SALT_WORK_FACTOR = 10;
const userSchema = new mongoose.Schema({
username:{
type: String,
lowercase:true,
unique: true,
required:[true, 'Username is required'],
match:[/^[a-zA-Z0-9]+$/, 'is an invalid username'],
index: true
},
password:{
type: String,
required:[true, 'Password is required']
},
email:{
type:String,
lowercase:true,
unique:true,
required:[true, 'Email is required'],
match:[/\S+#\S+\.\S+/, 'is an invalid email'],
index: true,
uniqueCaseInsensitive: true
}
}, {timestap: true})
userSchema.plugin(uniqueValidator, {message: '{PATH} is already taken.'});
//encrypt the password
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 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
console.log("hashedPassword stored");
user.password = hash;
next();
});
});
});
//validatePassword
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
userSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('users', userSchema, 'userInfo');
authRouter.js
router.post("/register-login",
//this section checks the authentication
(req, res, next) =>{
passport.authenticate('local'
,
{ successRedirect: '/',
failureRedirect: '/listingsForm'
}
,
//this will be called if authenticate was successful
(err, user, info) => {
if(req.body.isSignUp){
if(err){
return res.status(400).json({errors:err});
}
if(!user){
return res.status(400).json({errors:info});
}
else{
return res.status(200).json({success: `created ${user.username}`});
}
}
else{
if(err){
return res.status(400).json({errors:err});
}
if(!user){
return res.status(400).json({errors:info});
}
else{
console.log(user.id);
req.login(user, (err)=>{
if(err){
throw err;
}
});
return res.status(200).json({success:`Welcome back ${user.username}`});
}
}
})(req,res,next)
}
authUser.js
const User = require('../schemes/User')
const passport = require('passport');
const LocalStrategy = require('passport-local');
passport.serializeUser((user,done) =>{
console.log(user.id);
done(null,user.id);
})
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
new LocalStrategy(
{
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
},
(req, username, password, done) =>{
// console.log(username, password);
console.log(req.body);
//For Register
if(req.body.isSignUp){
//determine it is a register attempt
const newUser = new User({
username: username,
password: password,
email: req.body.email
});
newUser.save()
.then(
user => {
return done(null,user);
}
)
.catch(
err => {
console.log('there is error');
console.log(err);
return done(null, false, {message:err.message});
}
)
}
//For Login
else{
User.findOne({username: username})
.then(user => {
let attemptPassword = password;
if(!user){
return done(null, false, {message:'This username/password does not exist'})
}
else{
console.log("will verify now");
user.comparePassword(attemptPassword, function(err, isMatch) {
if (err){
console.log('hihi');
return done(null, false, {message:err})
}
if(!isMatch){
return done(null, false, {message:'This username/password does not exist'})
}
return done(null, user), {message:'Successfully Logged In'};
});
}
})
}
}
));
module.exports = passport;
Index.js
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//expression session
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
store: new MongoStore({mongooseConnection:mongoose.connection})
}))
app.use(passport.initialize());
app.use(passport.session());
//express-router
const authRouter = require('./routes/auth-router');
app.use('/users',authRouter);
server.listen(PORT, () => console.log(`Server has started on port ${PORT}`));
I guess app.use(cors({credentials:true})); will solve your problem, gyus.

how to solve objectId failed for value "john" at path "_id" for model User

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

Why is my sequelize model undefined only when I try to use find functions?

I'm trying to set up a user login and registration with the ORM Sequelize in Node. I have the registration part working fine. My model instance is defined as User, and when I call User.createUser, my model function works and a user is added to the db. However, when I try to use my getUserNameById function in my passport local strategy, I get an error "User is not defined". I've been stuck for over a day trying to figure this out.
Model file (I've imported sequelize, bcrypt, and created a connection)
var Users = connection.define("Users", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING
},
account: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
}, {
timestamps: false
});
Users.sync();
connection.authenticate()
.then(function () {
console.log("CONNECTED! ");
})
.catch(function (err) {
console.log("MYSQL ERROR: FAILED TO CONNECT");
})
.done();
module.exports = function (connection, DataTypes) {
return Users;
}
module.exports.createUser = function (newUser) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
Users.create(newUser).then(function (Users){
console.dir(Users.get());
})
});
});
}
module.exports.getUserByUsername = function (username) {
return Users.find({
where: {username: username}
}).then(function (user) {}, function (err) {
console.log(err);
});
}
module.exports.comparePassword = function(candidatePassword, hash, done, user){
bcrypt.compare(password, hash, function(err, isMatch){
if (err) console.log(err)
if (isMatch) {
return done(null, user)
} else {
return done(null, false)
}
});
}
module.exports.getUserById = function(id, callback){
Users.findAll({
where: {id: id}
});
}
My route code, specifically the local passport strategy I'm having trouble with
var User = require("../models/users");
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function (username, password, done) {
User.getUserByUsername(username, function (user) {
if(!user){
return done(null, false, {message:'Incorrect username'})
}
})
User.comparePassword(password, user.password, function (err, isMatch) {
if(err) throw err;
if(isMatch){
return done(null, user);
}else{
return done(null, false, {message: 'Invalid password'});
}
})
}
));
Your ./models/user class is exporting a function that takes the connection and DataTypes as arguments, but you aren't passing them in - the connection should be passed through. You shouldn't need to call connection.authenticate().
// new db connection
var connection = new Sequelize(
schema,
username,
password,
{
host: host,
dialect: dialect,
}
)
var DataTypes = // define DataTypes
// pass into User
var User = require("../models/users")(connection, DataTypes);

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