验证后req.user返回未定义

时间:2018-10-14 19:55:32

标签: node.js express passport.js cookie-session

我正在开发一个快速后端,该后端使用带有cookie会话的本地护照和google-oauth2策略进行身份验证。 google-oauth策略可以很好地100%正常运行。但是我的本地策略返回了req.user undefined ...,而req.session返回的是护照,后跟一个空对象。成功后直接进入成功重定向路线!!就像用户立即注销...

我使用了一些console.logs尽我所能尝试遵循策略的流程,但是没有找到切入点(发现在终端日志的图像上附加了一个链接)。 terminal logs img

代码如下...

server / index.js

import 'babel-polyfill'
import express from 'express'
import mongoose from 'mongoose'
import cookieSession from 'cookie-session'
import passport from 'passport'
import bodyParser from 'body-parser'

// Import User model / making schema globaly available
import './models/User'

// Import Routes
import userRoutes from './routes/api/user'
import localAuthRoutes from './routes/auth/local'
import googleAuthRoutes from './routes/auth/google'

// Import Strategies
import './services/passportGoogle'
import './services/passportLocal'

// Config Keys
import keys from './config/keys'

mongoose.Promise = global.Promise  

// Connect to Mongodb
mongoose
  .connect(
    keys.mongoURI,
    { useMongoClient: true }
  )
  .then(() => console.log('MongoDB wired up'))
  .catch(err => console.log(err))

// Run Express
const app = express()

// Middleware
app.use(bodyParser.json())

// Passport config
app.use(
  cookieSession({
    name: 'session',
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: [keys.cookieKey]
  })
)
app.use(passport.initialize())
app.use(passport.session())

// Use Routes
userRoutes(app)
localAuthRoutes(app)
googleAuthRoutes(app)

app.listen(5000, () => {
  console.log('Server monitoring port 5000')
})

server / routes / auth / local.js

import mongoose from 'mongoose'
import passport from 'passport'
import gravatar from 'gravatar'

import keys from '../../config/keys'
import validateRegisterInput from '../../validation/register'
import validateLoginInput from '../../validation/login'

// Import User Model
const User = mongoose.model('User')

module.exports = app => {
  // @route  POST auth/register
  // @desc   Register user with email and password
  // @access Public
  app.post('/auth/register', (req, res) => {
    const { errors, isValid } = validateRegisterInput(req.body)
    //Check Validation
    if (!isValid) {
      return res.status(400).json(errors)
    }
    // Check if User exists
    User.findOne({ email: req.body.email }).then(user => {
      if (user) {
        errors.email = 'Email alresdy in use'
        return res.status(400).json(errors)
      } else {
        const avatar = gravatar.url(req.body.email, {
          s: '200', // Size
          r: 'pg', // Rating
          d: 'mm' // Default
        })

        const newUser = new User({
          email: req.body.email,
          name: req.body.name,
          avatar,
          password: req.body.password
        })
        newUser
          .save()
          .then(user => res.json(user))
          .catch(err => console.log(err))
      }
    })
  })

  // @route  POST /auth/login
  // @desc   User Login with Eamil and Password
  // @access public
  app.post(
    '/auth/login',
    passport.authenticate('local', {
      successRedirect: '/api/success',
      failureRedirect: '/api/failed'
    })
  )
}

server / services / passportLocal.js

import passport from 'passport'
import mongoose from 'mongoose'
import { Strategy as LocalStrategy } from 'passport-local'

const User = mongoose.model('User')

passport.serializeUser((user, done) => {
  // mongoID not googleID
  console.log('reached serializeUser!')
  done(null, user.id)
})

passport.deserializeUser((id, done) => {
  // mongoID not googleID
  User.findById(id).then(user => {
    console.log('reached deserializeUser!')
    done(null, user)
  })
})

passport.use(
  new LocalStrategy(
    {
      usernameField: 'email'
    },
    async (email, password, done) => {
      const user = await User.findOne({ email: email })
      console.log('reached LocalStrategy!')

      if (!user || !user.validPassword(password)) {
        return done(null, false)
      } else {
        return done(null, user)
      }
    }
  )
)

现在已经无法在两天后解决这个问题了……任何建议都很棒!

1 个答案:

答案 0 :(得分:0)

我找到了解决方案...! 我缺少从Postman读取输入键和值对所需的url编码中间件。

已将app.use(bodyParser.urlencoded({extended:false}))添加到我的根index.js文件中,并且现在可以正常使用了:)