1c028313ba
Preserve the saved SMTP password when connection settings are unchanged and keep it out of admin forms. Ref: IT-1601
232 lines
8.7 KiB
C#
232 lines
8.7 KiB
C#
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
|
using HrynCo.NotificationService.Services.EmailChannels.Create;
|
|
using HrynCo.NotificationService.Services.EmailChannels.Delete;
|
|
using HrynCo.NotificationService.Services.EmailChannels.Get;
|
|
using HrynCo.NotificationService.Services.EmailChannels.GetUsageSummary;
|
|
using HrynCo.NotificationService.Services.EmailChannels.Send;
|
|
using HrynCo.NotificationService.Services.EmailChannels.TestSmtp;
|
|
using HrynCo.NotificationService.Services.EmailChannels.Update;
|
|
using HrynCo.NotificationService.Web.Controllers.Admin.ViewModels;
|
|
using MediatR;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace HrynCo.NotificationService.Web.Controllers.Admin;
|
|
|
|
[Route("admin/channels")]
|
|
public class AdminChannelsController(IMediator mediator) : Controller
|
|
{
|
|
|
|
// GET /admin/channels
|
|
[HttpGet("")]
|
|
public async Task<IActionResult> Index(CancellationToken ct)
|
|
{
|
|
var result = await mediator.Send(new GetChannelUsageSummaryQuery(), ct);
|
|
if (!result.IsSuccess)
|
|
{
|
|
ModelState.AddModelError("", result.Error?.Message ?? "Failed to load channels.");
|
|
return View(Array.Empty<ChannelUsageEntry>());
|
|
}
|
|
|
|
return View(result.Result);
|
|
}
|
|
|
|
// GET /admin/channels/create
|
|
[HttpGet("create")]
|
|
public IActionResult Create()
|
|
{
|
|
return View("Edit", new EmailChannelEditViewModel());
|
|
}
|
|
|
|
// GET /admin/channels/{id}
|
|
[HttpGet("{id:guid}")]
|
|
public async Task<IActionResult> Edit(Guid id, CancellationToken ct)
|
|
{
|
|
var result = await mediator.Send(new GetEmailChannelQuery(id), ct);
|
|
if (!result.IsSuccess || result.Result is null)
|
|
return NotFound();
|
|
|
|
var channel = result.Result;
|
|
var smtp = channel.Settings as SmtpChannelSettings ?? new SmtpChannelSettings
|
|
{
|
|
Host = "", Username = "", Password = "", FromEmail = "", FromName = ""
|
|
};
|
|
|
|
var vm = new EmailChannelEditViewModel
|
|
{
|
|
Id = channel.Id,
|
|
ServiceName = channel.ServiceName,
|
|
Priority = channel.Priority,
|
|
EmailChannelType = channel.EmailChannelType,
|
|
DailyLimit = channel.DailyLimit,
|
|
MonthlyLimit = channel.MonthlyLimit,
|
|
WarnThresholdPercent = channel.WarnThresholdPercent,
|
|
IsActive = channel.IsActive,
|
|
Host = smtp.Host,
|
|
Port = smtp.Port,
|
|
Username = smtp.Username,
|
|
UseSsl = smtp.UseSsl,
|
|
FromEmail = smtp.FromEmail,
|
|
FromName = smtp.FromName
|
|
};
|
|
|
|
return View(vm);
|
|
}
|
|
|
|
// POST /admin/channels/save
|
|
[HttpPost("save")]
|
|
[ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Save(EmailChannelEditViewModel model, CancellationToken ct)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
return EditWithErrors(model);
|
|
|
|
var (password, passwordError) = await ResolvePasswordForSave(model, ct);
|
|
if (passwordError is not null)
|
|
{
|
|
ModelState.AddModelError(nameof(model.Password), passwordError);
|
|
return EditWithErrors(model);
|
|
}
|
|
|
|
var smtpSettings = new SmtpChannelSettings
|
|
{
|
|
Host = model.Host,
|
|
Port = model.Port,
|
|
Username = model.Username,
|
|
Password = password,
|
|
UseSsl = model.UseSsl,
|
|
FromEmail = model.FromEmail,
|
|
FromName = model.FromName
|
|
};
|
|
|
|
if (model.IsNew)
|
|
{
|
|
var command = new CreateEmailChannelCommand(
|
|
model.ServiceName,
|
|
model.Priority,
|
|
EmailChannelType.Smtp,
|
|
smtpSettings,
|
|
model.DailyLimit,
|
|
model.MonthlyLimit,
|
|
model.WarnThresholdPercent,
|
|
model.IsActive);
|
|
|
|
var result = await mediator.Send(command, ct);
|
|
if (!result.IsSuccess)
|
|
{
|
|
ModelState.AddModelError("", result.Error?.Message ?? "Failed to create channel.");
|
|
return EditWithErrors(model);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
var command = new UpdateEmailChannelCommand(
|
|
model.Id,
|
|
model.Priority,
|
|
smtpSettings,
|
|
model.DailyLimit,
|
|
model.MonthlyLimit,
|
|
model.WarnThresholdPercent,
|
|
model.IsActive);
|
|
|
|
var result = await mediator.Send(command, ct);
|
|
if (!result.IsSuccess)
|
|
{
|
|
ModelState.AddModelError("", result.Error?.Message ?? "Failed to update channel.");
|
|
return EditWithErrors(model);
|
|
}
|
|
}
|
|
|
|
return RedirectToAction(nameof(Index));
|
|
}
|
|
|
|
private async Task<(string Password, string? Error)> ResolvePasswordForSave(
|
|
EmailChannelEditViewModel model, CancellationToken ct)
|
|
{
|
|
if (!string.IsNullOrEmpty(model.Password))
|
|
return (model.Password, null);
|
|
if (model.IsNew)
|
|
return ("", "The Password field is required.");
|
|
|
|
var channelResult = await mediator.Send(new GetEmailChannelQuery(model.Id), ct);
|
|
if (!channelResult.IsSuccess || channelResult.Result?.Settings is not SmtpChannelSettings saved)
|
|
return ("", "SMTP channel not found.");
|
|
if (!MatchesSavedSmtpConnection(model.Host, model.Port, model.Username, model.UseSsl, saved))
|
|
return ("", "Enter the password to save changed SMTP connection settings.");
|
|
|
|
return (saved.Password, null);
|
|
}
|
|
|
|
private IActionResult EditWithErrors(EmailChannelEditViewModel model)
|
|
{
|
|
model.Password = null;
|
|
return View("Edit", model);
|
|
}
|
|
|
|
// POST /admin/channels/test-smtp
|
|
[HttpPost("test-smtp")]
|
|
public async Task<IActionResult> TestSmtp([FromBody] TestSmtpRequest request, CancellationToken ct)
|
|
{
|
|
var password = request.Password;
|
|
if (string.IsNullOrEmpty(password) && request.ChannelId is Guid channelId)
|
|
{
|
|
var channelResult = await mediator.Send(new GetEmailChannelQuery(channelId), ct);
|
|
if (!channelResult.IsSuccess || channelResult.Result?.Settings is not SmtpChannelSettings saved)
|
|
return Ok(new { success = false, message = "SMTP channel not found." });
|
|
|
|
if (!MatchesSavedSmtpConnection(request.Host, request.Port, request.Username, request.UseSsl, saved))
|
|
return Ok(new { success = false, message = "Enter the password to test changed SMTP connection settings." });
|
|
|
|
password = saved.Password;
|
|
}
|
|
|
|
var result = await mediator.Send(new TestSmtpCommand(
|
|
request.Host, request.Port, request.Username, password ?? string.Empty,
|
|
request.UseSsl, request.FromEmail, request.FromName, request.ToEmail), ct);
|
|
|
|
if (!result.IsSuccess)
|
|
return Ok(new { success = false, message = result.Error?.Message });
|
|
|
|
return Ok(new { success = true, message = $"Test email sent to {request.ToEmail}." });
|
|
}
|
|
|
|
private static bool MatchesSavedSmtpConnection(
|
|
string host, int port, string username, bool useSsl, SmtpChannelSettings saved) =>
|
|
string.Equals(host, saved.Host, StringComparison.OrdinalIgnoreCase)
|
|
&& port == saved.Port
|
|
&& string.Equals(username, saved.Username, StringComparison.Ordinal)
|
|
&& useSsl == saved.UseSsl;
|
|
|
|
// POST /admin/channels/{id}/test
|
|
[HttpPost("{id:guid}/test")]
|
|
public async Task<IActionResult> Test(Guid id, [FromBody] TestChannelRequest request, CancellationToken ct)
|
|
{
|
|
var channelResult = await mediator.Send(new GetEmailChannelQuery(id), ct);
|
|
if (!channelResult.IsSuccess || channelResult.Result is null)
|
|
return NotFound(new { success = false, message = "Channel not found." });
|
|
|
|
var channel = channelResult.Result;
|
|
var subject = "✅ Test email from Notification Service";
|
|
var body = $"This is a test email sent from the Notification Service admin panel.\n\nChannel: {channel.ServiceName}";
|
|
|
|
var sendResult = await mediator.Send(
|
|
new SendEmailCommand(id, request.ToEmail, request.ToEmail, subject, body, null), ct);
|
|
|
|
if (!sendResult.IsSuccess)
|
|
return Ok(new { success = false, message = sendResult.Error?.Message });
|
|
|
|
return Ok(new { success = true, message = $"Test email sent to {request.ToEmail}." });
|
|
}
|
|
|
|
// POST /admin/channels/{id}/delete
|
|
[HttpPost("{id:guid}/delete")]
|
|
[ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
|
{
|
|
await mediator.Send(new DeleteEmailChannelCommand(id), ct);
|
|
return RedirectToAction(nameof(Index));
|
|
}
|
|
}
|
|
|
|
public record TestChannelRequest(string ToEmail);
|