How do I use formidable.js with passport authenticate? - javascript

Last time I used passport authenticate for login in the following manner:
router.post('/login', parserUrlEncodedTrue, (request, res, next) => {
console.log('logging in user');
passport.authenticate('local', (err, user, info) => {
var options = "";
if(err){
return next(err);
}
if(!user){
return res.json({
error: true,
message: "User doesn't exist"
});
}
req.logIn(user, function(err) {
if (err){
return next(err);
}
return res.json({
error: false,
message: "Login Success"
});
});
})(req, res, next);
Now I'm trying to use formidable.js and it works fine for registration but can't make it work with login.
let form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
if(err){
helpers.errors(err, res);
} else {
passport.authenticate('local', (err, user, info) => {})(req, res, next);
}
});
passport.authenticate gets to req before it is parsed by formidable. I'm also using express and passport-local-mongoose.

Related

Why isAuthenticated return false in passport.js local strategy after successful login the user

I have the following code to authenticate through the passport-local strategy:
routes.post("/login", passport.authenticate("local"), (req, res) => {
res.json(req.user);
});
function ensureAuth(req, res, next) {
console.log(req.isAuthenticated());
if (req.isAuthenticated()) {
next();
} else {
req.flash("info", "You must be logged in to see this page");
res.redirect("/login");
}
}
routes.get("/edit", ensureAuth, (req, res) => {
res.sendStatus(200);
});
routes.post("/edit", ensureAuth, (req, res, next) => {
req.user.username = req.body.username;
req.user.bio = req.body.bio;
req.user.email = req.body.email;
req.user.save((err) => {
if (err) {
return next(err);
} else {
res.send({
success: "true",
info: "Profile updated",
});
}
});
});
I can't figure out why this is happening? Why won't it authenticate?
I can't see your passport local configuration and I send a sample for local Authentication by passport local I hope help you :)
login route:
router.post('/login', loginController.process);
controller loginController.process :
async process(req, res, next) {
try {
passport.authenticate('local.login', async (err, user) => {
// User not Exist
if (!user) return this.back(req, res);
req.logIn(user, (err) => {
if (req.body.remember) {
user.setRememberToken(res);
}
return res.redirect('/');
});
})(req, res, next);
} catch (e) {
next(e);
}
}
}
passport configuration :
passport.use('local.login', new localStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true,
}, async (req, email: string, password: string, done) => {
// Select User Where email
const user = await userService.findOne({email});
// Check user Exist or Incorrect Password
if (!user || !user.comparePassword(password)) return done(req.flash('global_error', req.__('typeScript.app.passport.passport-local.wrong')), null);
done(null, user);
}));

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(.....

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

node.js passport local strategy problems

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

Categories

Resources