Ich versuche zu überprüfen, ob beide Passwörter übereinstimmen, bevor der Benutzer eine Änderung im Profil vornimmt.
Der erste wird bei der Registrierung des Benutzers so in der Datenbank gespeichert:
bcrypt.hashSync(req.body.pass, 8)
Und das zweite ist das Passwort, das der Benutzer als Anfrage gesendet hat
So versuche ich es zu vergleichen:
var passwordIsValid = bcrypt.compareSync(
req.body.pass,
user.pass // the result of searching the user in my database
);
ist aber passwordIsValid
immer falsch, obwohl die Zeichenfolgen gleich sind
Lösung des Problems
Dies könnte helfen. So verwende ich bcrypt mit Mungo, um mein Passwort zu hashen und zu vergleichen:
/* eslint-disable import/prefer-default-export */
import mongoose from 'mongoose';
import {
hash as _hash,
compareSync
} from 'bcrypt-nodejs';
import mongooseDelete from 'mongoose-delete';
const {
Schema
} = mongoose;
const UserSchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
gender: {
type: String,
enum: ['male', 'female'],
},
profilePicture: {
type: String
},
password: {
type: String,
required: true,
},
email: {
type: String,
unique: true,
required: true,
},
}, {
timestamps: true
}, );
UserSchema.plugin(mongooseDelete);
// hash the password before the user is saved
UserSchema.pre('save', function hashPassword(next) {
// hash the password only if the password has been changed or user is new
if (!this.isModified('password')) {
next();
return;
}
// generate the hash
_hash(this.password, null, null, (err, hash) => {
if (err) {
next(err);
return;
}
// change the password to the hashed version
this.password = hash;
next();
});
});
// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function comparePassword(password) {
const data = compareSync(password, this.password);
return data;
};
export {
UserSchema,
};
Keine Kommentare:
Kommentar veröffentlichen