Passport req.isAuthenticated() doesn't work - node.js

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

Related

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

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

Github oAuth with PassportJS not authenticated

I'm trying to use passportJS to authenticate with the github-strategy. I've previously used passportJS with success, but not with the github-strategy, though I don't figure it should be much different. /viewData is the route in which I'm testing for authentication.
The strategy authenticates successfully and puts the data in the DB and when I serialize and deserialize the user data is in fact there. The problem comes when I try to check in any route after if the req.isAuthenticated() or even if req.session.passport.user exists and it returns false and undefined respectively. The weird thing the same check in app.js after I've redirected through /testAuth the authentication logs correctly with the true and id#. So I feel like its some issue with express-session or the passport integration with that that's breaking it, but I can't find it. I've been on this for a long time so hopefully someone can help me.
app.use(cookieParser('test'));
app.use(session({
secret: 'test',
resave: false,
saveUninitialized: true
}));
//pasport setup
app.use(passport.initialize());
app.use(passport.session());
// Passport init
passport.use(new GithubStrategy({
clientID: config.github.clientID,
clientSecret: config.github.clientSecret,
callbackURL: config.github.callbackURL },
function(accessToken, refreshToken, profile, done) {
User.findOne({ oauthID: profile.id }, function(err, user) {
if(err) {
console.log(err); // handle errors!
}
if (!err && user !== null) {
done(null, user);
} else {
user = new User({
oauthID: profile.id,
name: profile.displayName,
created: Date.now()
});
user.save(function(err) {
if(err) {
console.log(err); // handle errors!
} else {
console.log("saving user ...");
done(null, user);
}
});
}
});
}
));
// test authentication
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
console.log("Not Authenticated", req.user);
res.redirect('/');
}
app.get('/testAuth', ensureAuthenticated, function(req, res){
User.findById(req.session.passport.user, function(err, user) {
if(err) {
console.log(err); // handle errors
} else {
res.redirect('/viewData');
}
});
});
//auth pages
app.get('/auth/github',
passport.authenticate('github'),
function(req, res){});
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/' }),
function(req, res) {
res.redirect('/testAuth');
});
// serialize and deserialize for session
passport.serializeUser(function(user, done) {
console.log('serializeUser: ' + user);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user){
console.log('deserializeUser: ' + user);
if(!err) done(null, user);
else done(err, null);
});
});
So this is a weird one, but I was fixing something else that was weird and in doing so solved this problem. I just moved my
app.use('/', index);
app.use('/viewData', viewData);
To below all the passport code and it works now.

NodeJs Passport Auth

I have a problem with passport.js, when I try to log into my account, I get an error: Error: Unknown authentication strategy "local-login". ". What's wrong with my code, thank you.
config/Passport.js
var passport = require('passport');
var request = require('request');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user'); // model 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('local-login', new LocalStrategy(function(username, password,
done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { msg: "Username" + username + "not found."
});
}
user.comparePassword(password, function(err, isMatch) {
if (err) { return done(err); }
// Make sure the user has been verified
if (isMatch) {
return done(null, user);
}
return done(null, false, { msg: 'Invalid email or password.' });
});
});
}));
app.js
var session = require('express-session');
var passport = require('passport');
app.use(session({
secret: config.secret,
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1*15*1000 }
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
res.locals.user = req.user;
next();
});
routes/authRoutes.js
app.post('/login', function(req, res, next) {
passport.authenticate('local-login', 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); }
res.redirect('/');
});
})(req, res, next);
});
It must be 'local' instead of 'local-login'
module.exports.login_post = passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/',
failureFlash: true
});
I Use MySQL. It's the complete code:
passport.use(new LocalStrategy({
passReqToCallback: true
}, function(req, username, password, done) {
pool.query("SELECT * FROM user WHERE username = ?",[username], function(err, rows, fields) {
if (err) throw err;
console.log('checked');
if(!isExist(username) || !isExist(password)){
return done(null, false, req.flash('message_err', 'Username and password cant be emptied!.'));
}
if (!rows[0]) {
return done(null, false, req.flash('message_err', 'Oops! Username or password didnt match.'));
}
if (!bcrypt.compareSync(password, rows[0].password)) {
return done(null, false, req.flash('message_err', 'Oops! Username/password didnt match.'));
}
return done(null, rows[0]);
});
}));
passport.deserializeUser(function(user, done) {
console.log('user : ' + user);
pool.query("SELECT * FROM user WHERE username = ?", [user], function(err, rows, fields) {
if(err) throw err;
console.log('deserialized');
done(err, rows[0]);
});
});
//serialize and deserialize passport
passport.serializeUser(function(req, user, done) {
console.log('serialized');
done(null, user.username, req.flash('message_success', 'Welcome, '+user.username + "!"));
});
module.exports.login_post = passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/',
failureFlash: true
});

