fix(auth): prevent race condition on user creation with DB-level uniqueness #159
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description:
This PR fixes a race condition that could occur when two users tried to register simultaneously with the same email or username.
Previously, we manually checked for existing emails and usernames before creating a user using the
checkUserUniqueness
function, which allowed a brief window where concurrent requests could bypass these checks and attempt duplicates. Although the database’s unique constraints prevented actual duplicate records, the application did not handle the resulting errors properly because user creation was not wrapped in a try-catch block. This led to unhandled errors without clear validation feedback.Now, we have removed the
checkUserUniqueness
function and rely on Prisma’s built-in unique constraints at the database level to enforce uniqueness atomically. The user creation logic is wrapped in a try-catch block that catches Prisma’sP2002
error and returns clean, detailed validation messages when duplicates are attempted.Benefits: