gpt4 book ai didi

javascript - 竞争条件与 bcrypt 的加密计时并添加新的 mongo db 文档

转载 作者:行者123 更新时间:2023-12-01 02:25:15 25 4
gpt4 key购买 nike

我的网站上有一个注册功能,基本上可以使用用户凭据创建一个新文档。这是我的实现,数据实际上是存储在对象中的用户名/密码的输入字段:

let users = db.collection('users');

let query = sanitize(data);

users.findOne({username: query.username}).then(res=>{
if (res){
socket.emit('usercreated', {
msg: `User: ${query.username} already exists.`
});
return;
}

const h = query.username + query.password;

bcrypt.hash(h, 13, (err, hash)=>{
users.insert({username: query.username, password: hash}, (err, user)=>{
if (err){
socket.emit('usercreated', {
msg: `DB is having issues. Please contact admin.`
});
return;
}
socket.emit('usercreated', {
msg: `User ${query.username} has been created.`
});
});
});
})

问题是,如果用户提交用户名/密码垃圾邮件,资源不会看到该用户已经存在,因为 bcrypt.hash 函数实际上需要一秒钟才能解析。

我也尝试过这种方法来在 bcrypt 完成工作后检查 res,但这也不起作用:

let users = db.collection('users');

let query = sanitize(data);

users.findOne({username: query.username}).then(res=>{
const h = query.username + query.password;

bcrypt.hash(h, 13, (err, hash)=>{
if (res){
socket.emit('usercreated', {
msg: `User: ${query.username} already exists.`
});
return;
}
users.insert({username: query.username, password: hash}, (err, user)=>{
if (err){
socket.emit('usercreated', {
msg: `DB is having issues. Please contact admin.`
});
return;
}
socket.emit('usercreated', {
msg: `User ${query.username} has been created.`
});
});
});
})

在进行插入之前检查用户是否已经正确存在的好方法是什么?

最佳答案

问题不在于 bcrypt.hash 需要 1 秒才能解决,而是您处理事情的方式。

以防垃圾邮件,这是一个经典的 readers-writters problem ,虽然有很多方法,但恕我直言,简单修改互斥锁就可以了。

class NamedLocks {
constructor() {
this._pid = {};
}

acquire(pid) {
if (this._pid[pid]) {
// process is locked
// handle it
return Promise.reject();
}

this._pid[pid] = true;
return Promise.resolve();
}

release(pid) {
this._pid[pid] = false;
}
}


let users = db.collection('users');
let query = sanitize(data);
const userLocks = new NamedLocks();

userLocks.acquire(query.username).then(() => {
users.findOne({
username: query.username
}).then(res => {
const h = query.username + query.password;

bcrypt.hash(h, 13, (err, hash) => {
if (res) {
socket.emit('usercreated', {
msg: `User: ${query.username} already exists.`
});
return;
}
users.insert({
username: query.username,
password: hash
}, (err, user) => {
if (err) {
socket.emit('usercreated', {
msg: `DB is having issues. Please contact admin.`
});
return;
}
socket.emit('usercreated', {
msg: `User ${query.username} has been created.`
});
userLocks.release(query.username);
});
});
})
}).catch((e) => {
// handle spamming
})

关于javascript - 竞争条件与 bcrypt 的加密计时并添加新的 mongo db 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48872178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com