processing / p5.js-web-editor

The p5.js Editor is a website for creating p5.js sketches, with a focus on making coding accessible and inclusive for artists, designers, educators, beginners, and anyone else! You can create, share, or remix p5.js sketches without needing to download or configure anything.
https://editor.p5js.org
GNU Lesser General Public License v2.1
1.3k stars 1.27k forks source link

Asynchronous Handling Issue in API Key Hashing Middleware fixed #3017

Closed Swarnendu0123 closed 2 weeks ago

Swarnendu0123 commented 4 months ago

Fixes #3016

Changes:

userSchema.pre('save', async function checkApiKey(next) {
  const user = this;
  if (!user.isModified('apiKeys')) {
    next();
    return;
  }

  try {
    const hashTasks = user.apiKeys
      .filter(k => k.isNew)
      .map(async (k) => {
        const salt = await bcrypt.genSalt(10);
        const hash = await bcrypt.hash(k.hashedKey, salt);
        k.hashedKey = hash;
        // Mongoose will handle isNew flag during save operation
      });

    await Promise.all(hashTasks);

    next(); // Call next if all operations are successful
  } catch (err) {
    next(err); // Pass any error to the next middleware
  }
});

As for the concern about setting the isNew flag to false, it's important to reset this flag after hashing each API key to prevent rehashing it unnecessarily in subsequent save operations. With the provided code, the isNew flag is set to false within the map function after hashing each API key. This ensures that each new API key is hashed only once, even if the save operation is called multiple times.

This implementation maintains the flow of the middleware and ensures that the next() function is called appropriately based on the completion or failure of the asynchronous operations.

I have verified that this pull request:

raclim commented 2 weeks ago

Thank you for your work on this! As this PR currently doesn't pass all the tests and the PR queue we currently have, I'm going to close this one for now. I'm sorry that we couldn't get this in, but please feel free to update and reopen this PR with any changes or check out the other issues!