Skip to content

Asynchronous Handling Issue in API Key Hashing Middleware #3338

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 21, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions server/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,34 +116,52 @@ userSchema.pre('save', function checkPassword(next) {
* API keys hash middleware
*/
userSchema.pre('save', function checkApiKey(next) {
// eslint-disable-line consistent-return
const user = this;
if (!user.isModified('apiKeys')) {
next();
return;
}

let hasNew = false;
let pendingTasks = 0;
let nextCalled = false;

const done = (err) => {
if (nextCalled) return;
if (err) {
nextCalled = true;
next(err);
return;
}
pendingTasks -= 1;
if (pendingTasks === 0) {
nextCalled = true;
next();
}
};

user.apiKeys.forEach((k) => {
if (k.isNew) {
hasNew = true;
pendingTasks += 1;
bcrypt.genSalt(10, (err, salt) => {
// eslint-disable-line consistent-return
if (err) {
next(err);
return;
done(err);
}
bcrypt.hash(k.hashedKey, salt, (innerErr, hash) => {
if (innerErr) {
next(innerErr);
return;
done(innerErr);
}
k.hashedKey = hash;
next();
done();
});
});
}
});
if (!hasNew) next();

if (!hasNew) {
next();
}
});

userSchema.virtual('id').get(function idToString() {
Expand Down