node.js passport local strategy problems - javascript

I am new to node.js in general and passport in particular.
I have exposed a passport configuration in a file by itself like the following:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/User');
var messages = {
100: 'Username and/or password are not correct.',
101: 'User already exists.'
};
module.exports = function (passport) {
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, req.flash('loginMessage', messages['100']));
}
user.comparePassword(password, function (err, isMatch) {
if (err) {
return done(err);
}
if (isMatch) {
return done(null, user);
} else {
return done(null, false, req.flash('loginMessage', messages['100']));
}
});
});
}));}
in my node routes, i am doing the following to handle the login scenario:
app.post('/login',function(req, res, next){
console.log('loggin in ')
passport.authenticate('local-login', function(err, user, info){
console.log('allo');
console.log(err);
console.log(user);
console.log(info)
});
});
however I am not getting a response; can you please clarify what I am doing wrong.

You need to return the object returned by passport.authenticate
app.post('/login',function(req, res, next){
console.log('loggin in ')
/**/return passport.authenticate('local-login', function(err, user, info){
console.log('allo');
console.log(err);
console.log(user);
console.log(info)
})(req, res, next);
});

Related

In Node+Express+Passport app, res.locals.users works, but data is undefined

I am making an app using NodeJS, Express and Passport, but I am facing a problem with displaying user data in the views.
I get the ObjectID of the user in res.locals.user, but data from it like name, email, etc is returned as "undefined". For example, console.log(res.locals.user) returns "5ef5ddd2e67f9e2918e79bcb" but console.log(res.locals.user.name) or console.log(user.name) returns "undefined".
For clarification:
In the EJS, if I put <%= user %> it shows the object ID of the user from the database. If I put <%= user.name %> it doesn't render and console shows "undefined".
Here is my passport-local-strategy.js:
const express = require('express');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/users');
passport.use(new LocalStrategy({
usernameField: 'email'
},
function (email, password, done) {
User.findOne({ email: email }, function (err, user) {
if (err) {
console.log('Error in finding user --> Passport');
return done(err);
}
if (!user || user.password != password) {
console.log('Invalid username or password');
return done(null, false);
}
return done(null, user);
});
}
));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
if (err) {
console.log('Error in finding user --> Passport');
return done(err);
}
return done(null, user.id);
});
});
passport.checkAuthentication = function (req, res, next) {
if (req.isAuthenticated()) {
return next();
}
return res.redirect('/users/sign-in');
};
passport.setAuthenticatedUser = function (req, res, next) {
if (req.isAuthenticated()) {
res.locals.user = req.user;
console.log(res.locals.user);
}
next();
}
module.exports = passport;
I fixed it by assigning res.locals.user to User.findById with an async and await block.
passport.setAuthenticatedUser = async function (req, res, next) {
if (req.isAuthenticated()) {
res.locals.user = await User.findById(req.user, function (err, user) {
if (err) {
console.log('Error in finding user --> Passport');
}
return;
});
}
next();
}

Nodejs Passport Failure message not working

I have Passport Local working on my app.
Success brings authenticates and failure does not.
However im trying to make it fail better through fail messages and escaping the action.
Tried following the passport documentation.
The error messages are not appearing for some reason, would appreciate some assistance!
here is the local startegy
// Configure the local strategy for use by Passport.
passport.use(new Strategy(
function(username, password, cb) {
db.users.findByUsername(username, function(err, user) {
if (err) { return cb(err); }
if (!user) { return cb(null, false,req.flash('message','Invalid username or password')); }
if (user.password != password) { return cb(null, false,req.flash('message','Invalid username or password')); }
return cb(null, user);
});
}));
The authentication
//Home
app.post('/home.ejs',
passport.authenticate('local'),
function(req, res) {
res.redirect('/');
});
I also have another attempt at authentication if this is more accurate but also had no luck
//Home
app.post('/home.ejs', function( req, res, next) { passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); req.flash('message','Invalid username or password') }
if (!user) { return res.redirect('/'); failureFlash: 'Invalid username or password' }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/');
});
})(req, res, next);
});*/
It should be
passport.use(new LocalStrategy ...
instead of your
passport.use(new Strategy(.....

Why thwos this ERR: Unknown authentication strategy "loca"

When I using passprot.js it throws this Error Unknown authentication strategy "local" !
config/configuration.js
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var User = require('../model/students');
passport.use('local', new LocalStrategy(
function(username, password, done) {
User.findOne({ username: email }, 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);
});
}
));
index.js
router.get('/test', function (req, res, next) {
res.render('test');
});
router.post('/test',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/test',
failureFlash: true })
);
Remove the local from the passport middleware.
Example:
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: email }, 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);
});
}
));
Hope this will solve the issue.

