我正在創建一個 MERN 應用程式,其路由基于角色身份驗證進行限制。因此,當服務器啟動時,它會在連接到 MongoDB 后查找超級用戶,如果找不到,則會提示創建超級用戶:
(async () =>
{
const MONGO_URI = process.env.MONGO_URI;
await mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
}).then(() => console.log("Mongo success")).catch(err => console.log(err));
const User = require('./models/User');
const Role = require('./_inc/role');
const superUser = await User.findOne({ role: Role.Superuser });
if (!superUser)
{
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl._writeToOutput = function(str)
{
if (rl.stdoutMuted)
{
rl.output.write('*');
}
else
{
rl.output.write(str);
}
}
const prom = (str, muted = false) => new Promise(resolve => {
rl.question(str, resolve);
rl.stdoutMuted = muted;
});
const username = await prom('Username: ');
const email = await prom('Email: ');
const password = await prom('Password: ', true);
rl.history = rl.history.slice(1);
rl.close();
const newUser = new User({
name: username,
email, password,
role: Role.Diosito,
picture: '',
method: {
local: true,
},
});
bcrypt.genSalt(10, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.catch(err => console.log({
error: 'se ocurrió un error por intentar crear al usario'
}));
});
}
})();
不幸的是,密碼哈希在某些時候被縮短為前 29 個字符。這是用戶模式:
const userModel = {
name: {
type: String,
},
email: {
type: String,
unique: true,
},
picture: {
type: String,
},
password: {
type: String,
},
role: {
type: String,
required: true,
},
banned: {
type: Boolean,
default: false,
},
method: {
google: Boolean,
local: Boolean,
},
};
const UserSchema = new Schema(userModel);
任何幫助表示贊賞,謝謝
uj5u.com熱心網友回復:
您需要在 bcrypt.genSalt 回呼中呼叫 bcrypt.hash 方法
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(password, salt, function(err, hash) {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.catch(err => console.log({
error: 'se ocurrió un error por intentar crear al usario'
}));
});
});
uj5u.com熱心網友回復:
問題是bcrypt.genSalt只生成鹽值,而不是散列密碼,所以這就是密碼被縮短的原因。你還需要打電話bcrypt.hash(password, salt)
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(password, salt, function(err, hash) {
newUser.password = hash;
newUser
.save()
.catch(err => console.log({
error: 'se ocurrió un error por intentar crear al usario'
}));
});
});
你可以在這里閱讀更多關于https://heynode.com/blog/2020-04/salt-and-hash-passwords-bcrypt/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/460146.html
標籤:javascript mongodb 猫鼬
上一篇:mongoose中的finOne()失敗并出現MongoServerError:Expectedfieldcollat??iontobeoftypeobject
