Node.js Passport.authenticate is not a Function, how do I fix this?

Asked

Viewed 385 times

1

As requested, I reduced the codes a little and kept only the essentials that I believe are involved with the problem. Reformulating my question: I have a simple registration in a modal (only name, email, phone and password) I can navigate the site quietly but when I insert data in this registration and try to submit (sending the data via a post to the signup route below, in the third sample of codes) the following error occurs.

Passport.authenticate is not a Function

Typeerror: Passport.authenticate is not a Function at module.Exports (C: Users Bruno Desktop pe Routes rotaslogin-cadastro.js:26:33) At layer.Handle [as handle_request] (C: Users Bruno Desktop pe node_modules express lib router layer.js:95:5) at trim_prefix (C: Users Bruno Desktop pe node_modules express lib router index.js:317:13) AT: Users Bruno Desktop pe node_modules express lib router index.js:284:7 At function.process_params (C: Users Bruno Desktop pe node_modules express lib router index.js:335:12) at next (C: Users Bruno Desktop pe node_modules express lib router index.js:275:10) AT: Users Bruno Desktop pe node_modules express lib router index.js:635:15 at next (C: Users Bruno Desktop pe node_modules express lib router index.js:260:14) At function.Handle (C: Users Bruno Desktop pe node_modules express lib router index.js:174:3) at router (C: Users Bruno Desktop pe node_modules express lib router index.js:47:12) At layer.Handle [as handle_request] (C: Users Bruno Desktop pe node_modules express lib router layer.js:95:5) at trim_prefix (C: Users Bruno Desktop pe node_modules express lib router index.js:317:13) AT: Users Bruno Desktop pe node_modules express lib router index.js:284:7 At function.process_params (C: Users Bruno Desktop pe node_modules express lib router index.js:335:12) at next (C: Users Bruno Desktop pe node_modules express lib router index.js:275:10) AT: Users Bruno Desktop pe node_modules connect-flash lib flash.js:21:5

Follow the code lines related to the app.js Passport

    var mongoose = require('mongoose');
    var passport = require('passport');
    var flash = require('connect-flash');

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


    // configuration ===============================================================
    mongoose.connect(configDB.url); // connect to our database

    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions
    app.use(flash()); // use connect-flash for flash messages stored in session


    require('./routes/rotaslogin-cadastro')(app, passport);
    require('./config/passport')(passport); // pass passport for configuration

    module.exports = app;

Follow the code of 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);
        });
    });

 // LOCAL SIGNUP
    passport.use('local-signup', new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField: 'email',
            passwordField: 'senha',
            telefoneField: 'telefone',
            nomeField: 'nome',
            passReqToCallback: true // allows us to pass back the entire request to the callback
        },
        function(req, email, senha, telefone, nome, done) {

            // asynchronous
            // User.findOne wont fire unless data is sent back
            process.nextTick(function() {

                // find a user whose email is the same as the forms email
                // we are checking to see if the user trying to login already exists
                User.findOne({ 'local.email': email }, function(err, user) {
                    // if there are any errors, return the error
                    if (err)
                        return done(err);

                    // check to see if theres already a user with that email
                    if (user) {
                        return done(null, false, req.flash('signupMessage', 'Esse email já existe.'));
                    } else {

                        // create the user
                        var newUser = new User();

                        // set the user's local credentials
                        newUser.local.email = email;
                        newUser.local.senha = newUser.generateHash(senha);
                        newUser.local.telefone = telefone;
                        newUser.local.nome = nome;

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

                });

            });

        }));


    // LOCAL LOGIN 

    passport.use('local-login', new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField: 'email',
            passwordField: 'senha',
            passReqToCallback: true // allows us to pass back the entire request to the callback
        },
        function(req, email, senha, telefone, nome, done) { // callback with email and password from our form

            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            User.findOne({ 'local.email': email }, function(err, user) {
                // if there are any errors, return the error before anything else
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user)
                    return done(null, false, req.flash('loginMessage', 'Não existe um usuario com esse email.')); // req.flash is the way to set flashdata using connect-flash

                // if the user is found but the password is wrong
                if (!user.validPassword(password))
                    return done(null, false, req.flash('loginMessage', 'Oops! senha errada.')); // create the loginMessage and save it to session as flashdata

                // all is well, return successful user
                return done(null, user);
            });

        }));

};

Follows the code of the registration and login routes (it is the function Passport.authenticate that of the problem I think):

module.exports = function(app, passport) {

// SIGNUP ==============================
// show the signup form
app.get('/signup', function(req, res, next) {
    passport.authenticate('local-login', function(err, user, info) {
        if (err) { return next(err); }
        //if there is no user in the response send the info back to modal
        if (!user) {
            return res.send(info);
        }
        //user was able to login, send true and redirect
        req.logIn(user, function(err) {
            if (err) { return next(err); }
            return res.send({ valid: true });
        });
    })(req, res, next);
});

// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
    successRedirect: '/', // redirect to the secure profile section
    failureRedirect: '/signup', // redirect back to the signup page if there is an error
    failureFlash: true // allow flash messages
}));
}

Here the software dependencies:

"name": "pe",
"version": "0.0.0",
"private": true,
"scripts": {
    "start": "node ./bin/www"
},
"dependencies": {
    "body-parser": "~1.17.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.3",
    "ejs": "~2.5.6",
    "express": "~4.15.2",
    "express-session": "~1.15.3",
    "morgan": "~1.8.1",
    "serve-favicon": "~2.4.2",
    "passport-twitter": "~1.0.4",
    "passport-google-oauth": "~1.0.0",
    "bcrypt-nodejs": "~0.0.3",
    "mongoose": "~4.11.1",
    "passport": "~0.3.2",
    "passport-facebook": "~2.1.1",
    "passport-local": "~1.0.0",
    "connect-flash": "~0.1.1"
}

}

  • 1

    I tried to read the problem, Bruno. You could try abstracting the most relevant points and formatting the question correctly, please.

  • I edited it, it’s better this way?

  • Try to put require('./routes/rotaslogin-cadastro')(app, passport); after require('./config/passport')(passport);.

  • I tried and kept making the same mistake =/

  • console.log(passport) within the routes display what? As it is going undefined.

  • And favicon.ico started to give error 500 with this change

  • _key: 'passport' ,

 
_strategies: {session: sessionStrategy {name: 'session' } },
_serializers: [],
_deserializers: [],
_infoTransformers: [],
_framework: 
{initialize: [Fuction: initialize],
 authenticate: [Fuction: authenticate] },
_userproperty: 'user',
Authenticator : [Function: authenticate] ,
Passport: [Function: Authenticator],
strategy: {[Function: Strategy] Strategy: [Circular] },
strategies: {SessionStrategy: { [Fuction: SessionStrategy] super_:[object]
} } }

  • I don’t know how to leave this formatted right kkkk

Show 3 more comments

1 answer

-1

Do something like this, see if it works:

app.post("/signup", function(req, res){  
User.register({usernameField: req.body.usernameField}, req.body.passwordField, function(err, user){
  if (err) {
    console.log(err);
    res.redirect("/signup");
  } else {
    passport.authenticate("local")(req, res, function(){
      res.redirect("/");
    });
  }
});
});

Source: http://www.passportjs.org/docs/authenticate/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.