javascript - how to fix TypeError: Cannot read property 'authenticate' of undefined passportjs - Stack Overflow

im working on a node passport login authentication but im stack on this error which makes it hard for m

im working on a node passport login authentication but im stack on this error which makes it hard for me to run my node server

/home/emil/Documents/myapp/app/routes.js:14 app.post('/login', passport.authenticate('local-login', { ^ TypeError: Cannot read property 'authenticate' of undefined

how can i fix it?

my code: server.js

var express = require('express');
var app = express();
var port = 8080;

var cookieParser = require('cookie-parser');
var session = require('express-session');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');

var configDB = require('./config/database.js');
mongoose.connect(configDB.url);

app.use(passport.initialize());
app.use(passport.session());
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(session({
secret: 'anystringoftext',
saveUninitialized: true,
resave: true
}));

app.set('view engine', 'ejs');

//app.use('/', function(req, res){
//  res.send('Our First Express program!');
//  console.log(req.cookies);
//  console.log('===============');
//  console.log(req.session);
//});

require('./app/routes.js')(app);

app.listen(port);
console.log('Server running on port: ' + port);

routes.js:

var User = require('./models/user');

module.exports = function (app, passport) {
app.get('/', function (req, res) {
    res.render('index.ejs');
});

 app.get('/login', function (req, res) {
    res.render('login.ejs', {
        message: req.flash('loginMessage')
    });
});

app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/profile',
    failureRedirect: '/login',
    failureFlash: true
}));

app.get('/signup', function (req, res) {
    res.render('signup.ejs', {
        message: req.flash('signupMessage')
    });
});

app.post('/signup', passport.authenticate('local-signup', {
    successRedirect: '/',
    failureRedirect: '/signup',
    failureFlash: true
}));

app.get('/profile', isLoggedIn, function(req, res){
   res.render('profile.ejs', { user: req.user });
});

app.get('/:username/:password', function (req, res) {
    var newUser = new User();
    newUser.local.username = req.params.username;
    newUser.local.password = req.params.password;
    console.log(newUser.local.username + " " + newUser.local.password);
    newUser.save(function (err) {
        if (err)
            console.log(err);
    });
    res.send("Success!");
})
};

function isLoggedIn(req, res, next) {
if(req.isAuthenticated()){
    return next();
}
res.redirect('/login');
}

passport.js

var LocalStrategy = require('passport-local').Strategy;

var User = require('../app/models/user');

module.exports - function(passport) {

passport.serializeUser(function(usser, 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({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
},
function(req, email, password, done){
    process.nextTick(function(){
        User.findOne({'local.username': email}, function(err, user){
            if(err)
                return done(err);
            if(user){
                return done(null, false, req.flash('signupMessage', 'That account exists'));
            } else {
                var newUser = new User();
                newUser.local.username = email;
                newUser.local.password = password;

                newUser.save(function(err){
                    if(err)
                        throw err;
                    return done(null, newUser);
                })
            }
        })

    });
}));

passport.use('local-login', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
},
function(req, email, password, done){
    process.nextTick(function(){
        User.findOne({ 'local.username': email}, function(err, user){
           if(err)
               return done(err);
            if(!user)
                return done(null, false, req.flash('loginMessage', 'No user found'));
            if(user.local.password != password)
                return done(null, false, req.flash('loginMessage', 'invalid password'));
        }
           return done(null, user);  
    })
    })
}
))

im working on a node passport login authentication but im stack on this error which makes it hard for me to run my node server

