Access email settings through the factory

This commit is contained in:
nicolas.dorier
2024-12-06 13:47:14 +09:00
parent 52a1627d81
commit 4d01e3a16a
13 changed files with 64 additions and 60 deletions

View File

@@ -47,6 +47,7 @@ namespace BTCPayServer.Controllers
readonly ILogger _logger;
public PoliciesSettings PoliciesSettings { get; }
public EmailSenderFactory EmailSenderFactory { get; }
public IStringLocalizer StringLocalizer { get; }
public Logs Logs { get; }
@@ -62,6 +63,7 @@ namespace BTCPayServer.Controllers
Fido2Service fido2Service,
UserLoginCodeService userLoginCodeService,
LnurlAuthService lnurlAuthService,
EmailSenderFactory emailSenderFactory,
LinkGenerator linkGenerator,
IStringLocalizer stringLocalizer,
Logs logs)
@@ -75,6 +77,7 @@ namespace BTCPayServer.Controllers
_btcPayServerEnvironment = btcPayServerEnvironment;
_fido2Service = fido2Service;
_lnurlAuthService = lnurlAuthService;
EmailSenderFactory = emailSenderFactory;
_linkGenerator = linkGenerator;
_userLoginCodeService = userLoginCodeService;
_eventAggregator = eventAggregator;
@@ -738,8 +741,7 @@ namespace BTCPayServer.Controllers
[RateLimitsFilter(ZoneLimits.ForgotPassword, Scope = RateLimitsScope.RemoteAddress)]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
var settings = await _SettingsRepository.GetSettingAsync<EmailSettings>();
if (ModelState.IsValid && settings?.IsComplete() is true)
if (ModelState.IsValid && await EmailSenderFactory.IsComplete())
{
var user = await _userManager.FindByEmailAsync(model.Email);
if (!UserService.TryCanLogin(user, out _))

View File

@@ -425,8 +425,7 @@ namespace BTCPayServer.Controllers
private async Task PrepareCreateUserViewData()
{
var emailSettings = await _SettingsRepository.GetSettingAsync<EmailSettings>() ?? new EmailSettings();
ViewData["CanSendEmail"] = emailSettings.IsComplete();
ViewData["CanSendEmail"] = await _emailSenderFactory.IsComplete();
ViewData["AllowRequestEmailConfirmation"] = _policiesSettings.RequiresConfirmedEmail;
}
}

View File

