Cannot read property 'use' of undefined, in the passport .js file - node.js

I created a folder config and i created passport.js file inside it, that holds all the configuration passport module when i tried to run my code i got this error TypeError: Cannot read property 'use' of undefined referring to this line of code passport.use(new LocalStrategy(function(username, password, done) {
passport.js file :
var express = require('express');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../server/model/userModel');
const bcrypt = require('bcrypt');
var passport = require('passport');
module.exports = function(passport) {
// Local Strategy
passport.use(new LocalStrategy(function(username, password, done) {
// Match Username
let query = { username: username };
User.findOne(query, function(err, user) {
/*
if (err) throw err;
if (!user) {
return done(null, false, { message: 'No user found' });
}
*/
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
// Match Password
bcrypt.compare(password, user.password, function(err, isMatch) {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Wrong password' });
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
}

You use two different references for the same name.
var passport = require('passport');
Here, you defined the passport variable.
module.exports = function(passport) {
Here, you define the parameter name as passport. Using passport in this context will refer to the parameter
passport.use(...
Calling on the parameter's use method instead of the passport.use method from the defined variable. Consider changing the function parameter name to something other than passport, maybe _passport?
module.exports = function(passport) {
//to
module.exports = function(_passport) {

Have you initialised:
app.use(passport.initialize());
app.use(passport.session());
To use Passport in an Express or Connect-based application, configure it with the required passport.initialize() middleware. If your application uses persistent login sessions (recommended, but not required), passport.session() middleware must also be used.
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
https://github.com/jaredhanson/passport

Related

Passport req.isAuthenticated() doesn't work

I'm using express-session and passport to authenticate.
Here's my module :
(updated)
passport.use(new LocalStrategy(
function(username, password, done) {
LamAdmin.findOne({ email: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Incorrect username' }); }
if (!comparePassword(user.password, password)) { return done(null, false, { message: 'Incorrect password' }); }
return done(null, user);
});
}
));
router.post('/login', passport.authenticate('local',{
successRedirect: '/p/dashboard',
failureRedirect: '/p',
failureFlash: true
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
LamAdmin.findById(id, function (err, user) {
done(err, user);
});
});
function checkAuth(req,res,next) {
if (req.isAuthenticated()) {
next();
} else {
res.redirect('/p');
}
}
// //DOES NOT WORK WITH CHECKAUTH MIDDLEWARE
// router.get('/dashboard',(req,res,next)=> {
// res.render('dashboard');
// });
router.get('/dashboard',checkAuth,(req,res,next)=> {
res.render('dashboard');
});
checkAuth is my middleware and idk why it always returns false.
This is passport and session configs in app.js :
//sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true,
cookie: { secure: false } // Remember to set this
}));
//passport
app.use(passport.initialize());
app.use(passport.session());
Is there anything wrong with my checkAuth middleware ?
Or my redirect to Dashboard view?
Thanks in advance!
When you call passport.authenticate() method, it uses a strategy to authenticate the user. If you have the user information stored in a local DB, then you can use the Local Strategy that will use username and password to authenticate. So in your app.js add the following:
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
/* Change this to fetch user info from your db
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!comparePasswords(user.password, password)) { return done(null, false); }
return done(null, user);
});
*/
}
));
When the user is authenticated, serializeUser() method is called with the user object returned from the above method passed as an argument and express appends the value returned to the current user session in req.session.passport.user
passport.serializeUser(function(user, done) {
done(null, user.id);
});
On each subsequent request, when isAuthenticated() method is called, passport checks if some value is present in req.session.passport.user. If user information is present, it calls the deserializeUser() method which appends the user information to the request and can be accessed via req.user
passport.deserializeUser(function(id, done) {
// Replace it with your db
User.findById(id, function (err, user) {
done(err, user);
});
});

PassportJS Local Strategy not working Withh MongoDB

I'm trying to get a handle on user authentication with PassportJS, and I cannot get it to work my database setup.
I'm using MongoDB without Mongoose, and I can't get the LocalStrategy module to work.
Hopefully my database queries aren't too cumbersome to read.
Local Strategy:
passport.use(new LocalStrategy(
function(username, password, done) {
//Fire up database
mongo.connect("mongodb://localhost:27017/formulas", function(e, db) {
if (e) {return next(e);}
var col = db.collection("users");
//Do a database query to find a record by username
col.findOne({"username": username}, function(err, user){
if (err) { return done(err);}
if(!user) {
return done(null, false, { message: "Please check your log in credentials." });
}
//if it exists call done() object with user information
bcrypt.compare(password, user.password, function(err, res){
if (err) throw err;
if (res == true) {
return done(null, {username: username, password: password});
} else {
return done(null, false, { message: "Invalid password."});
}
});
});
});
}));
I call passport.authenticate() like this:
router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect:'/about',failureFlash: false}),
function(req, res){
console.log(req.body);
console.log(req.user);
console.log("The user was logged");
});
SerializeUser and deserializeUser look like this:
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(id, done) {
mongo.connect("mongodb://localhost:27017/formulas", function(e, db){
if (e) {return next(e);}
var col = db.collection("users");
col.findOne({"username": id}, function(err, user){
done(err, {"username": id});
});
});
});
When I call app.post(/login) I'm taken directly to /about and nothing is logged to the console so I'm not quite sure what's going wrong.
Advice on what to fix or how to troubleshoot is greatly appreciated.
Firstly when u serialize user object , then in deserialize also whole user object must be passed.
Consider the example below.
For routes :
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
req.session.user = req.user;
return res.redirect('/home');
});
})(req, res, next);
});
For passport.js , place the localstrategy and passport in same folder
var passport = require('passport'),
session = require('express-session');
var local = require('./localstrategy.js');
module.exports = function (app) {
app.use(session({
secret: 'Site visit',
resave: true,
saveUninitialized: true,
cookie: { secure: false }
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done){
done(null, user);
});
passport.deserializeUser(function(user, done){
done(null, user);
});
local();
};
For local strategy :
'use strict';
var passport = require('passport'),
local = require('passport-local').Strategy;
var user;
// path where the db.js is placed
var db = require('./../db.js');
var ObjectId = db.getObjectID();
var bcrypt = require('bcrypt');
module.exports = function(){
passport.use(new local({
usernameField : 'username',
passwordField : 'password'
}, function(username, password, done){
var collection = db.getDb().collection('users');
collection.findOne({
username: username,
}, function (err, result) {
if(result == null){
cb(null, false);
}else {
bcrypt.compare(password, result.password, function (err, passRes) {
if (passRes == true) {
user = user;
done(err, user);
}else{
done(null, false, { message : 'Invalid Password'});
}
});
}
});
}));
};

User Authentication on MEAN stack application

I am building an API using the MEAN stack and am working on the login and signup functions.
And I want to respond with a json string as follows
{
success: 0,
message: ""
}
success:1 for successful login and 0 otherwise.
My authenticate.js is as follows
module.exports = function(passport){
//log in
router.post('/login', passport.authenticate('login', {
//success
//failure
}));
//sign up
router.post('/signup', passport.authenticate('signup', {
//success
//failure
}));
//log out
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
My passport.init.js middleware is as follows
var mongoose = require('mongoose');
var User = mongoose.model('User');
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('deserializing user:',user.username);
done(err, user);
});
});
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
// check in mongo if a user with username exists or not
User.findOne({ 'username' : username },
function(err, user) {
// In case of any error, return using the done method
if (err)
return done(err);
// Username does not exist, log the error and redirect back
if (!user){
console.log('User Not Found with username '+username);
return done(null, false);
}
// User exists but wrong password, log the error
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false); // redirect back to login page
}
// User and password both match, return user from done method
// which will be treated like success
return done(null, user);
}
);
}
));
passport.use('signup', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// find a user in mongo with provided username
User.findOne({ 'username' : username }, function(err, user) {
// In case of any error, return using the done method
if (err){
console.log('Error in SignUp: '+err);
return done(err);
}
// already exists
if (user) {
console.log('User already exists with username: '+username);
return done(null, false);
} else {
// if there is no user, create the user
var newUser = new User();
// set the user's local credentials
newUser.username = username;
newUser.password = createHash(password);
// save the user
newUser.save(function(err) {
if (err){
console.log('Error in Saving user: '+err);
throw err;
}
console.log(newUser.username + ' Registration succesful');
return done(null, newUser);
});
}
});
})
);
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
};
// Generates hash using bCrypt
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};
};
Please help me out in passing the JSON string accordingly
Using Express, all you have to do is to execute res.json inside any controller, passing it any JavaScript object. Express will automatically convert it to JSON and return it to the user.
return res.json({ success: 0, message: '' }

TypeError: user.verifyPassword is not a function

My model looks like this, but when I try use verifyPassword, it says TypeError: user.verifyPassword is not a function
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var User = require('../models/user');
passport.use(new BasicStrategy(
function(username, password, callback) {
User.findOne({ username: username }, function (err, user) {
if (err) { return callback(err); }
// No user found with that username
if (!user) { return callback(null, false); }
// Make sure the password is correct
// Error comind at this point
user.verifyPassword(password, function(err, isMatch) {
if (err) { return callback(err); }
// Password did not match
if (!isMatch) { return callback(null, false); }
// Success scenario
return callback(null, user);
});
});
}
));
Try to use User.verifyPassword function
But for more correct answer show your User model
You should have in your User schema something like:
// I am use bctypt, but you need your comparer function
userSchema.methods.verifyPassword = function(password, callback) {
callback(err, bcrypt.compareSync(password, this.password));
};
I know i am late but you can do something like this,
passport.use(
'local',
new LocalStrategy(function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != password) {
return done(null, false);
}
return done(null, user);
});
})
);
Reference : https://github.com/sikandar114/node-auth-pass-local/blob/master/config/passport.js
Since the data is sent by post method, express is not able to parse data because body-parser middleware has been omitted from express due to some issues. Hence you must add it manually.Import body-parser:
npm install body-parser
Add these lines to your code.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
Also define these 2 functions.
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
Try using passport.use(new LocalStrategy(User.authenticate()));

