簡體   English   中英

什么是最好的方法; req.body.password 或 express-mongoose web 應用程序中的數據庫 user.password 中的哈希密碼

[英]What is the best approach; hashing password in req.body.password or at the database user.password in express-mongoose web app

我正在創建一個用戶發布路線,我將在其中進行密碼散列。 那么散列密碼的最佳方法是什么;

let user = await User.findOne({email: req.body.email})
if (user) return res.status(400).send('The user already exists')

user = new User({
    name : req.body.name,
    email: req.body.email,
    password: req.body.password
})


// hashing user passwords
const salting = await bcrypt.genSalt(10)
user.password = await bcrypt.hash(user.password, salting)

在數據庫級別或此上對其進行散列;

let user = await User.findOne({email: req.body.email})
if (user) return res.status(400).send('The user already exists')

 // hashing user passwords
    const salting = await bcrypt.genSalt(10)
    const hashedPassword = await bcrypt.hash(req.body.password, salting)

user = new User({
    name : req.body.name,
    email: req.body.email,
    password: hashedPassword
})

在請求級別上散列,還是有更好的散列方法? 您的意見/建議將非常有用。 提前致謝。

在 mongoDB 中存儲用戶的用戶名和密碼的最佳方法是使用此 mongoose 庫: 'passport-local-mongoose'這會將用戶名和密碼字段添加到您的架構中,並且密碼將保存為散列密碼。

它非常易於使用(在您的用戶模式文件中):

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const passportLocalMongoose = require('passport-local-mongoose')

var userSchema = new Schema({
   admin:{
      type:Boolean,
      default:false
   },
firstName:{
    type:String,
    default:''
},
lastName:{
    type:String,
    default:''
},

})

userSchema.plugin(passportLocalMongoose)

var Users = mongoose.model('User',userSchema)

module.exports = Users

並且您可以使用具有護照本地策略的相同庫來驗證用戶憑據,如下所示:

passport.use(new LocalStrategy((User.authenticate())))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM