Passportjs req.isAuthenticated always shows false - node.js

i am worked nodejs/Angular passport middleware login Authentication working fine but when I try to get login username with the help of req.authentication's not call the passport.deserializeUser function always req.authentication is shown false help how to rectify this problem any ideas.
here i pasted my tried code
Server.js
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
// const logger = require('morgan');
var cookieParser = require('cookie-parser');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const dotenv = require('dotenv');
const path = require('path');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const passport = require('passport');
const expressValidator = require('express-validator');
const http = require('http');
const app = express();
// cros origin handling method start
const cors = require('cors');
dotenv.load({ path: '.env.Config' });
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public"));
app.set('views', __dirname + '\\public');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//mongodb config
mongoose.connect(process.env.MONGODB_URI);
mongoose.connection.on('error', () => {
console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
process.exit();
});
app.use(cookieParser(process.env.SESSION_SECRET));
app.enable('trust proxy'); // add this line
//express session config
app.use(session({
name: 'UpgradeApp.sid',
resave: true,
// saveUninitialized: true,
secret: process.env.SESSION_SECRET,
store: new MongoStore({
url: process.env.MONGODB_URI,
autoReconnect: true
}),
proxy: true, // add this line
saveUninitialized: false,
cookie: {//New
maxAge: 36000000,
httpOnly: false,
secure: false
}
}));
require('./src/SchemaConfig/PassportConfig');
//cors origin config
app.use(cors({
origin: ['http://localhost:4200', 'http://127.0.0.1:4200', 'http://192.168.1.93:4200'],
credentials: true
}));
//bodyparser config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: "200mb" }));
app.use(bodyParser.urlencoded({ limit: "200mb", extended: true, parameterLimit: 200000 }));
app.use(passport.initialize());
app.use(passport.session());
//schema config
const UserConfig = require('./src/SchemaConfig/UserSchema');
function isAuthenticated(req, res, next) {
var ss = req.isAuthenticated();//always show false
if (req.isAuthenticated()) next();
else return res.json('Un-Authenticated');
};
app.get('/logout', isAuthenticated, function (req, res) {
req.logout();
res.json("logout");
});
app.get('/GetUser', isAuthenticated, function (req, res, next) {
return res.json(req.user.UserName);
});
app.post('/login', UserConfig.loginVerify);
app.set('port', process.env.App_PORT || 3000);
app.listen(app.get('port'), () => {
console.log('%s server running on port', chalk.green('✓'), app.get('port'));
console.log(' Press CTRL-C to stop\n');
});
PassportConfig
const User = require('../SchemaConfig/UserSchema');
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt-nodejs');
passport.use('local', new LocalStrategy({
usernameField: 'Email',
passwordField: 'Password'
},
function (Email, Password, done) {
debugger
User.findOne({ Email: Email }, function (err, user) {
debugger
if (err) { return done(err); }
if (!user) {
return done(null, false, {
ErrorMsg: 'Incorrect Email.'
});
}
if (user) {
GlobalUserPwd = user.Password;
}
if (!ComparePassword(Password)) {
return done(null, false, {
ErrorMsg: 'Incorrect password.'
});
}
return done(null, user);
});
}
));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
function ComparePassword(CandidatePassword) {
return bcrypt.compareSync(CandidatePassword, GlobalUserPwd)
};
Userschema
exports.loginVerify = (req, res, next) => {
passport.authenticate('local', function (err, user, info) {
debugger
if (err) { return next(err); }
if (!user) { return res.status(501).json(info); }
req.logIn(user, function (err) {
if (err) { return next(err); }
return res.status(200).json({message:'Login Success'});
});
})(req, res, next);
};

Finally i found a solution for my problem passing login header request with withCredentials:true
const httpOptions = {
observe:'body',
withCredentials:true,
headers:new HttpHeaders().append('Content-Type','application/json')
};

Related

nodejs flash message disappears from request

