如何配置和打包护照作为一个模块?

时间:2016-02-08 07:20:17

标签: node.js authentication passport.js passport-local

我在Advanced Rest Client中测试我的路由,并且我的代码输出为401,未经授权。我不明白为什么会这样。 我将身份验证打包在一个模块中。然后,我使用wagner-core(依赖注入器)在我的服务器文件中调用它:

wagner.invoke(require('./passport-init'),{ app: app })

passport.js:

'use strict'
const bCrypt = require('bcryptjs')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const session = require('express-session')

module.exports = (User, app) => {
  passport.serializeUser((user, done) => {
    done(null, user._id)
  })

  passport.deserializeUser((id, done) => {
    User.findOne({ _id: id }).exec(done)
  })

  passport.use('login', new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => {
    User.findOne({ username: username }, (err, user) => {
      if (err) { return done(err) }
      if (!user) { return done(null, false, { message: 'Invalid username' }) }
      if (!isValidPassword(user, password)) {
        return done(null, false, { message: 'Invalid password' })
      }
      return done(null, user)
    })
  }))

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

  app.post('/login', passport.authenticate('login'), (req, res) => {
    res.redirect('/users/' + req.user.username)
  })
}

function isValidPassword (user, password) {
  return bCrypt.compareSync(password, user.password)
}

1 个答案:

答案 0 :(得分:0)

我明白了。这与我的路线和isValidpassword功能有关。

修改后的代码:

'use strict'
const bCrypt = require('bcryptjs')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const session = require('express-session')

module.exports = (User, app) => {
  passport.serializeUser((user, done) => {
    done(null, user._id)
  })

  passport.deserializeUser((id, done) => {
    User.findById(id, (err, user) => {
      done(err, user)
    })
  })

  passport.use('login', new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => {
    process.nextTick(() => {
      User.findOne({ username: username }, (err, user) => {
        if (err) { return done(err) }
        if (!user) { return done(null, false, { message: 'Invalid username' }) }
        if (!user.password) {
          bCrypt.compareSync(password, user.password)
          return done(null, false, { message: 'Invalid password' })
        }
        return done(null, user)
      })
    })
  }))

  passport.use('signup', new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => {
    process.nextTick(() => {
      User.findOne({ username: username }, (err, user) => {
        if (err) { return done(err) }
        if (user) {
          return done(null, false, { message: 'User already exists' })
        } else {
          let newUser = new User()
          newUser.username = req.body.username
          newUser.password = createHash(req.body.password)
          newUser.save((err) => {
            if (err) throw err
            return done(null, newUser)
          })
        }
      })
    })
  }))

  app.use(session({
    secret: 'secret',
    resave: false,
    saveUninitialized: false
  }))
  app.use(passport.initialize())
  app.use(passport.session())

  app.get('/success', (req, res) => {
    res.send({ state: 'success', user: req.user ? req.user : null })
  })

  app.post('/login', passport.authenticate('login', {
    successRedirect: '/success',
    failureRedirect: '/fail'
  }))

  app.post('/signup', passport.authenticate('signup', {
    successRedirect: '/success',
    failureRedirect: '/fail'
  }))
}

function createHash (password) {
  return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null)
}