如何使用Mongoose/Mongodb和node.js- passport身份验证

xmq68pz9  于 2023-03-07  发布在  Go
关注(0)|答案(2)|浏览(131)

我正在构建我的第一个全栈node.js应用程序,我想使用passport进行身份验证。我偶然发现了一个passport的教程,它将用户信息存储在一个用户数组中。
passport-config.js文件:

const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')

function initialize(passport, getUserByEmail, getUserById) {
  const authenticateUser = async (email, password, done) => {
    const user = getUserByEmail(email)
    if (user == null) {
      return done(null, false, { message: 'No user with that email' })
    }

    try {
      if (await bcrypt.compare(password, user.password)) {
        return done(null, user)
      } else {
        return done(null, false, { message: 'Password incorrect' })
      }
    } catch (e) {
      return done(e)
    }
  }

  passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
  passport.serializeUser((user, done) => done(null, user.id))
  passport.deserializeUser((id, done) => {
    return done(null, getUserById(id))
  })
}

module.exports = initialize

服务器. js文件

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config()
}

const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const methodOverride = require('method-override')

const initializePassport = require('./passport-config')
initializePassport(
  passport,
  email => users.find(user => user.email === email),
  id => users.find(user => user.id === id)
)

const users = []

app.set('view-engine', 'ejs')
app.use(express.urlencoded({ extended: false }))
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'))

app.get('/', checkAuthenticated, (req, res) => {
  res.render('index.ejs', { name: req.user.name })
})

app.get('/login', checkNotAuthenticated, (req, res) => {
  res.render('login.ejs')
})

app.post('/login', checkNotAuthenticated, passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/login',
  failureFlash: true
}))

app.get('/register', checkNotAuthenticated, (req, res) => {
  res.render('register.ejs')
})

app.post('/register', checkNotAuthenticated, async (req, res) => {
  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10)
    users.push({
      id: Date.now().toString(),
      name: req.body.name,
      email: req.body.email,
      password: hashedPassword
    })
    res.redirect('/login')
  } catch {
    res.redirect('/register')
  }
})

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

function checkAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next()
  }

  res.redirect('/login')
}

function checkNotAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return res.redirect('/')
  }
  next()
}

app.listen(3000)

我的应用程序使用mongoDb数据库,希望将用户存储在数据库中。我已经对注册路径进行了必要的更改,可以成功地将数据存储在数据库中。

app.post('/register', checkNotAuthenticated, async (req, res) => {
    try {
      const hashedPassword = await bcrypt.hash(req.body.password, 10)
      
      const users = new User({
        name: req.body.name,
        email: req.body.email,
        password: hashedPassword
    })
      await users.save()
      res.redirect('/login')
               
     }
     
     catch(err){
         console.log(err)
         res.redirect('/register')     }
})

问题是,当我尝试登录与存储的用户的数据,我不断得到以下错误.
错误:www.example.com(C:\AIT715\reactlogin\node_modules\bcrypt\bcrypt.js:208:17)中需要数据和散列参数,网址为C:\AIT715\reactlogin\node_modules\bcrypt\promises.js:29:12,网址为对象.模块.导出.承诺(C:\AIT715\reactlogin\node_modules\bcrypt\promises.js:20:12)中的新承诺(),网址为www.example.com(C:\AIT715\reactlogin\node_modules\bcrypt\bcrypt.js:204:25),网址为策略.验证用户[as_verify](C:\AIT715\reactlogin\passport-config.js:14:24),网址为 Object.compare (C:\AIT715\reactlogin\node_modules\bcrypt\bcrypt.js:208:17) at C:\AIT715\reactlogin\node_modules\bcrypt\promises.js:29:12 at new Promise () at Object.module.exports.promise (C:\AIT715\reactlogin\node_modules\bcrypt\promises.js:20:12) at Object.compare (C:\AIT715\reactlogin\node_modules\bcrypt\bcrypt.js:204:25) at Strategy.authenticateUser [as _verify] (C:\AIT715\reactlogin\passport-config.js:14:24) at processTicksAndRejections (internal/process/task_queues.js:95:5)
我尝试对passport-config.js文件进行以下更改,但没有效果。

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

function initialize(passport, getUserByEmail, getUserById) {
  const authenticateUser = async (email, password, done) => {
    const user = await User.find({email:email});
    console.log(user);
    if (user == null) {
      return done(null, false, { message: 'No user with that email' })
    }

    try {
      if (await bcrypt.compare(password, user.password)) {
        return done(null, user)
      } else {
        return done(null, false, { message: 'Password incorrect' })
      }
    } catch (e) {
      return done(e)
    }
  }

当我使用console. log(user)时,我可以读取数据,但是当我使用console. log(www.example.com)时,我得到了未定义的数据。有人能告诉我这里做错了什么吗?或者我需要对passport-config文件做什么修改才能让它正常工作。任何线索或帮助都是非常感谢的。user.email) I get undefined. Can anyone suggest what am I doing wrong here? or what changes do I need to make to the passport-config file to make this work. Any leads or help is highly appreciated.

uoifb46i

uoifb46i1#

const passwordMatch = await bcrypt.compare(password, user.password);

请确保您提供的是原始密码和散列密码。这将返回一个布尔值。

y0u0uwnf

y0u0uwnf2#

以防万一,将来有人在看这个;使用findOne而不是find对我很有效。

const user = await User.findOne({email:email});

相关问题