Skip to content

Commit 0b3851c

Browse files
authored
Merge pull request #3338 from Jatin24062005/Jatin-#Issue3016
Asynchronous Handling Issue in API Key Hashing Middleware
2 parents 3094040 + 888961e commit 0b3851c

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

server/models/user.js

+26-8
Original file line numberDiff line numberDiff line change
@@ -116,34 +116,52 @@ userSchema.pre('save', function checkPassword(next) {
116116
* API keys hash middleware
117117
*/
118118
userSchema.pre('save', function checkApiKey(next) {
119-
// eslint-disable-line consistent-return
120119
const user = this;
121120
if (!user.isModified('apiKeys')) {
122121
next();
123122
return;
124123
}
124+
125125
let hasNew = false;
126+
let pendingTasks = 0;
127+
let nextCalled = false;
128+
129+
const done = (err) => {
130+
if (nextCalled) return;
131+
if (err) {
132+
nextCalled = true;
133+
next(err);
134+
return;
135+
}
136+
pendingTasks -= 1;
137+
if (pendingTasks === 0) {
138+
nextCalled = true;
139+
next();
140+
}
141+
};
142+
126143
user.apiKeys.forEach((k) => {
127144
if (k.isNew) {
128145
hasNew = true;
146+
pendingTasks += 1;
129147
bcrypt.genSalt(10, (err, salt) => {
130-
// eslint-disable-line consistent-return
131148
if (err) {
132-
next(err);
133-
return;
149+
done(err);
134150
}
135151
bcrypt.hash(k.hashedKey, salt, (innerErr, hash) => {
136152
if (innerErr) {
137-
next(innerErr);
138-
return;
153+
done(innerErr);
139154
}
140155
k.hashedKey = hash;
141-
next();
156+
done();
142157
});
143158
});
144159
}
145160
});
146-
if (!hasNew) next();
161+
162+
if (!hasNew) {
163+
next();
164+
}
147165
});
148166

149167
userSchema.virtual('id').get(function idToString() {

0 commit comments

Comments
 (0)