Harden password reset and email send flows

This commit is contained in:
2026-03-28 14:17:12 +01:00
parent 25ae6b94e9
commit 9f949ee9df
15 changed files with 205 additions and 57 deletions
+31 -13
View File
@@ -17,12 +17,14 @@ public sealed class UsersController : ControllerBase
private readonly RoleManager<IdentityRole> _roles;
private readonly IAppEmailSender _email;
private readonly IConfiguration _cfg;
public UsersController(UserManager<ApplicationUser> users, RoleManager<IdentityRole> roles, IAppEmailSender email, IConfiguration cfg)
private readonly ILogger<UsersController> _logger;
public UsersController(UserManager<ApplicationUser> users, RoleManager<IdentityRole> roles, IAppEmailSender email, IConfiguration cfg, ILogger<UsersController> logger)
{
_users = users;
_roles = roles;
_email = email;
_cfg = cfg;
_logger = logger;
}
public sealed record UserDto(
@@ -150,12 +152,20 @@ public sealed class UsersController : ControllerBase
var link = $"{baseUrl}/reset-password?email={Uri.EscapeDataString(u.Email)}&token={Uri.EscapeDataString(token)}";
await _email.SendAsync(
u.Email,
"Password reset",
$"An admin initiated a password reset for your Jobbjakt account.\n\nReset link:\n{link}\n",
cancellationToken
);
try
{
await _email.SendAsync(
u.Email,
"Password reset",
$"An admin initiated a password reset for your Jobbjakt account.\n\nReset link:\n{link}\n",
cancellationToken
);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send admin-initiated password reset email to {Email}", u.Email);
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: "Password reset email could not be sent right now. Please try again later.");
}
return NoContent();
}
@@ -176,12 +186,20 @@ public sealed class UsersController : ControllerBase
? "This is a test email from the Jobbjakt admin panel.\n\nIf you received this, the SMTP configuration is working."
: request!.Message!.Trim();
await _email.SendAsync(
toEmail,
subject,
$"{message}\n\nSent at: {DateTimeOffset.UtcNow:u}",
cancellationToken
);
try
{
await _email.SendAsync(
toEmail,
subject,
$"{message}\n\nSent at: {DateTimeOffset.UtcNow:u}",
cancellationToken
);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send test email to {Email}", toEmail);
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: "Test email could not be sent right now. Please try again later.");
}
return NoContent();
}