@@ -1199,7 +1199,7 @@ namespace BTCPayServer.Controllers
[HttpGet("server/emails")]
public async Task<IActionResult> Emails()
{
var email = await _SettingsRepository.GetSettingAsync<EmailSettings>() ?? new EmailSettings();
var email = await _emailSenderFactory.GetSettings() ?? new EmailSettings();
var vm = new ServerEmailsViewModel(email)
{
EnableStoresToUseServerEmailSettings = !_policiesSettings.DisableStoresToUseServerEmailSettings
@@ -1216,7 +1216,7 @@ namespace BTCPayServer.Controllers
{
if (model.PasswordSet)
{
var settings = await _SettingsRepository.GetSettingAsync<EmailSettings>() ?? new EmailSettings();
var settings = await _emailSenderFactory.GetSettings() ?? new EmailSettings();
model.Settings.Password = settings.Password;
}
model.Settings.Validate("Settings.", ModelState);
@@ -1262,7 +1262,7 @@ namespace BTCPayServer.Controllers
ModelState.AddModelError("Settings.From", StringLocalizer["Invalid email"]);
return View(model);
}
var oldSettings = await _SettingsRepository.GetSettingAsync<EmailSettings>() ?? new EmailSettings();
var oldSettings = await _emailSenderFactory.GetSettings() ?? new EmailSettings();
if (new ServerEmailsViewModel(oldSettings).PasswordSet)
{
model.Settings.Password = oldSettings.Password;

View File

@@ -26,22 +26,18 @@ public partial class UIStoresController
if (store == null)
return NotFound();
var blob = store.GetStoreBlob();
if (blob.EmailSettings?.IsComplete() is not true && !TempData.HasStatusMessage())
var configured = await _emailSenderFactory.IsComplete(store.Id);
if (!configured && !TempData.HasStatusMessage())
{
var emailSender = await _emailSenderFactory.GetEmailSender(store.Id) as StoreEmailSender;
if (!await IsSetupComplete(emailSender?.FallbackSender))
TempData.SetStatusMessageModel(new StatusMessageModel
{
TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Warning,
Html = "You need to configure email settings before this feature works." +
$" <a class='alert-link' href='{Url.Action("StoreEmailSettings", new { storeId })}'>Configure store email settings</a>."
});
}
Severity = StatusMessageModel.StatusSeverity.Warning,
Html = "You need to configure email settings before this feature works." +
$" <a class='alert-link' href='{Url.Action("StoreEmailSettings", new { storeId })}'>Configure store email settings</a>."
});
}
var vm = new StoreEmailRuleViewModel { Rules = blob.EmailRules ?? [] };
var vm = new StoreEmailRuleViewModel { Rules = store.GetStoreBlob().EmailRules ?? [] };
return View(vm);
}
@@ -110,8 +106,7 @@ public partial class UIStoresController
try
{
var rule = vm.Rules[commandIndex];
var emailSender = await _emailSenderFactory.GetEmailSender(store.Id);
if (await IsSetupComplete(emailSender))
if (await _emailSenderFactory.IsComplete(store.Id))
{
var recipients = rule.To.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o =>
@@ -121,7 +116,8 @@ public partial class UIStoresController
})
.Where(o => o != null)
.ToArray();
var emailSender = await _emailSenderFactory.GetEmailSender(store.Id);
emailSender.SendEmail(recipients.ToArray(), null, null, $"[TEST] {rule.Subject}", rule.Body);
message += StringLocalizer["Test email sent — please verify you received it."];
}
@@ -178,14 +174,12 @@ public partial class UIStoresController
if (store == null)
return NotFound();
var blob = store.GetStoreBlob();
var data = blob.EmailSettings ?? new EmailSettings();
var fallbackSettings = await _emailSenderFactory.GetEmailSender(store.Id) is StoreEmailSender { FallbackSender: not null } storeSender
? await storeSender.FallbackSender.GetEmailSettings()
var emailSender = await _emailSenderFactory.GetEmailSender(store.Id);
var data = await emailSender.GetEmailSettings() ?? new EmailSettings();
var fallbackSettings = emailSender is StoreEmailSender { FallbackSender: { } fallbackSender }
? await fallbackSender.GetEmailSettings()
: null;
var vm = new EmailsViewModel(data, fallbackSettings);
return View(vm);
return View(new EmailsViewModel(data, fallbackSettings));
}
[HttpPost("{storeId}/email-settings")]
@@ -262,9 +256,4 @@ public partial class UIStoresController
}
return RedirectToAction(nameof(StoreEmailSettings), new { storeId });
}
private static async Task<bool> IsSetupComplete(IEmailSender emailSender)
{
return emailSender is not null && (await emailSender.GetEmailSettings())?.IsComplete() == true;
}
}

View File

@@ -61,7 +61,8 @@ public partial class UIStoresController
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
var tcs = new TaskCompletionSource<Uri>();
var invitationEmail = await _emailSenderFactory.IsComplete();
var tcs = new TaskCompletionSource<Uri>();
var currentUser = await _userManager.GetUserAsync(HttpContext.User);
_eventAggregator.Publish(new UserRegisteredEvent
@@ -70,14 +71,13 @@ public partial class UIStoresController
Kind = UserRegisteredEventKind.Invite,
User = user,
InvitedByUser = currentUser,
SendInvitationEmail = true,
SendInvitationEmail = invitationEmail,
CallbackUrlGenerated = tcs
});
var callbackUrl = await tcs.Task;
var settings = await _settingsRepository.GetSettingAsync<EmailSettings>() ?? new EmailSettings();
var info = settings.IsComplete()
? "An invitation email has been sent.<br/>You may alternatively"
var info = invitationEmail
? "An invitation email has been sent.<br/>You may alternatively"
: "An invitation email has not been sent, because the server does not have an email server configured.<br/> You need to";
successInfo = $"{info} share this link with them: <a class='alert-link' href='{callbackUrl}'>{callbackUrl}</a>";
}

View File

@@ -60,7 +60,6 @@ public partial class UIStoresController : Controller
WalletFileParsers onChainWalletParsers,
UIUserStoresController userStoresController,
UriResolver uriResolver,
SettingsRepository settingsRepository,
CurrencyNameTable currencyNameTable,
IStringLocalizer stringLocalizer,
EventAggregator eventAggregator,
@@ -88,7 +87,6 @@ public partial class UIStoresController : Controller
_onChainWalletParsers = onChainWalletParsers;
_userStoresController = userStoresController;
_uriResolver = uriResolver;
_settingsRepository = settingsRepository;
_currencyNameTable = currencyNameTable;
_eventAggregator = eventAggregator;
_html = html;
@@ -110,7 +108,6 @@ public partial class UIStoresController : Controller
private readonly TokenRepository _tokenRepository;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RateFetcher _rateFactory;
private readonly SettingsRepository _settingsRepository;
private readonly CurrencyNameTable _currencyNameTable;
private readonly ExplorerClientProvider _explorerProvider;
private readonly LanguageService _langService;