Passport authentication won't pass - node.js

I am trying to use passport authentication with a local strategy but the authentication fails every time and doesn't move on to the local strategy.
I have added a couple console logs to see where the code is derailed but nothing at all is logged.
users.js(router)
var express = require('express');
var router = express.Router();
var User = require('../models/user');
var multer=require('multer');
var passport=require('passport');
var LocalStrategy=require('passport-local').Strategy;
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register',{
'title':'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login',{
'title':'Login'
});
});
passport.use(new LocalStrategy(
function(username,password,done){
console.log('words');
User.getUserByUsername(username,function(err,user){
if (err) throw err;
if(!user){
console.log('Unknown user');
return done(null,false);
}
});
}
));
router.post('/login',passport.authenticate('local',{failureRedirect:'/users/register'}),function(req,res){
console.log('Authentication succesful');
req.flash('success','You are logged in');
res.redirect('/');
});
module.exports = router;

Did you set the session and added passport to the router? I don't know if setting the initialize and session method in two different spots will work.
This is how I made it work: All set in in a router
let express = require('express');
let session = require('express-session');
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let router = express.Router();
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, { message: 'Incorrect username.' });
}
user.comparePassword(password, function (err, isMatch) {
if (err) { return done(err); }
if(!isMatch){
return done(null, false, { message: 'Incorrect password.' });
} else {
return done(null, user);
}
});
});
}
));
passport.serializeUser(function(user, done) {
done(null, {email: user.email, roles : user.roles});
});
passport.deserializeUser(function(session, done) {
User.findOne({email: session.email}, function(err, user) {
done(err, user);
});
});
router.use(session({ secret: 'my super secret',name: 'my-id', resave: false, saveUninitialized: false }));
router.use(passport.initialize());
router.use(passport.session());
Furthermore if this ever goes into production you need a different session handler than express-session like MongoStore or Redis
The routes
/* GET home page. */
router.get('/', require('connect-ensure-login').ensureLoggedIn('login'), function (req, res, next) {
if (req.user) {
res.render('index');
} else {
res.redirect('/login');
}
});
router.get('/login', function (req, res, next) {
res.render('login');
});
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}));
router.get('/logout', function (req, res) {
req.logout();
res.render('logout');
});

Related

passport logout() error: Cast to ObjectId failed for value "logout" at path "_id" for model "somemodel(not the user model)"