/home/emil/Documents/myapp/app/routes.js:14 app.post('/login', passport.authenticate('local-login', { ^ TypeError: Cannot read property 'authenticate' of undefined

how can i fix it?

my code: server.js

var express = require('express');
var app = express();
var port = 8080;

var cookieParser = require('cookie-parser');
var session = require('express-session');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');

var configDB = require('./config/database.js');
mongoose.connect(configDB.url);

app.use(passport.initialize());
app.use(passport.session());
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(session({
secret: 'anystringoftext',
saveUninitialized: true,
resave: true
}));

app.set('view engine', 'ejs');

//app.use('/', function(req, res){
//  res.send('Our First Express program!');
//  console.log(req.cookies);
//  console.log('===============');
//  console.log(req.session);
//});

require('./app/routes.js')(app);

app.listen(port);
console.log('Server running on port: ' + port);

routes.js:

var User = require('./models/user');

module.exports = function (app, passport) {
app.get('/', function (req, res) {
    res.render('index.ejs');
});

 app.get('/login', function (req, res) {
    res.render('login.ejs', {
        message: req.flash('loginMessage')
    });
});

app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/profile',
    failureRedirect: '/login',
    failureFlash: true
}));

app.get('/signup', function (req, res) {
    res.render('signup.ejs', {
        message: req.flash('signupMessage')
    });
});

app.post('/signup', passport.authenticate('local-signup', {
    successRedirect: '/',
    failureRedirect: '/signup',
    failureFlash: true
}));

app.get('/profile', isLoggedIn, function(req, res){
   res.render('profile.ejs', { user: req.user });
});

app.get('/:username/:password', function (req, res) {
    var newUser = new User();
    newUser.local.username = req.params.username;
    newUser.local.password = req.params.password;
    console.log(newUser.local.username + " " + newUser.local.password);
    newUser.save(function (err) {
        if (err)
            console.log(err);
    });
    res.send("Success!");
})
};

function isLoggedIn(req, res, next) {
if(req.isAuthenticated()){
    return next();
}
res.redirect('/login');
}

passport.js

var LocalStrategy = require('passport-local').Strategy;

var User = require('../app/models/user');

module.exports - function(passport) {

passport.serializeUser(function(usser, 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({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
},
function(req, email, password, done){
    process.nextTick(function(){
        User.findOne({'local.username': email}, function(err, user){
            if(err)
                return done(err);
            if(user){
                return done(null, false, req.flash('signupMessage', 'That account exists'));
            } else {
                var newUser = new User();
                newUser.local.username = email;
                newUser.local.password = password;

                newUser.save(function(err){
                    if(err)
                        throw err;
                    return done(null, newUser);
                })
            }
        })

    });
}));

passport.use('local-login', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
},
function(req, email, password, done){
    process.nextTick(function(){
        User.findOne({ 'local.username': email}, function(err, user){
           if(err)
               return done(err);
            if(!user)
                return done(null, false, req.flash('loginMessage', 'No user found'));
            if(user.local.password != password)
                return done(null, false, req.flash('loginMessage', 'invalid password'));
        }
           return done(null, user);  
    })
    })
}
))
Share Improve this question asked Apr 24, 2015 at 4:49 emilkituaemilkitua 952 gold badges4 silver badges12 bronze badges 2
  • At least one bug immediately found: module.exports - function(passport) {... should be = not -. Anyway, you shouldn't expect people to debug all your code. Post the minimum code you are having problems with, no one wants to read all that code unless they're working on it. – Hamza Kubba Commented Apr 24, 2015 at 4:54
  • ok thanks. will do that next time – emilkitua Commented Apr 24, 2015 at 5:32
Add a ment  | 

2 Answers 2

Reset to default 8

You have not passed passport to the routes. require('./app/routes.js')(app); should be require('./app/routes.js')(app, passport) in server.js;

I was also facing same error after many trials AND i found this basic error. Related to module.exports that it export a object everytime.

while i was writting this and getting error: module.exports = User;

But This solved my error, module.exports = {User};

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");


const userSchema = new mongoose.Schema({
   name:{
       type: String,
   },
   email:{
       type: String,
   },
});

userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User",userSchema);



module.exports = {User};

and i was requiring it, in this way: const {User} = require("./models/User");

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743697526a4492008.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信