passportjs deserializeUser nothing happen after call

am using nodejs and express with passportJS to auth my users with session (very important to use session in my case)
basically, i have a dashboard and I want to auth each request using isLoggedIn middleware
after the user logged in, the function (deserializeUser) get running and run the findById but nothing happened after that !!!
below my code
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// required for passport
app.use(session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
console.log("serializeUser =>"+user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log("Deaire ==>"+id);
models.User.findById(id, function(err, user) {
if(user)
return done(false,user);
return done(false,false);
});
});
passport.use(new UniqueTokenStrategy({
session: true},
function (token, done) {
models.User.findOne({where: {token: token}}).then(function (user) {
models.userHasRoles.findOne({
where: {
userId: user.id
}
}).then(function (hasRoles) {
if (!hasRoles) {
return done(null, false);
}
return done(null, user);
});
})
}
));
passport.use('local',new LocalStrategy({
usernameField: 'phone_number',
passwordField: 'pin',
session: true,
passReqToCallback : true
},
function(req,phone_number, pin, done) {
console.log("Inside local str");
models.PhoneVerification.findOne({ where: {phoneNumber: phone_number, pinCode:pin}}).then(function (phoneVerification) {
if(phoneVerification==null){
models.configuration.findOne({
where:{name :"default pin"}
}).then(function (configuration) {
if(configuration.detail==pin){
}else {
return done(null, false, {message: "Couldn't login"});
}
})
}
models.User.findOne({where: {phoneNumber: phone_number}}).then(function (user) {
if(user == null){
models.User.create({
phoneNumber: phone_number,
token: randtoken.generate(32)
}).then(function (user) {
return done(null, user);
});
}else {
user.update({token: randtoken.generate(32)}).then(function () {
return done(null, user);
});
}
});
})
}
));
so till now everthing is good , i can check if am not logged in , but if i am really logged in then the code get idle there
here is my middleware to check the session
function isLoggedIn(req, res, next) {
console.log("first auth");
// if user is authenticated in the session, carry on
if (req.isAuthenticated()) {
return next();
}
so when am trying to check iof am logged in or not i get the following from console
Deaire ==>17152 Executing (default): SELECT id, firstName,
lastName, phoneNumber, photo, token, deviceToken, osInfo,
actualLat, actualLng, cityId, countryId, status,
createdAt, updatedAt FROM users AS User WHERE User.id =
17152;

Passport.js positive result

I am attempting to authenticate a user in a Node app using Sequelize and Passport. I am able to hit my database but can't seem to get a positive result. Basically, I have a simple frontend form that accepts a username and password (using the respective names "username" and "password") and then the following Passport definition:
passport.use(new localStrategy(
{usernameField: 'email'},
function(req, email, password, done) {
models.TeacherX.findOne({ email: email }, 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);
});
}
));
Then I call it with:
router.post('/login',
passport.authenticate('local', { failureRedirect: '/login?msg=failure'}),
function(req, res) {
res.redirect("/?msg=positive");
});
Since you are passing the request to the verify callback, you need to set the property passReqToCallback to true or remove the req param from the verify callback. Try this:
passport.use(new localStrategy(
{passReqToCallback: true ,
usernameField: 'email'},
function(req, email, password, done) {
models.TeacherX.findOne({ email: email }, 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);
});
}
));

Resources