Passport.js - req.isAuthenticated 不是一个函数

Posted

技术标签:

【中文标题】Passport.js - req.isAuthenticated 不是一个函数【英文标题】:Passport.js - req.isAuthenticated is not a function 【发布时间】:2022-01-06 14:38:43 【问题描述】:

我是 node 和 express 和 node 的新手,我正在使用 passport.js 构建身份验证功能。在我的路由中,我使用了一个名为“checkNotAuthenticated”的中间件函数来检查用户是否未通过身份验证,但我收到此错误:“TypeError: req.isAuthenticated is not a function”

这可能是什么问题?

我的路线:

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

完全错误:

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)

【问题讨论】:

【参考方案1】:
function checkNotAuthenticated(req, res, next) 
  if (req.isAuthenticated()) 
    return res.redirect('/')
  
  next()

将此中间件函数放在脚本底部之前

module.exports = router;

【讨论】:

以上是关于Passport.js - req.isAuthenticated 不是一个函数的主要内容,如果未能解决你的问题,请参考以下文章

passport.js 是不是支持 ajax?

Passport.JS 卡在重定向

passport.js 使用sails.js 验证弹出窗口

Passport.js 在 req.login 上失败

格兰特 vs Passport.js? [关闭]

Passport.js本地策略如何保护路线