Why this simple passport-local authentication doesn't work? - node.js

This minimalistic implementation of local passport strategy, always redirect me to /failure:
const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
var user = {username:"joe", password:"parmesano", id:34};
console.log(user);
passport.use(new LocalStrategy( (username, password, done) => {
done(null, user);
}));
passport.serializeUser( (user, done) => {
done(null, user.id)
});
passport.deserializeUser( (id, done) => {
done(null, user)
});
const app = express();
app.use(session({ secret: 'jamalaja', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
app.post('/', passport.authenticate('local', { failureRedirect: '/failure', successRedirect: '/success' }));
app.listen(3000);
Should not I be sent to / success?

I get the /success redirect if I add body-parser middleware:
app.use(require('body-parser').urlencoded({ extended: true }));
And test it with the command:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'username=meda&password=ajana' localhost:3000/

Related

req.user undefined in other model

I have 2 modules
users
blogs
i have implemented users for login register with passport authentication . When i try to use current user data(req.user) in blog model it results 'undefined'.
i have share my code below
app.js
const express = require('express');
const app =express();
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended : false }));
app.use(bodyParser.json());
const Users = require("./routes/Users");
const Blogs = require("./routes/Blog");
app.use("/users",Users);
app.use("/blogs",Blogs);
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.listen(3000, function() {
console.log('Server started...');
});
users.js
const passport = require('passport');
const express=require('express');
const users = express.Router();
const models = require('../models');
const User = models.users;
var cookieParser = require('cookie-parser');
const session = require('express-session');
users.use(cookieParser());
users.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
users.use(passport.initialize());
users.use(passport.session());
require('../config/passport.js')(passport, User);
users.post('/register',passport.authenticate('local-register', {
successRedirect: '/users/profile',
failureRedirect: '/users/register'
}
));
users.post('/login',passport.authenticate('local-login', {
session: true,
successRedirect: '/users/profile',
failureRedirect: '/users/profile'
}
));
module.exports =users;
blogs.js
const express = require('express');
const blogs = express.Router();
const blogModel = require('../models/blogs');
blogs.get('/',(req,res) =>{
console.log(req.user) // RESULTS UNDEFINED
res.send('Blog List');
});
passport.js
const bCrypt = require('bcryptjs');
const LocalStrategy = require('passport-local').Strategy;
module.exports = function(passport, user) {
const User = user;
passport.use('local-register', new LocalStrategy( { usernameField: 'email', passwordField: 'password', passReqToCallback: true },
function(req, email, password, done) {
... ....
}
));
passport.use('local-login', new LocalStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: true },
function(req, email, password, done) {
..... .....
}
));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
const User =user;
User.findById(id).then((user) =>{
if (user) {
done(null, user);
} else {
done(user.errors, null);
}
});
});
}
You are initiating passport (which handles req.user) only for Users router, this way only routes starting with /users will actually have access to req.user.
In order to use req.user inside the Blogs module, you need to initiate passport for the entire express app (instead of just the users router).
You would probably want to move the initialization to the app.js file
app.use(bodyParser.urlencoded({extended : false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
I believe your problem is you are using multiple objects/instance of express packages and trying to pass from one to another. It won't work as expected. To make it working you should have multiple routes using the same express instance.

express passport check if user is authenticated

I am using passport to login and display '/home'.The login works and redirects to '/home'.But this end point is not protected and can be accessed by typing in the browser.I tried using req.isAuthenticated() (and went through multiple questions here) to no avail.
Routes//index.js
var express = require('express');
var router = express.Router();
var User = require('../models/user');
var passport = require('passport');
var session = require('express-session');
const LocalStrategy = require('passport-local').Strategy;
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.password != password) {
return done(null, false);
}
return done(null, user);
});
}
));
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/login', function(req, res, next) {
res.render('login');
});
router.post('/login', passport.authenticate('local', { failureRedirect : '/', successRedirect : '/home'}))
router.get('/register', function(req, res, next) {
res.render('register');
});
router.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
router.get('/home', ensureLocalAuthenticated, function(req, res){
res.render('home', { user: req.user });
});
function ensureLocalAuthenticated(req, res, next) {
console.log(req.isAuthenticated());
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
}
module.exports = router;
on my app.js file i have configued passport like this:
//passportconfig
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done){
done(null, user.id)
})
passport.deserializeUser(function(id, done){
User.findById(id, function(err, user){
done(err, user)
})
})
app.use('/', indexRouter);
app.use('/users', usersRouter);
isAuthenticated is always returning false,cant login with that middleware.If i remove it,i can login fine but then the '/home' is accessible by all users
Adding the following lines to app.js worked for me:
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
So passport is configured as follows:
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var mongoose = require('mongoose');
var User = require('./models/user')
const LocalStrategy = require('passport-local').Strategy;
Using them:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'public')));
//passportconfig
app.use(passport.initialize());
app.use(passport.session());
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
//
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});

Passport session not working

