Passport.js 身份验证重定向超时

Passport.js Authentication Redirect Timeout

我花了两天时间寻找这个问题的答案,但无济于事。

当我尝试注册用户时,重定向无法执行。它在数据库中创建用户但不会重定向到主页。最终它超时并抛出此错误 A user with the given username is already registered 即使它是一个全新的用户。它似乎创建了用户,然后重试。

我在另一个网络应用程序中使用了相同的代码(如下),没有任何问题。非常感谢任何帮助。

App.js

require('dotenv').config()

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const morgan = require('morgan')
const passport = require('passport')
const flash = require('connect-flash')
const LocalStrategy = require('passport-local').Strategy
const methodOverride = require('method-override')

//Require Models
const User = require('./models/user')

//Require Routes
const indexRoutes = require('./routes/index')
const membersRoutes = require('./routes/members')

mongoose.connect(process.env.MONGODB_URL, {useNewUrlParser: true})

//Console log
app.use(morgan('dev'))

//Configure Body Parser
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.use(methodOverride('_method'))
app.use(flash())

//Add time stamp to post, comments, and contributions.
app.locals.moment = require('moment')

//Allow browser access.
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
  if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, PUT')
  }
  next()
})

//Passport Config
app.use(require('express-session')({
  secret: 'string that I will not show',
  resave: false,
  saveUninitialized: false
}))

app.use(passport.initialize())
app.use(passport.session())
passport.use(new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password'
},
  User.authenticate))
passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())

app.use((req, res, next) => {
  res.locals.currentUser = req.user
  res.locals.error = req.flash('error')
  res.locals.success = req.flash('success')
  next()
})

//Use Routes
app.use(indexRoutes)
app.use(membersRoutes)

module.exports = app

Member.js

const express = require('express')
const router = express.Router()
const passport = require('passport')
const User = require('../models/user')

//Register Routes
router.get('/register', (req, res, next) => {
  res.render('register', { page: 'register'})
})

router.post('/register', (req, res, next) => {
  var newUser = new User(req.body.user)
  newUser.email = req.body.email
  if (req.body.password !== req.body.confirmPassword) {
    req.flash('error', 'Passwords do not match. Please, try again.')
    return res.redirect('/register')
  } else {
    User.register(newUser, req.body.password, (err, user) => {
      if (err) {
        console.log(err)
        return res.render('register', { 'error': err.message })
      }
        passport.authenticate('local')(req, res, () => {
          req.flash('success', 'Welcome to ALUPC, ' + user.firstName + ' ' + user.lastName + '!')
          res.redirect('/')
      })
    }) 
  }
})

//Login Routes
router.get('/login', (req, res, next) => {
  res.render('login', {page: 'login'})
})

router.post('/login', passport.authenticate('local',
  {
    successRedirect: '/',
    failureRedirect: '/login'
  }), function (req, res) {
  })

//Logout Routes
router.get('/logout', function (req, res) {
  req.logout();
  res.redirect('/');
})

//Member Page Routes

module.exports = router

用户模型

const mongoose = require('mongoose')
const passLocMon = require('passport-local-mongoose')

const userSchema = mongoose.Schema({
  email: {type: String, unique: true, required: true},
  password: String,
  firstName: {type: String, required: true},
  lastName: {type: String, required: true},
})

userSchema.plugin(passLocMon, {
  usernameField: 'email', 
  passwordField: 'password'
})

module.exports = mongoose.model('User', userSchema)

找到了!!原来在搜索上一个错误的答案时,我在下面的代码部分中删除了一组括号...

passport.use(new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password'
},
  User.authenticate))

我忘记加回用于调用 User.authenticate() 的括号。