I am trying to post a flash message after authenticating but for some reason the req.flash() loses its value after a redirect.
The code starts when the user asks for a GET on '/'. Here's the code:
const express = require('express');
const session = require('express-session');
const cookie = require('cookie');
const methodOverride = require('method-override')
const passport = require('passport');
const localStrategy = require ('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const cookieParser = require('cookie-parser');
const flash = require('express-flash');
const fs = require('fs');
const config = require('./config.js');
const db = require('./db.js');
const log = require('./logger.js');
const crypto = require('crypto');
var app = express();
const server = require('http').createServer(app);
const build_version = fs.readFileSync("minorBuild.txt").toString();
process.on('UnhandledPromiseRejectionWarning', function(err) {
log.error({ section: "UnhandledPromiseRejectionWarningr", err: err, uid: '1', orgId: '1' });
});
app.set('port', 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(cookieParser(config.cookieSecret));
app.use(flash());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(session({ name: 'sid',
secret: config.sessionSecret,
cookie: { maxAge: config.sessionCookieMaxAge, domain: 'localhost:3000' },
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('public'));
app.use(methodOverride('_method'))
app.get('/', function(req, res, next) {
if (req.isAuthenticated()) {
res.redirect('/dashboard');
} else {
res.render('index', { messages: req.flash("error") });
})
}
});
Once the user POSTS username and password, the data is sent to this function:
app.post('/login', function(req, res, next){
passport.authenticate('local', function(err, user, info){
var redirectUrl = '/';
if (!user) {
req.flash('error', info.messages);
return res.redirect('/');
}
if (req.session.redirectUrl) {
redirectUrl = req.session.redirectUrl;
req.session.redirectUrl = null;
}
req.logIn(user, function(err){
if (err) {
return next(err);
}
});
res.redirect(redirectUrl);
})(req, res, next);
});
The data is authenticated here and the message is set on incorrect auth:
async function authenticateUser (email, password, done) {
await db.getParticipantByEmail(email)
.then(async (getEmailResult) => {
if (getEmailResult === undefined) {
return done(null, false, { messages: "Incorrect Username and/or Password" });
}
});
}
Using the debugger I see the message come back to /login in the info.messages. In this line in the '/login' function:
if (!user) {
req.flash('error', info.messages); //I see the message show up here
return res.redirect('/');
}
After the redirect to '/' req.flash('error') is empty.
res.render('index', { messages: req.flash("error") }); //req.flash("error") is empty here
I have no idea why this is. What am I missing?

successRedirect is not working in passport login passport-local

I am using node.js express with sequelize and database postgreSql.the problem is in passport login failureRedirect works properly sucessRedirect does not redirect to the page that I want. It still loading and not responding anything and does not come any error.
when I submit login it will check for errors if errors it will work perfectly in failureRedirect but in Success it does not work like page has loading only not goes to the destination page and if I stop the project and restart the project it will be in destination page!! i dont know what is the problem help me.
mainController.js
const express = require("express");
const sessions = require("express-session");
require("../model/MasterUser.model");
const passport = require("passport");
var session = sessions;
const router = express.Router();
router.get("/dashboard", (req, res) => {
res.render('dashboard');
});
router.get("/login", (req, res) => {
res.render("login", { layout: "login.hbs" });
});
router.post(
"/login",
passport.authenticate("local", {
successRedirect: "/main/dashboard",
failureRedirect: "/main/login",
failureFlash: true,
})
);
module.exports = router;
passport.js
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcryptjs");
const sequelize = require("sequelize");
const masterUser = require("../model/MasterUser.model");
module.exports = function (passport) {
passport.use(
new LocalStrategy(
{ usernameField: "user_name" },
(user_name, password, done) => {
// Match user
masterUser.findOne({ where: { user_name: user_name } }).then((user) => {
if (!user) {
return done(null, false, {
message: "This username is not registered",
});
}
// Match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: "Password incorrect" });
}
});
});
}
)
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
masterUser.findByPk(id, (err, user) => {
done(err, user);
});
});
};
index.js
const express = require("express");
const Handlebars = require("handlebars");
var flash = require("connect-flash");
const app = express();
const path = require("path");
const bodyparser = require("body-parser");
const expressHandlebars = require("express-handlebars");
const passport = require("passport");
const sessions = require("express-session");
var session = sessions;
const MainController = require("./controllers/MainController");
const db = require("./config/database");
//test db
db.authenticate()
.then(() => console.log("Database Connected..."))
.catch((err) => console.log("error" + err));
//for security purpose
const cors = require("cors");
app.use(
cors()
);
//Passport Config
require("./config/passport")(passport);
app.use(cookieParser());
//use body parser
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
const {
allowInsecurePrototypeAccess,
} = require("#handlebars/allow-prototype-access");
app.use(
bodyparser.urlencoded({
urlencoded: true,
})
);
app.use(
sessions({
secret: "secret_key",
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 },
})
);
// use flash for show messages
app.use(flash());
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
//flash messages
app.use((req, res, next) => {
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
next();
});
//setting up view Engine
app.set("views", path.join(__dirname, "/views"));
//using the hbs
app.engine(
"hbs",
expressHandlebars({
extname: "hbs",
defaultLayout: "default",
layoutsDir: __dirname + "/views/layouts",
handlebars: allowInsecurePrototypeAccess(Handlebars),
})
);
app.set("view engine", "hbs");
//route for Main
app.use("/main", MainController);
//default
app.get("/", (req, res) => {
res.render("login");
});
app.listen(3000, () => {
console.log("App listening on port 3000!");
});
the problem has been solved guys I made done wrong code in deserializeUser.
passport.js before
passport.deserializeUser((id, done) => {
masterUser.findByPk(id, (err, user) => {
done(err, user);
});
});
};
passport.js after
passport.deserializeUser(function (id, done) {
masterUser.findOne({ where: { id: id } }).then((user) => {
done(null, user);
});
});
the problem is for sequelize get the user data is different so now its worked for me.this is useful for who using express with sequelize and passport with postgresql

