From 703757d326fdc5853c690719b530c2467b53e192 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 6 Sep 2026 19:47:38 +0100 Subject: [PATCH] handles duplicate email at register --- .../Accounting/AccountController.cs | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Yavsc.Org/Controllers/Accounting/AccountController.cs b/src/Yavsc.Org/Controllers/Accounting/AccountController.cs index 77e0e32a4..44927d461 100644 --- a/src/Yavsc.Org/Controllers/Accounting/AccountController.cs +++ b/src/Yavsc.Org/Controllers/Accounting/AccountController.cs @@ -467,8 +467,25 @@ IHtmlLocalizerFactory htmlLocalizerFactory, if (ModelState.IsValid) { + var existingUser = await _userManager.FindByEmailAsync(model.Email); + if (existingUser is not null) + { + ModelState.AddModelError(nameof(model.Email), _localizer["DuplicateEmail"]); + return View(model); + } + var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; - var result = await _userManager.CreateAsync(user, model.Password); + IdentityResult result; + try + { + result = await _userManager.CreateAsync(user, model.Password); + } + catch (DbUpdateException ex) when (IsDuplicateEmailViolation(ex)) + { + _logger.LogWarning(ex, "Registration rejected: duplicate email '{Email}'.", model.Email); + ModelState.AddModelError(nameof(model.Email), _localizer["DuplicateEmail"]); + return View(model); + } if (result.Succeeded) { _logger.LogInformation(3, "User created a new account with password."); @@ -517,6 +534,21 @@ IHtmlLocalizerFactory htmlLocalizerFactory, return View(model); } + private static bool IsDuplicateEmailViolation(Exception exception) + { + for (var current = exception; current is not null; current = current.InnerException) + { + if (current is PostgresException pg + && pg.SqlState == PostgresErrorCodes.UniqueViolation + && string.Equals(pg.ConstraintName, "AK_AspNetUsers_Email", StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + [Authorize, HttpPost, ValidateAntiForgeryToken] public async Task SendConfirationEmail() {