简体   繁体   中英

Passport.js - req.isAuthenticated is not a function

I'm new to node and express and node and I'm building an authentication feature with passport.js. In my routes I'm using a middleware function called "checkNotAuthenticated" to check if the user is not authenticated, but I'm getting this error: "TypeError: req.isAuthenticated is not a function"

What could the problem be here?

My routes:

const express = require('express')
const router = express.Router()
const bcrypt = require('bcrypt')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const methodOverride = require('method-override')

const User = require('../models/user.model')
const initializePassport = require('../passport-config')
initializePassport(passport)

const app = express()

app.use(flash())
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))

/* Middleware function to check if user is authenticated */
function checkNotAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return res.redirect('/')
  }
  next()
}

/* ------- Routes ------- */
/* Create new user */
router.post('/register', checkNotAuthenticated, async (req, res) => {

  /* Check if the email isn't already taken */
  const emailIsTaken = await User.findOne({email: req.body.email})
  if (emailIsTaken) return res.status(500).send('Email already used')

  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10)

    const user = new User({
      name: req.body.name,
      password: hashedPassword,
      email: req.body.email,
      title: req.body.title,
      about: req.body.about
    })

    user.save()

    res.send('Success - User created')

  } catch (err) {
    res.status(500).send(err)
  }

})

/* Login user */
router.post('/login', checkNotAuthenticated, passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/login',
  failureFlash: true
}))

/* Logout */
router.delete('/logout', (req, res) => {
  req.logOut()
  res.redirect('/login')
})

module.exports = router

passport-config.js:

const User = require('./models/user.model')
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')

function initializePassport(passport) {

    const authenticateUser = async done => {

        /* Check if there's a user account created with that email */
        const userFound = await User.findOne({email: req.body.email})
        if (!userFound) return done(null, false, {message: 'Cannot find user with that email'})
        
        /* Validate password */
        try {
            const checkPassword = await bcrypt.compare(req.body.password, userFound.password)

            if (checkPassword) {
                return done(null, userFound)
            } else {
                return done(null, false, {message: 'Incorrect password'})
            }
            
        } catch (err) {
            return done(err)
            
        }
    }

    passport.use(new LocalStrategy( { usernameField: 'email' }, authenticateUser) )

    passport.serializeUser(done => { done(null, userFound.id) })
    passport.deserializeUser(done => { done(null, userFound) })
}

module.exports = initializePassport

Full error:

TypeError: req.isAuthenticated is not a function
    at checkNotAuthenticated (/home/German/Desktop/ger/code/projects/helpr/helpr-back/routes/users.route.js:27:11)
    at Layer.handle [as handle_request] (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/layer.js:95:5)
    at /home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:335:12)
    at next (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:174:3)
    at router (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:47:12)
function checkNotAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return res.redirect('/')
  }
  next()
}

put this middleware function at bottom of your script just before

module.exports = router;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM