我創建了一個類似于博客應用程式的應用程式。用戶可以注冊和登錄注銷。當用戶創建它的帳戶而不是注銷時,他/她可以使用相同的密碼再次登錄。但是,在用戶嘗試使用相同的密碼和用戶名登錄時(我無法準確指定時間,但超過 1 天)后。Bcrypt 回傳錯誤。
這是用戶嘗試登錄時的功能。
userSchema.statics.login = async function(username,password){
const user = await this.findOne({username})
if (user){
const auth = await bcrypt.compare(password,user.password)
console.log(auth)
if (auth){
return user
}else{
throw Error('Password is wrong.')
}
}else{
throw Error('Username doesn\'t exist.')
}}
這是用戶注冊時的功能。
userSchema.pre('save', async function(next){
const salt = await bcrypt.genSalt()
this.password = await bcrypt.hash(this.password,salt)
next()
})
uj5u.com熱心網友回復:
不確定這是否有幫助,但這就是我使用 bcrypt 預保存密碼以及比較密碼時的方式:
// 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;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481738.html
下一篇:如何將Map轉換為String?