Passport JS auth middleware issue

I am implementing auth using passport js and database is mysql. My successRedirect route is '/main' and in the main route, I have added a middleware (isAuthenticated). But the issue is that, after entering valid credentials, I am not being redirected to '/main', instead, it just timeouts. I tried without adding middleware to '/main' route and it works fine.
var isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
return next;
}
res.redirect("/login")
}
// AUTH Implementation
app.use(session( {
secret: "asdnoifjasofijmaofmjkneknf",
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
passport.use(new localStrategy(
function(username, password, done) {
connection.query("SELECT password FROM user" +
" WHERE email = ?", [username], function (err, results, fields) {
if (err) {
console.log(err);
}
else if (results.length === 0) {
done(null, false);
}
else {
console.log("Results");
console.log(results[0]);
hashedPassword = results[0].password;
bcrypt.compare(password, hashedPassword, function (err, response) {
if (response) {
console.log("True");
return done(null, true);
}
else {
console.log("False");
return done(null, false);
}
})
}
})
}
));
passport.serializeUser(function(ID, done) {
done(null, ID);
});
passport.deserializeUser(function(ID, done) {
connection.query("SELECT * FROM user WHERE userID = ?", [ID], function (err, results, fields) {
if (err) throw err;
else if (results.length === 0) done(null, false);
else {
done(null, results[0]);
}
})
done(null, ID);
});
app.post("/login", passport.authenticate('local', {
successRedirect: "/main",
failureRedirect: "/login"
}))
app.get("/main", isAuthenticated, function(req, res) {
res.send("In the main page");
})
app.post("/login", passport.authenticate('local', {
successRedirect: "/main",
failureRedirect: "/login"
}))
Help me out.
You need execute next function instead of return it.
var isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("/login")
}

NodeJS passport unknown authentication strategy

I am currently working on a node js project with passport authentication.
But i get the following error message:
Error: "Unknown authentication strategy "
Here is my Code:
LocalStrategy = require('passport-local').Strategy;
var UserModel = require('../models/user');
module.exports = function(passport){
passport.serializeUser(function(user, done){
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user){
return done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
passReqToCallback: true
}, function(req, username, password, done){
process.nextTick(function(){
User.findOne({username: username}, function(err, user) {
if(err){
return done(err);
}
if(user){
return done(null, false, req.flash('signUpErr', 'The mail is taken'));
} else {
var newUser = new UserModel();
newUser.name = username;
newUser.password = newUser.generateHash(password);
newUser.save(function(err){
if(err){
throw err;
}
console.log('All Ok');
return done(null, newUser);
})
}
});
});
}));
}
Route:
//Post requests
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/',
failureRedirect : '/signup'
}));
My model:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new mongoose.Schema({
name: String,
password: String
});
UserSchema.method.generateHash = function(password){
return bcrypt.hash(password);
};
module.exports = mongoose.model('UserModel', UserSchema);
I would really need your help, thanks!
Check if you passing the strategy along with the user credentials
var credentials = {
username:"username",
password:"password",
strategy:"local"
};
$http.post('auth/signin', credentials);
Server side
function passportAuthenticate(req, res, next, strategy) {
passport.authenticate(strategy, function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
next(req, res, user);
}
})(req, res, next);
}

Categories

Resources