I'm trying to build a login system using express and passport.
As far as I know, I can use the req.user to access user id and correctly store their actions and req.isAuthenticated() would be true if Passport is working properly, however it isn't working.
For some reason, req.user is always undefined and req.isAuthenticated() is always false.
This is my app.js ->
const express = require('express');
const http = require('http');
const session = require('express-session');
const bodyParser = require('body-parser');
const passport = require('passport');
const route = require('./controllers/core'); **// CORE.JS**
const app = express();
app.set('view engine', 'ejs');
app.use('/css', express.static('css'));
app.use('/js', express.static('js'));
app.use('/themify', express.static('themify'));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
//cookie: { secure: true }
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());
app.use(route);
//core(app);
app.listen(3000);
And this is my core.js
const router = require('express').Router();
const passport = require('passport');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'pharmate',
dateStrings: 'date'
});
const urlencodedParser = bodyParser.urlencoded({ extended: false });
router.get('/index', function(req,res){
console.log(req.user);
});
router.post('/index', urlencodedParser, function(req,res){
var email = req.body.email;
var pass = req.body.password;
connection.query("SELECT `Pharmacy_ID`, `Email`, `Password` FROM `pharmacy` WHERE Email = ? AND Password = ?", [email, pass], function (error, results, fields) {
if (error) res.send(error);//throw error;
else{
if(results.length>0){
req.login(results[0], function(err){
res.redirect('index');
});
}
else{
res.redirect('login');
}
}
});
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
done(null, user);
});
module.exports = router;
Any help would be appreciated. Thanks in advance.
You should handle the authentication like:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/secret',
failureRedirect: '/login',
})
);
Did you setup the passport local strategy ?

Cannot POST in Express + Passport app

I've read similar questions, but I couldn't find a solution.
In my server.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var passport = require('passport');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var passportHelp = require('./config/passport');
var flash = require('connect-flash');
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('view engine', '.hbs');
app.set('views', path.join(__dirname, './app/views'))
app.use(expressSession({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
passportHelp(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(require('./app/controllers'));
app.listen(3000);
In ./app/controllers
var express = require('express');
var router = express.Router();
router.use(require('./signup'));
module.exports = router;
In ./controllers/signup
var express = require('express');
var passport = require('passport');
var router = express.Router();
router.get('/signup', function(req, res) {
res.render('signup');
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true,
}));
module.exports = router;
Finally, in ./config/passport
var LocalStrategy = require('passport-local').Strategy;
var User = require('../app/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) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
console.log(req.body.username);
console.log(req.body.password); //successfully logs all of these 3
console.log(req.body.email);
process.nextTick(function() {
User.findOne({ 'username' : username }, function(err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
}
else {
var newUser = new User;
//filling new user data here
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
I end up with strange behavior. Sometimes POST has no problem, sometimes I get cannot POST /signup, but the result is still saved into the database.
I've tried switching some lines in server.js file, but without result. As I've read, when I require passport in controller/signup, it should be the same 'passport' object which I 'initialized' in server.js, so I dont end up working with a fresh passport object. Am I right?
In case someone faces the same problem.
The reason I got the error, but the save into the database was successful was that I have commented that line: successRedirect

Node PassportJS authentication: req.isAuthenticated() doesn't stay set

Short summary of the problem: I'm using a new version of express (4.9.0) on a Node.js website which has a few public pages and a few private pages, which I'm putting behind a Google OAuth2 login, using PassportJS. When I request a page behind the sign-in, the user keeps being asked to sign-in; req.isAuthenticated() isn't "sticky". I've seen some comments online that there are can be problems with cookie parser versions being incompatible, so that could be the issue here.
Here is my (rather long) app.js:
var express = require('express');
var http = require('http');
var path = require('path');
var passport = require('passport');
var googleStrategy = require('passport-google-oauth').OAuth2Strategy;
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var app = express();
app.use(cookieParser());
app.use(bodyParser());
app.use(session({ secret: 'mysecret' }));
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('port', process.env.PORT || 3000);
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new googleStrategy({
clientID: clientId,
clientSecret: secret,
callbackURL: "http://127.0.0.1:3000/auth/google/callback"
},
function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
return done(null, profile);
});
}
));
app.get('/auth/google',
passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'] }),
function(req, res){
});
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
console.log("successfully authenticated with google");
res.redirect('/');
});
app.get('/login', function(req, res){
res.redirect('/auth/google');
});
app.get('/privatepage', ensureAuthenticated, function(req, res) {
var dostuff = module.listThings(function(rows) {
res.render('somepage.html', {
title : "some page",
data : rows
});
});
});
function ensureAuthenticated(req, res, next) {
console.log("in ensureAuth", req.isAuthenticated());
console.log("session data", req.session);
console.log("user data", req.user);
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
}
var server = app.listen(3000, function() {
var host = server.address().address
var port = server.address().port
console.log('App listening at http://%s:%s', host, port)
})
After the first login, if I visit the /privatepage URL, I get re-directed through Google and land on the homepage again. This is what's in the log from those console.log lines:
in ensureAuth false
session data { cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: {} }
user data undefined
I assume this is some session issue where it doesn't store the user's logged in state, but I'm a node newbie & am a little stuck on how to fix this. I'm running on a single computer, so it's not a multiple machines issue. Any debugging suggestions, or ideas on the conflict causing the logged-in state not to be stored?

Resources