I'm a hobbyist coder, and I can usually solve errors with lots of searches, but this one I can't get it right.
when I hit my logout route it throws an error: Cast to ObjectId failed for value "logout" at path "_id" for model "Spot"
I tried mongoose version 4.7.2, it's not working. I can't imagine why is it associating my logout route with the spot model at all.
my app.js
var express = require("express"),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
passport = require("passport"),
passportFacebook = require("passport-facebook").Strategy,
User = require("./models/user.js"),
Spot = require("./models/spot.js");
mongoose.connect("mongodb://localhost/biketrialspots", { useNewUrlParser: true });
var app = express();
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static('public'));
app.use(require("express-session")({
secret: "some secret",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
});
passport.use(new passportFacebook({
clientID: "some id",
clientSecret: "some secret",
callbackURL: "somewebsite/auth/facebook/callback",
profileFields: ['id', 'displayName', 'picture.type(large)']
}, function(accessToken, refreshToken, profile, done) {
User.findOrCreate(profile, function(err, user) {
if (err)
{ return done(err); }
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);
});
});
app.get("/", function(req, res){
Spot.find({}, function(err, spots){
if(err){
console.log(err);
} else{
res.render("index", {spots:spots});
}
});
});
app.get("/new", ensureAuthenticated, function(req, res){
res.render("new");
});
app.post("/", function(req, res){
Spot.create(req.body.spot, function(err, result){
if(err){
console.log(err);
} else{
res.redirect("/");
}
});
});
app.get("/:id", function(req, res){
Spot.findById(req.params.id, function(err, spot){
if(err){
console.log(err);
} else{
res.render("spot", {spot: spot});
}
});
});
// Redirect the user to Facebook for authentication. When complete,
// Facebook will redirect the user back to the application at
// /auth/facebook/callback
app.get('/auth/facebook', passport.authenticate('facebook'));
// Facebook will redirect the user to this URL after approval. Finish the
// authentication process by attempting to obtain an access token. If
// access was granted, the user will be logged in. Otherwise,
// authentication has failed.
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/',
failureRedirect: '/login' }));
app.get("/logout", function(req, res){
req.user.logout();
res.redirect('/');
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
return res.redirect('/');
}
app.listen(process.env.PORT, process.env.IP, function(req, res){
console.log("APP HAS STARTED!!!!!");
});
user model
var mongoose = require("mongoose");
var userSchema = new mongoose.Schema({
facebookID:Number,
username:String,
photo:String
});
userSchema.statics.findOrCreate = function findOrCreate(profile, cb){
var userObj = new this();
this.findOne({facebookID : profile.id},function(err,result){
if(!result){
userObj.facebookID = profile.id;
userObj.username = profile.displayName;
userObj.photo = profile.photos[0].value;
userObj.save(cb);
} else{
cb(err,result);
}
});
};
module.exports = mongoose.model("User", userSchema);
Thank you
Because app.get("/:id", ...) is written before app.get("/logout", ...) in your code, I guess the request handler of /:id would be called when you get /logout. Then, req.params.id becomes "logout" and the error is thrown by Spot.findById().
How about trying to write app.get("/logout", ...) before app.get("/:id", ...)?

How to make signup function in nodejs using passportjs?

I am trying to make a signup and signin app in node.js. I am using passport.js for authentication purpose.
My main problem here is whenever i submit my signup form with valid form data, its automatically log user in. Other functions are working properly. Login works perfectly but whenever i submit signup form it submits without any errors and shows successful message too. But main drawback is along with singup it also log user in which i don`t want.
Here is my code
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const validator = require('express-validator');
const passport = require('passport');
const expressHbs = require('express-handlebars');
const flash = require('connect-flash');
const session = require('express-session');
const mongoose = require('mongoose');
const configDB = require('./config/database.js');
//db configuration
mongoose.connect(configDB.url, (err) => {
if(err) {
console.log('Error connecting to databse');
} else {
console.log('Connection Successful');
}
});
require('./config/passport');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'node_modules')));
//required for passport
app.use(session({
secret: 'mysecret',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.locals.login = req.isAuthenticated();
res.locals.session = req.session;
next();
});
app.use('/users', users);
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
passport.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) => {
var fullname = req.body.name;
var address = req.body.address;
req.checkBody('name', 'Name is Required').notEmpty();
req.checkBody('email', 'Invalid email').notEmpty().isEmail();
req.checkBody('password', 'Invalid password').notEmpty().isLength({ min: 4 });
var errors = req.validationErrors();
if (errors) {
var messages = [];
errors.forEach((error) => {
messages.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
User.findOne({ 'email': email }, (err, user) => {
if (err) {
return done(err);
}
if (user) {
return done(null, false, {message: 'That email is already taken.'});
} else {
var newUser = new User();
newUser.fullname = fullname;
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
newUser.address = address;
newUser.isAdmin = false;
//saving the user
newUser.save((err) => {
if (err) {
return done(err);
}
return done(null, newUser, req.flash('info', 'Signup Completed, pleases login to continue'));
});
}
});
}));
passport.use('local-signin', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) =>{
req.checkBody('email', 'Invalid email').notEmpty().isEmail();
req.checkBody('password', 'Invalid password').notEmpty().isLength({ min: 4 });
var errors = req.validationErrors();
if (errors) {
var messages = [];
errors.forEach((error) => {
messages.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
User.findOne({'email': email}, (err, user) => {
if(err) {
return done(err);
}
if(!user) {
return done(null, false, {message: 'No User Found'});
}
if(!user.validPassword(password)) {
return done(null, false, {message: "Wrong Password"});
}
return done(null, user);
});
}));
user.js
var express = require('express');
var router = express.Router();
const passport = require('passport');
const User = require('../models/user');
/* GET users listing. */
router.get('/admin/dashboard', isLoggedIn, isAdmin, (req, res) => {
var user = req.user;
User.find({}, (err, users) => {
if(err) {
throw err;
} else {
res.render('admin/dashboard', {
successMsg: 'Hello' + ' ' + user.fullname,
users: users
});
}
});
});
//router.use('/', notLoggedIn, (req, res, next) => {
// next();
//});
router.get('/login', (req, res) => {
var messages = req.flash('error');
var infoMsg = req.flash('info');
res.render('users/login', { infoMsg: infoMsg, messages: messages, hasErrors: messages.length > 0 });
});
router.post('/login', passport.authenticate('local-signin', {// successRedirect: '/users/profile',
failureRedirect: '/users/login',
failureFlash: true
}), (req, res, next) => {
user = req.user;
role = user.isAdmin;
if(role) {
return res.redirect('/users/admin/dashboard');
} else {
return res.redirect('/users/profile');
}
});
router.get('/signup', (req, res, next) => {
var messages = req.flash('error');
res.render('users/signup', { messages: messages, hasErrors: messages.length > 0 });
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/users/login',
failureRedirect: '/users/signup',
failureFlash: true
}));
router.get('/profile', isLoggedIn, (req, res) => {
var user = req.user;
var role = user.isAdmin;
res.render('users/profile', {
user: user,
role: role,
successMsg: 'Welcome' + ' ' + user.fullname
});
});
router.get('/logout', isLoggedIn, (req, res, next) => {
req.logout();
res.redirect('/users/login');
});
//route middleware to make sure a use is logged in
function isLoggedIn(req, res, next) {
//if user is authenticated in the session, carry on
if(req.isAuthenticated()) {
return next();
}
res.redirect('/users/login');
}
function isAdmin(req, res, next) {
var user = req.user;
if(user.isAdmin == true) {
return next();
}
res.redirect('/users/profile');
}
function notLoggedIn(req, res, next) {
if(!req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
module.exports = router;
You can use session configuration as per passport documentation
.post(passport.authenticate('local-signup', {
successRedirect: '/users/login',
failureRedirect: '/users/signup',
badRequestMessage: "You must fill in all of the form fields.",
failureFlash: true, // allow flash,
session: false // prevent auto-login
})
or you can give a callback to passport call and prevent session storing so it will not perform login
router.post('/signup', function(req, res, next) {
passport.authenticate('local-signup', function(err, user) {
if (err) { return next(err) }
if (!user) { return res.redirect('/users/signup') }
res.redirect('/users/login');
})(req, res, next);
});

How to get the profile of current user in node js

I am using MEAN Stack and mongoose. Using passport for authentication. I want to get the currently logged in user and display his details. For example if I am logged in and if I go to the profile page I want to get my details. There were only few resources on the internet.
Login.js (passport and routes are here)
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var ConnectRoles = require('connect-roles');
router.get('/', function(req, res, next) {
res.render('Login', { title: 'Login' });
});
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("/", new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false,
{ message: "No user has that username!" });
}
user.checkPassword(password, function(err, isMatch) {
if (err) { return done(err); }
if (isMatch) {
return done(null, user);
} else {
return done(null, false,
{ message: "Invalid password." });
}
});
});
}));
router.use(function(req, res, next) {
res.locals.currentUser = req.user;
res.locals.errors = req.flash("error");
res.locals.infos = req.flash("info");
next();
});
router.post("/", passport.authenticate("/", {
successRedirect: "/SubmitSurvey",
failureRedirect: "/",
session: false,
failureFlash: true
}));
router.get("/AdminDatabase", function(req, res) {
res.render('AdminDatabase', { title: 'AdminDatabase' });
});
router.get('/CreateSurvey', function(req, res, next) {
res.render('CreateSurvey', { title: 'CreateSurvey' });
});
router.get('/SubmitSurvey', function(req, res, next) {
res.render('SubmitSurvey', { title: 'SubmitSurvey' });
});
router.get('/profile', function(req, res, next) {
res.render('profile', { title: 'profile' });
});
router.get("/Logout", function(req, res) {
req.logout();
res.redirect("/");
});
module.exports = router;
How can I do this in nodejs
It's on the req.user object
router.get('/profile', function(req, res, next) {
//here it is
var user = req.user;
//you probably also want to pass this to your view
res.render('profile', { title: 'profile', user: user });
});
passport fills the req.user object with the current user through middlewares pipelines so you can extract it from there.
As Alex said, you may explicitly pass some variable (e.g. your req.user) when calling res.render:
router.get('/profile', function(req, res, next) {
res.render('profile', { title: 'profile', user: req.user });
});
Instead, maybe you'd like some variables (like that req.user) to be accessible in all calls to res.render without bothering to specify them every time? In that case, you can use res.locals, e.g. by adding this middleware:
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
And finally, for completeness -- in both of the approaches above, the variable user is available for you in the view. For example, if you're using a pug template, you may now do something like:
if user
p Hello, #{user.id}, good to see you!
else
p Please log in...

Can't send headers after they are sent

I am new to nodejs. I have been trying to create a simple login and register system using mongodb and express. I have created the entire app but with one error:
var express = require('express')
, passport = require('passport')
, util = require('util')
, LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
//var flash = require('connect-flash');
var monk = require('monk');
var db = monk('localhost:27017/loginsystem');
var collection = db.get('messagescollection');
function findById(id, fn) {
var collection = db.get('messagescollection');
collection.findOne({ _id: id }).on('success', function (doc) {
fn(null, doc);
});
}
function findByUsername(username, fn) {
collection.findOne({ username: username }).on('success', function(doc) {
return fn(null, doc);
});
return fn(null, null);
}
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(function(req,res,next){
req.db = db;
next();
});
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat'
hours
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
console.log("user",user);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
console.log(id,"id");
findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
})
}
));
app.use(express.static(__dirname + '/public'));
app.get('/account', ensureAuthenticated, function(req, res){
res.send(req.user);
});
app.get('/login', function(req, res){
res.redirect("/login.html") //redirect back to homepage
});
app.get('/register', function(req, res) {
res.redirect("/register.html") //redirect back to homepage
})
app.post('/login', passport.authenticate('local', { failureRedirect: '/login'}), function(req, res) {
console.log("success",req.user);
res.redirect('/account');
});
app.post('/register', function(req, res) {
console.log(req.body);
// Submit to the DB
collection.insert({
"username" : req.body.username,
"email" : req.body.email,
"password" : req.body.password
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
//res.redirect('/account');
}
});
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.listen(9000);
function ensureAuthenticated(req, res, next) {
console.log("req.user",req.user,req.session);
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
}
When I register, the user is added to the database. And it is redirected to /login but when I login then I get this error:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/response.js:700:10)
at ServerResponse.res.location (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/response.js:814:8)
at ServerResponse.redirect (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/response.js:853:8)
at /home/mareebsiddiqui/SummerOfCode/loginsystem/app.js:130:7
at Layer.handle [as handle_request] (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/router/layer.js:82:5)
at next (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/express/lib/router/route.js:110:13)
at complete (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/passport/lib/middleware/authenticate.js:243:13)
at /home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/passport/lib/middleware/authenticate.js:250:15
at pass (/home/mareebsiddiqui/SummerOfCode/loginsystem/node_modules/passport/lib/authenticator.js:427:14)
How could I resolve this issue? Thanks.
EDIT: I know that there are many questions with the same title but there problems are different. This error is caused by many different situations and my situation is different from others. I have a problem of redirects whereas other questions have problems of ending a response.
You should use return response.<method>. For example, return response.redirect().
Also, response.end() might be helpful.

NodeJS Passport

I setup passport on nodejs and have it working with mongoose for allowing users to login and create new accounts.
app.js:
var express = require('express')
, app = module.exports = express.createServer()
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, routes = require('./routes/index')(app) //index loads in multiple routes
, MongoDBConnection = require('./database/DatabaseConnector').MongoDBConnection;
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'justdoit' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
var mongoDbConnection = new MongoDBConnection();
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
mongoDbConnection.findUserById(id, function(err, user){
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
process.nextTick(function () {
mongoDbConnection.findUser(username, function(err, user) {
//conditions....
});
});
}
));
app.get('/', function(req, res){
res.render('index', { title: "Index", user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { title: "Account", user: req.user });
});
app.get('/login', function(req, res){
res.render('login', { title: "Login", user: req.user, message: req.flash('error') });
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/account',
failureRedirect: '/login',
failureFlash: true })
);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
My problem is the app.js (which is where the passport code is) file is getting a bit large and I tried to move the passport sections into its own script and have the routes outside the app.js and in its own auth.js route file and then reference the routes via the app.js. It works for other routes but for passport related ones such as login it doesnt appear to fire the passport.authenicate() function.
Is there anyway I can put passport routes and functions into its own file and call it/load it from app.js?
auth.js:
module.exports = function(app){
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
mongoDbConnection.findUserById(id, function(err, user){
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
process.nextTick(function () {
mongoDbConnection.findUser(username, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Unknown user ' + username });
}
if (user.password != password) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
});
});
}
));
app.get('/', function(req, res){
res.render('index', { title: "Index", user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
console.log("directing to the account page....");
res.render('account', { title: "Account", user: req.user });
});
app.get('/login', function(req, res){
res.render('login', { title: "Login", user: req.user, message: req.flash('error') });
});
app.post('/login',
passport.authenticate('local', {
successRedirect: '/account',
failureRedirect: '/login',
failureFlash: true })
);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
}
This is what I do. Please comment if you need more help tailoring it to your code.
First Step
Put your passport code in a separate file. e.g. pass.js. (I see you have already done that) Then, in that file, put all the code inside this:
module.exports = function(passport, LocalStrategy){
};
Remember to add to the function input anything else that you are using. In your case, besides passport and LocalStrategy, you will probably need to add mongoDbConnection as an input too.
Second Step
In your app.js, include this line. Just before "app.listen" if possible to ensure that everything has been properly defined/declared/included.
require('./pass.js')(passport, LocalStrategy);
Explanation
The "wrapper" in step one defines the chunk of code you will be including into your app. The "require" in step two is the code that actually includes it. You are basically defining the entire "pass.js" file as a function and passing it the tools it needs to carry out the code (passport, LocalStrategy etc)
In your case, you will probably need to modify my code to:
module.exports = function(passport, LocalStrategy, mongoDbConnection){
};
require('./pass.js')(passport, LocalStrategy, mongoDbConnection);
This should works. I googled about this a while ago and this appears to be the "correct" way to break up your app.js (I say this with great trepidation though :) ). Feel free to comment if you need anymore help.
This github repo also has a good example of this.
https://github.com/madhums/nodejs-express-mongoose-demo
The server.js file would be your app.js. And the /config/passport.js is the included passport setup.
For this I'll suggest to do this In app.js
require('./mypassport')(app);
And
mypassport.js
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, MongoDBConnection = require('./database/DatabaseConnector').MongoDBConnection;
module.exports = function(app){
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
mongoDbConnection.findUserById(id, function(err, user){
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
process.nextTick(function () {
mongoDbConnection.findUser(username, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Unknown user ' + username });
}
if (user.password != password) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
});
});
}
));
}
Adding on to Legendre's answer. module.exports = function() is a way in nodejs to make a file, a variable or a certain functionality globally available to the entire application.
// anyfile.js
module.exports = function(){
//global code.
}
module.exports = function(app){
passport.serializeUser(function(user, done) {
done(null, user.id);
});
Maybe it doesnt work because u do not have a reference to a passport object ?

Resources