Tweet on user profile using Twit package

I am trying to create a tweet to the user profile using twit package. This is the code I am using. By using this code I am able to tweet to my profile because I have access_token and access_token_secret. My question is If I want to tweet to some other people's profile. What is the procedure to do it I am not able to understand? I am using passport library to get the user details.
var Twit = require('twit');
var T = new Twit({
consumer_key: '************',
consumer_secret: '**********',
access_token: '******************',
access_token_secret: '******************',
timeout_ms: 60 * 1000,
strictSSL: true,
})
T.post('statuses/update', {status: 'hello world! '}, function(err, data, response) {
console.log('post on ',data);
})
Below down is my passport authentication code
'use strict';
require('dotenv').config();
const path = require('path');
const express = require('express');
const passport = require('passport');
const { Strategy } = require('passport-twitter');
const { TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, SESSION_SECRET } = process.env;
const port = process.env.PORT || 3000;
const app = express();
const routes = require('./routes');
passport.use(new Strategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: '/return'
},
(token, tokenSecret, profile, cb) => {
console.log(token);
console.log(tokenSecret);
console.log(profile);
return cb(null, profile);
}));
passport.serializeUser((user, cb) => {
cb(null, user);
});
passport.deserializeUser((obj, cb) => {
cb(null, obj);
});
app.set('view engine', 'ejs');
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use(require('express-session')({ secret: SESSION_SECRET, resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.listen(port);
another file
'use strict';
const express = require('express');
const passport = require('passport');
const router = express.Router();
router.get('/', (req, res, next) => {
const { user } = req;
console.log('user details', req.user);
// res.render('home', { user });
});
router.get('/login/twitter', passport.authenticate('twitter'));
router.get('/logout', (req, res, next) => {
req.logout();
res.redirect('/');
});
router.get('/return',
passport.authenticate('twitter', { failureRedirect: '/' }),
(req, res, next) => {
res.redirect('/');
});
module.exports = router;
Got the answer following these steps. https://developer.twitter.com/en/docs/basics/authentication/oauth-1-0a

passport.js session lost after redirect

I am trying to integrate passport into my node.js app.
app.js file
const app = express();
app.set('view engine', 'pug');
app.use('/libs', express.static('node_modules'));
require('../config/auth.config')(app, data, passport);
app.use((req, res, next) => {
res.locals.user = req.user;
next();
});
app.get('/', (req, res) => {
// those objects are populated correctly after redirect from auth middleware
console.log(req.session)
console.log(req.user)
return res.render('home');
});
app.get('/login', console.log(req.user);
// req.user is undefined here
if (req.user) {
return res.redirect('/');
}
return res.render('login'););
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
}));
auth.config.js
const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const LocalStrategy = require('passport-local');
const MongoStore = require('connect-mongo')(session);
const config = require('./config');
const configAuth = (app, {
users
}, passport, db) => {
app.use(cookieParser('Purple Unicorn'));
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(bodyParser.json());
app.use(session({
store: new MongoStore({
url: config.connectionString
}),
secret: 'Purple Unicorn',
resave: true,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy((username, password, done) => {
return users.login(username, password)
.then((user) => {
if (user) {
return done(null, user);
}
return done(null, false);
});
}));
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((id, done) => {
users.getUserById(id)
.then((user) => {
console.log(user);
if (user) {
done(null, user);
}
done(null, false);
});
});
app.use((req, res, next) => {
res.locals = {
user: req.user,
};
next();
});
};
module.exports = configAuth;
The data object is working correctly.
After the post request on /login with correct data, I am redirected to / where console.log(req.user) prints the correct user. It is also added in the req.session object.
After I follow a link to /login, it should redirect me after the check for req.user but returns undefined. Sessions in mongo are stored correctly.
It seems passport is not saving the session correctly.
The problem is in your deserializeUser method where you always run done callback twice. In if statement you should use return done(null, user); to get out from function;

How get passport var on routes with express load

I'm trying to use passport local strategy in my app but the passport variable is undefined on the index.js route. Below is my codes from app.js, passport.js and my index.js route.
Here is my app.js:
var express = require("express");
var path = require('path');
var load = require("express-load");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var expressSession = require("express-session");
var methodOverride = require('method-override');
var passport = require('passport');
var error = require('./middlewares/error');
var app = express();
var server = require('http').Server(app);
global.mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
require('./config/passport')(passport);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cookieParser('talkieparty'));
app.use(expressSession({
resave: false,
saveUninitialized: false,
secret: "149194"
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
load('models').then('controllers').then('routes').into(app, passport);
app.use(error.notFound);
app.use(error.serverError);
var User = app.models.user;
var moment = require('moment');
process.on('message', function(data) {//Executa um função ordenada pelo master.
console.log(process.pid + " executar: " + JSON.stringify(data));
var action = data.action;
switch(action) {
case "confirmation-email-sended":
var email = data.data.email;
User.findOne({email: email}, function(error, user) {
if(error) {
console.log(error);
}else {
if(!user) {
return console.log("No user was found with e-mail like " + email);
}
user.register.notified = true;
user.register.notified_date = new Date(moment().format());
user.save(function(error, user) {
if(error) {
console.log(error);
}else {
console.log("User " + user.email + " received the confirmation e-mail successfully!");
}
});
}
});
break;
default:
console.log("No action was found for " + action);
break;
};
});
server.listen(80, function() {
console.log("Listening!");
});
Here is my passport.js:
var LocalStrategy = require('passport-local').Strategy;
var User = 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) {
done(err, user);
});
});
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, function(req, email, password, done){
User.findOne({'email': email}, function(err, user) {
if(err) return done(err);
if(!user) return done(null, false, null);
if(!user.comparePasswordHashes(data.pass, user.register.password)) return done(null, false, null);
return done(null);
})
}));
}
And here is my index.js route where i'm getting the passport undefined:
module.exports = function(app, passport) {
var indexController = app.controllers.index;
app.get('/', indexController.index);
app.post('/login', indexController.login);
app.post('/register', indexController.register);
app.post('/passport', passport.authenticate('local-login', {
successRedirect: '/logado',
failureRedirect: '/falhou',
failureFlash: false
}));
};

Resources