Estoy creando una aplicación MERN, con rutas restringidas según la autenticación de roles. Entonces, cuando el servidor se inicia, busca un superusuario después de conectarse a MongoDB, si no encuentra uno, solicita la creación del mismo:
(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' })); }); } })();Lamentablemente, en algún momento, el hash de la contraseña se reduce a los primeros 29 caracteres. Aquí está el esquema de usuario:
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);Cualquier ayuda se agradece, gracias
Debe llamar al método bcrypt.hash dentro de la devolución de llamada bcrypt.genSalt
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' })); }); });El problema es que bcrypt.genSalt solo genera el valor salt, no la contraseña codificada, por eso la contraseña se acorta. También debe llamar a 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' })); }); });Puede leer más aquí https://heynode.com/blog/2020-04/salt-and-hash-passwords-bcrypt/