Passport js error in Node

Asked

Viewed 28 times

-1

I am trying to log in my application with Passport but am encountering the following error: Referenceerror: Cannot access 'Passport' before initialization. At object. (C: Users Claudio Desktop new app.js:10:3

Here is the code of my app.js:

const express = require('express')
const mongoose = require('mongoose')
const path = require('path')
const flash = require('connect-flash')
const session = require('express-session')

const app = express()

//passport config
 require('./config/passport')(passport)

//Database config
const database = require('./config/keys').MongoURI
const passport = require('./config/passport')

//Connect to mongo
mongoose.connect(database, {
useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true
})

//Static File
app.use(express.static(path.join(__dirname, '/public')));

//Ejs
app.set('view engine', 'ejs')

//BodyParser
app.use(express.urlencoded({ extended: false }))

//express session
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true,
}))

//passport middleware
app.use(passport.initialize());
app.use(passport.session());

//connect flash
app.use(flash())

//global variables
    app.use((req, res, next) => {
    res.locals.success_msg = req.flash('success_msg')
    res.locals.error_msg = req.flash('error_msg')
    next()
})

//Routes
app.use('/', require('./routes/index'))
app.use('/users', require('./routes/users'))

const PORT = process.env.PORT || 5000

app.listen(PORT, console.log(`Server started on port ${PORT}`))

Here is the config code of the Passport:

const LocalStrategy = require('passport-local').Strategy
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')

//load user model
const User = require('../models/User')

module.exports = function (passport) {
    passport.use(
        new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
            //match user
            User.findOne({ email })
                .then(user => {
                    if (!user) {
                        return done(null, false, { message: 'Usuário ja cadastrado!' })
                    }
                    //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: 'Senha incorreta' })
                        }
                    })
                })
                .catch(err => console.log(err))
        })
    )

    passport.serializeUser((user, done) => {
        done(null, user.id);
    });

    passport.deserializeUser((id, done) => {
        User.findById(id, (err, user) => {
            done(err, user);
        });
    });
}
  • The error is quite clear, you are setting using Passport before require it

1 answer

1

You are using passport on the line:

require('./config/passport')(passport)

Before the line you define passport:

const passport = require('./config/passport')

Note: I don’t know the invocation of your file is correct since you are using the same file.

  • Thank you, for the visa was just a lack of attention from me.

  • @FZ3R0 if the answer helped you, don’t forget to accept it as correct.

Browser other questions tagged

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