Failed to serialize user into session when using passport-facebook strategy with passport-local

I am using passport-local and passport-facebook strategies for authentication in sails.js. Authentication with email is working fine. But when user authenticates using facebook, I am getting this error message [Error: Failed to serialize user into session].
Then I tested serializeUser method and it turns out user param is empty in case of facebook. While I also tried to see if verifyHandler is called or not and it is not being called.
Here is my code for the facebook authentication action:
facebook: function (req, res) {
passport.authenticate('facebook', {failureRedirect: '/login', scope: ['email']}, function (err, user) {
if ((err) || (!user)) {
req.session.flash = {
errMsg: 'Email or password mismatch.'
}
return res.redirect('/login');
}
req.logIn(user, function (err) {
if (err) {
console.log(err);
res.view('500');
return;
}
res.redirect('/');
return;
});
})(req, res);
}
And this is the code of passport.js service (api/services/passport.js)
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
FacebookStrategy = require('passport-facebook').Strategy,
bcrypt = require('bcrypt');
var verifyHandler = function (token, tokenSecret, profile, done) {
console.log('in verifyHandler'); // this line is not being executed.
console.log(profile);
process.nextTick(function () {
User.findOne({uid: profile.id}, function (err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, user);
} else {
var data = {
provider: profile.provider,
uid: profile.id,
name: profile.displayName
};
if (profile.emails && profile.emails[0] && profile.emails[0].value) {
data.email = profile.emails[0].value;
}
User.create(data, function (err, user) {
return done(err, user);
});
}
});
});
};
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(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function (email, password, done) {
User.findOne({email: email}).exec(function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {message: 'Unknown user ' + email});
}
bcrypt.compare(password, user.password, function (err, res) {
if (!res) return done(null, false, {message: 'Invalid Password'});
return done(null, user);
});
});
}
));
passport.use(new FacebookStrategy({
clientID: sails.config.facebook.clientID,
clientSecret: sails.config.facebook.clientSecret,
callbackURL: sails.config.facebook.callbackURL
}, verifyHandler));
And finally (config/passport.js)
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
FacebookStrategy = require('passport-facebook').Strategy;
module.exports = {
http: {
customMiddleware: function (app) {
app.use(passport.initialize());
app.use(passport.session());
}
}
};
Any thoughts?
Check if user.id is defined and it is string but not ObjectId().
in
passport.serializeUser(function (user, done) {
done(null, user.id);
});

Resources