App: Add events which the app subscribes to (#6435)

* App: Add events which the app subscribes to

Various events, which are relevant for the app to react to changes made on the server.

* Refactor events

* Do not extend NewBlockEvent

* Refactoring events

* Add store role events

* Refactoring: Rename StoreUserEvent

* Fix: Subscribe to UserEvent.Invited

---------

Co-authored-by: nicolas.dorier <nicolas.dorier@gmail.com>
This commit is contained in:
d11n
2024-12-11 12:11:51 +01:00
committed by GitHub
parent 6e222c573b
commit 00cc16455c
29 changed files with 493 additions and 326 deletions

View File

@@ -37,6 +37,7 @@ namespace BTCPayServer.Controllers.Greenfield
private readonly RoleManager<IdentityRole> _roleManager;
private readonly SettingsRepository _settingsRepository;
private readonly EventAggregator _eventAggregator;
private readonly CallbackGenerator _callbackGenerator;
private readonly IPasswordValidator<ApplicationUser> _passwordValidator;
private readonly IRateLimitService _throttleService;
private readonly BTCPayServerOptions _options;
@@ -50,6 +51,7 @@ namespace BTCPayServer.Controllers.Greenfield
SettingsRepository settingsRepository,
PoliciesSettings policiesSettings,
EventAggregator eventAggregator,
CallbackGenerator callbackGenerator,
IPasswordValidator<ApplicationUser> passwordValidator,
IRateLimitService throttleService,
BTCPayServerOptions options,
@@ -65,6 +67,7 @@ namespace BTCPayServer.Controllers.Greenfield
_settingsRepository = settingsRepository;
PoliciesSettings = policiesSettings;
_eventAggregator = eventAggregator;
_callbackGenerator = callbackGenerator;
_passwordValidator = passwordValidator;
_throttleService = throttleService;
_options = options;
@@ -113,7 +116,8 @@ namespace BTCPayServer.Controllers.Greenfield
if (user.RequiresApproval)
{
return await _userService.SetUserApproval(user.Id, request.Approved, Request.GetAbsoluteRootUri())
var loginLink = _callbackGenerator.ForLogin(user, Request);
return await _userService.SetUserApproval(user.Id, request.Approved, loginLink)
? Ok()
: this.CreateAPIError("invalid-state", $"User is already {(request.Approved ? "approved" : "unapproved")}");
}
@@ -219,6 +223,10 @@ namespace BTCPayServer.Controllers.Greenfield
ModelState.AddModelError(string.Empty, error.Description);
}
}
else
{
_eventAggregator.Publish(new UserEvent.Updated(user));
}
}
if (!ModelState.IsValid)
@@ -255,7 +263,7 @@ namespace BTCPayServer.Controllers.Greenfield
blob.ImageUrl = fileIdUri.ToString();
user.SetBlob(blob);
await _userManager.UpdateAsync(user);
_eventAggregator.Publish(new UserEvent.Updated(user));
var model = await FromModel(user);
return Ok(model);
}
@@ -280,6 +288,7 @@ namespace BTCPayServer.Controllers.Greenfield
blob.ImageUrl = null;
user.SetBlob(blob);
await _userManager.UpdateAsync(user);
_eventAggregator.Publish(new UserEvent.Updated(user));
}
return Ok();
}
@@ -399,18 +408,11 @@ namespace BTCPayServer.Controllers.Greenfield
await _settingsRepository.FirstAdminRegistered(policies, _options.UpdateUrl != null, _options.DisableRegistration, Logs);
}
}
var currentUser = await _userManager.GetUserAsync(User);
var userEvent = new UserRegisteredEvent
var userEvent = currentUser switch
{
RequestUri = Request.GetAbsoluteRootUri(),
Admin = isNewAdmin,
User = user
};
if (currentUser is not null)
{
userEvent.Kind = UserRegisteredEventKind.Invite;
userEvent.InvitedByUser = currentUser;
{ } invitedBy => await UserEvent.Invited.Create(user, invitedBy, _callbackGenerator, Request, true),
_ => await UserEvent.Registered.Create(user, _callbackGenerator, Request)
};
_eventAggregator.Publish(userEvent);
@@ -444,6 +446,7 @@ namespace BTCPayServer.Controllers.Greenfield
// Ok, this user is an admin but there are other admins as well so safe to delete
await _userService.DeleteUserAndAssociatedData(user);
_eventAggregator.Publish(new UserEvent.Deleted(user));
return Ok();
}

View File

@@ -41,7 +41,7 @@ namespace BTCPayServer.Controllers
readonly SettingsRepository _SettingsRepository;
private readonly Fido2Service _fido2Service;
private readonly LnurlAuthService _lnurlAuthService;
private readonly LinkGenerator _linkGenerator;
private readonly CallbackGenerator _callbackGenerator;
private readonly UserLoginCodeService _userLoginCodeService;
private readonly EventAggregator _eventAggregator;
readonly ILogger _logger;
@@ -64,7 +64,7 @@ namespace BTCPayServer.Controllers
UserLoginCodeService userLoginCodeService,
LnurlAuthService lnurlAuthService,
EmailSenderFactory emailSenderFactory,
LinkGenerator linkGenerator,
CallbackGenerator callbackGenerator,
IStringLocalizer stringLocalizer,
Logs logs)
{
@@ -78,8 +78,8 @@ namespace BTCPayServer.Controllers
_fido2Service = fido2Service;
_lnurlAuthService = lnurlAuthService;
EmailSenderFactory = emailSenderFactory;
_linkGenerator = linkGenerator;
_userLoginCodeService = userLoginCodeService;
_callbackGenerator = callbackGenerator;
_userLoginCodeService = userLoginCodeService;
_eventAggregator = eventAggregator;
_logger = logs.PayServer;
Logs = logs;
@@ -297,10 +297,7 @@ namespace BTCPayServer.Controllers
{
RememberMe = rememberMe,
UserId = user.Id,
LNURLEndpoint = new Uri(_linkGenerator.GetUriByAction(
action: nameof(UILNURLAuthController.LoginResponse),
controller: "UILNURLAuth",
values: new { userId = user.Id, action = "login", tag = "login", k1 = Encoders.Hex.EncodeData(r) }, Request.Scheme, Request.Host, Request.PathBase) ?? string.Empty)
LNURLEndpoint = new Uri(_callbackGenerator.ForLNUrlAuth(user, r, Request))
};
}
return null;
@@ -627,12 +624,7 @@ namespace BTCPayServer.Controllers
RegisteredAdmin = true;
}
_eventAggregator.Publish(new UserRegisteredEvent
{
RequestUri = Request.GetAbsoluteRootUri(),
User = user,
Admin = RegisteredAdmin
});
_eventAggregator.Publish(await UserEvent.Registered.Create(user, _callbackGenerator, Request));
RegisteredUserId = user.Id;
TempData[WellKnownTempData.SuccessMessage] = StringLocalizer["Account created."].Value;
@@ -699,11 +691,8 @@ namespace BTCPayServer.Controllers
var result = await _userManager.ConfirmEmailAsync(user, code);
if (result.Succeeded)
{
_eventAggregator.Publish(new UserConfirmedEmailEvent
{
User = user,
RequestUri = Request.GetAbsoluteRootUri()
});
var approvalLink = _callbackGenerator.ForApproval(user, Request);
_eventAggregator.Publish(new UserEvent.ConfirmedEmail(user, approvalLink));
var hasPassword = await _userManager.HasPasswordAsync(user);
if (hasPassword)
@@ -749,11 +738,8 @@ namespace BTCPayServer.Controllers
// Don't reveal that the user does not exist or is not confirmed
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
_eventAggregator.Publish(new UserPasswordResetRequestedEvent
{
User = user,
RequestUri = Request.GetAbsoluteRootUri()
});
var callbackUri = await _callbackGenerator.ForPasswordReset(user, Request);
_eventAggregator.Publish(new UserEvent.PasswordResetRequested(user, callbackUri));
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
@@ -889,11 +875,10 @@ namespace BTCPayServer.Controllers
private async Task FinalizeInvitationIfApplicable(ApplicationUser user)
{
if (!_userManager.HasInvitationToken<ApplicationUser>(user)) return;
_eventAggregator.Publish(new UserInviteAcceptedEvent
{
User = user,
RequestUri = Request.GetAbsoluteRootUri()
});
// This is a placeholder, the real storeIds will be set by the UserEventHostedService
var storeUsersLink = _callbackGenerator.StoreUsersLink("{0}", Request);
_eventAggregator.Publish(new UserEvent.InviteAccepted(user, storeUsersLink));
// unset used token
await _userManager.UnsetInvitationTokenAsync<ApplicationUser>(user.Id);
}

View File

@@ -4,9 +4,9 @@ using System.Threading.Tasks;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Contracts;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.Events;
using BTCPayServer.Fido2;
using BTCPayServer.Models.ManageViewModels;
using BTCPayServer.Security.Greenfield;
@@ -36,11 +36,12 @@ namespace BTCPayServer.Controllers
private readonly APIKeyRepository _apiKeyRepository;
private readonly IAuthorizationService _authorizationService;
private readonly Fido2Service _fido2Service;
private readonly LinkGenerator _linkGenerator;
private readonly CallbackGenerator _callbackGenerator;
private readonly IHtmlHelper Html;
private readonly UserService _userService;
private readonly UriResolver _uriResolver;
private readonly IFileService _fileService;
private readonly EventAggregator _eventAggregator;
readonly StoreRepository _StoreRepository;
public IStringLocalizer StringLocalizer { get; }
@@ -55,13 +56,13 @@ namespace BTCPayServer.Controllers
APIKeyRepository apiKeyRepository,
IAuthorizationService authorizationService,
Fido2Service fido2Service,
LinkGenerator linkGenerator,
CallbackGenerator callbackGenerator,
UserService userService,
UriResolver uriResolver,
IFileService fileService,
IStringLocalizer stringLocalizer,
IHtmlHelper htmlHelper
)
IHtmlHelper htmlHelper,
EventAggregator eventAggregator)
{
_userManager = userManager;
_signInManager = signInManager;
@@ -72,8 +73,9 @@ namespace BTCPayServer.Controllers
_apiKeyRepository = apiKeyRepository;
_authorizationService = authorizationService;
_fido2Service = fido2Service;
_linkGenerator = linkGenerator;
_callbackGenerator = callbackGenerator;
Html = htmlHelper;
_eventAggregator = eventAggregator;
_userService = userService;
_uriResolver = uriResolver;
_fileService = fileService;
@@ -189,9 +191,9 @@ namespace BTCPayServer.Controllers
return View(model);
}
if (needUpdate is true)
if (needUpdate && await _userManager.UpdateAsync(user) is { Succeeded: true })
{
needUpdate = await _userManager.UpdateAsync(user) is { Succeeded: true };
_eventAggregator.Publish(new UserEvent.Updated(user));
TempData[WellKnownTempData.SuccessMessage] = StringLocalizer["Your profile has been updated"].Value;
}
else
@@ -217,8 +219,7 @@ namespace BTCPayServer.Controllers
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = _linkGenerator.EmailConfirmationLink(user.Id, code, Request.Scheme, Request.Host, Request.PathBase);
var callbackUrl = await _callbackGenerator.ForEmailConfirmation(user, Request);
(await _EmailSenderFactory.GetEmailSender()).SendEmailConfirmation(user.GetMailboxAddress(), callbackUrl);
TempData[WellKnownTempData.SuccessMessage] = StringLocalizer["Verification email sent. Please check your email."].Value;
return RedirectToAction(nameof(Index));
@@ -320,7 +321,7 @@ namespace BTCPayServer.Controllers
return RedirectToAction(nameof(SetPassword));
}
[HttpPost()]
[HttpPost]
public async Task<IActionResult> DeleteUserPost()
{
var user = await _userManager.GetUserAsync(User);
@@ -330,12 +331,12 @@ namespace BTCPayServer.Controllers
}
await _userService.DeleteUserAndAssociatedData(user);
_eventAggregator.Publish(new UserEvent.Deleted(user));
TempData[WellKnownTempData.SuccessMessage] = StringLocalizer["Account successfully deleted."].Value;
await _signInManager.SignOutAsync();
return RedirectToAction(nameof(UIAccountController.Login), "UIAccount");
}
#region Helpers
private void AddErrors(IdentityResult result)

View File

@@ -70,8 +70,7 @@ namespace BTCPayServer.Controllers
InvitationUrl =
string.IsNullOrEmpty(blob?.InvitationToken)
? null
: _linkGenerator.InvitationLink(u.Id, blob.InvitationToken, Request.Scheme,
Request.Host, Request.PathBase),
: _callbackGenerator.ForInvitation(u, blob.InvitationToken, Request),
EmailConfirmed = u.RequiresEmailConfirmation ? u.EmailConfirmed : null,
Approved = u.RequiresApproval ? u.Approved : null,
Created = u.Created,
@@ -98,7 +97,7 @@ namespace BTCPayServer.Controllers
Id = user.Id,
Email = user.Email,
Name = blob?.Name,
InvitationUrl = string.IsNullOrEmpty(blob?.InvitationToken) ? null : _linkGenerator.InvitationLink(user.Id, blob.InvitationToken, Request.Scheme, Request.Host, Request.PathBase),
InvitationUrl = string.IsNullOrEmpty(blob?.InvitationToken) ? null : _callbackGenerator.ForInvitation(user, blob.InvitationToken, Request),
ImageUrl = string.IsNullOrEmpty(blob?.ImageUrl) ? null : await _uriResolver.Resolve(Request.GetAbsoluteRootUri(), UnresolvedUri.Create(blob.ImageUrl)),
EmailConfirmed = user.RequiresEmailConfirmation ? user.EmailConfirmed : null,
Approved = user.RequiresApproval ? user.Approved : null,
@@ -120,7 +119,8 @@ namespace BTCPayServer.Controllers
if (user.RequiresApproval && viewModel.Approved.HasValue && user.Approved != viewModel.Approved.Value)
{
approvalStatusChanged = await _userService.SetUserApproval(user.Id, viewModel.Approved.Value, Request.GetAbsoluteRootUri());
var loginLink = _callbackGenerator.ForLogin(user, Request);
approvalStatusChanged = await _userService.SetUserApproval(user.Id, viewModel.Approved.Value, loginLink);
}
if (user.RequiresEmailConfirmation && viewModel.EmailConfirmed.HasValue && user.EmailConfirmed != viewModel.EmailConfirmed)
{
@@ -260,31 +260,21 @@ namespace BTCPayServer.Controllers
if (model.IsAdmin && !(await _UserManager.AddToRoleAsync(user, Roles.ServerAdmin)).Succeeded)
model.IsAdmin = false;
var tcs = new TaskCompletionSource<Uri>();
var currentUser = await _UserManager.GetUserAsync(HttpContext.User);
var sendEmail = model.SendInvitationEmail && ViewData["CanSendEmail"] is true;
_eventAggregator.Publish(new UserRegisteredEvent
{
RequestUri = Request.GetAbsoluteRootUri(),
Kind = UserRegisteredEventKind.Invite,
User = user,
InvitedByUser = currentUser,
SendInvitationEmail = sendEmail,
Admin = model.IsAdmin,
CallbackUrlGenerated = tcs
});
var callbackUrl = await tcs.Task;
var evt = await UserEvent.Invited.Create(user, currentUser, _callbackGenerator, Request, sendEmail);
_eventAggregator.Publish(evt);
var info = sendEmail
? "An invitation email has been sent. You may alternatively"
: "An invitation email has not been sent. You need to";
TempData.SetStatusMessageModel(new StatusMessageModel
{
Severity = StatusMessageModel.StatusSeverity.Success,
AllowDismiss = false,
Html = $"Account successfully created. {info} share this link with them:<br/>{callbackUrl}"
Html = $"Account successfully created. {info} share this link with them:<br/>{evt.InvitationLink}"
});
return RedirectToAction(nameof(User), new { userId = user.Id });
}
@@ -387,7 +377,8 @@ namespace BTCPayServer.Controllers
if (user == null)
return NotFound();
await _userService.SetUserApproval(userId, approved, Request.GetAbsoluteRootUri());
var loginLink = _callbackGenerator.ForLogin(user, Request);
await _userService.SetUserApproval(userId, approved, loginLink);
TempData[WellKnownTempData.SuccessMessage] = approved
? StringLocalizer["User approved"].Value
@@ -414,8 +405,7 @@ namespace BTCPayServer.Controllers
throw new ApplicationException($"Unable to load user with ID '{userId}'.");
}
var code = await _UserManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = _linkGenerator.EmailConfirmationLink(user.Id, code, Request.Scheme, Request.Host, Request.PathBase);
var callbackUrl = await _callbackGenerator.ForEmailConfirmation(user, Request);
(await _emailSenderFactory.GetEmailSender()).SendEmailConfirmation(user.GetMailboxAddress(), callbackUrl);

View File

@@ -64,7 +64,7 @@ namespace BTCPayServer.Controllers
private readonly StoredFileRepository _StoredFileRepository;
private readonly IFileService _fileService;
private readonly IEnumerable<IStorageProviderService> _StorageProviderServices;
private readonly LinkGenerator _linkGenerator;
private readonly CallbackGenerator _callbackGenerator;
private readonly UriResolver _uriResolver;
private readonly EmailSenderFactory _emailSenderFactory;
private readonly TransactionLinkProviders _transactionLinkProviders;
@@ -90,7 +90,7 @@ namespace BTCPayServer.Controllers
EventAggregator eventAggregator,
IOptions<ExternalServicesOptions> externalServiceOptions,
Logs logs,
LinkGenerator linkGenerator,
CallbackGenerator callbackGenerator,
UriResolver uriResolver,
EmailSenderFactory emailSenderFactory,
IHostApplicationLifetime applicationLifetime,
@@ -119,7 +119,7 @@ namespace BTCPayServer.Controllers
_eventAggregator = eventAggregator;
_externalServiceOptions = externalServiceOptions;
Logs = logs;
_linkGenerator = linkGenerator;
_callbackGenerator = callbackGenerator;
_uriResolver = uriResolver;
_emailSenderFactory = emailSenderFactory;
ApplicationLifetime = applicationLifetime;

View File

@@ -9,6 +9,7 @@ using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.Events;
using BTCPayServer.Models.StoreViewModels;
using BTCPayServer.Services;
using BTCPayServer.Services.Mails;
using BTCPayServer.Services.Stores;
using Microsoft.AspNetCore.Authorization;
@@ -58,28 +59,18 @@ public partial class UIStoresController
Created = DateTimeOffset.UtcNow
};
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
var currentUser = await _userManager.GetUserAsync(HttpContext.User);
if (currentUser is not null &&
(await _userManager.CreateAsync(user)) is { Succeeded: true } result)
{
var invitationEmail = await _emailSenderFactory.IsComplete();
var tcs = new TaskCompletionSource<Uri>();
var currentUser = await _userManager.GetUserAsync(HttpContext.User);
var evt = await UserEvent.Invited.Create(user, currentUser, _callbackGenerator, Request, invitationEmail);
_eventAggregator.Publish(evt);
_eventAggregator.Publish(new UserRegisteredEvent
{
RequestUri = Request.GetAbsoluteRootUri(),
Kind = UserRegisteredEventKind.Invite,
User = user,
InvitedByUser = currentUser,
SendInvitationEmail = invitationEmail,
CallbackUrlGenerated = tcs
});
var callbackUrl = await tcs.Task;
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>";
successInfo = $"{info} share this link with them: <a class='alert-link' href='{evt.InvitationLink}'>{evt.InvitationLink}</a>";
}
else
{

View File

@@ -59,6 +59,7 @@ public partial class UIStoresController : Controller
EmailSenderFactory emailSenderFactory,
WalletFileParsers onChainWalletParsers,
UIUserStoresController userStoresController,
CallbackGenerator callbackGenerator,
UriResolver uriResolver,
CurrencyNameTable currencyNameTable,
IStringLocalizer stringLocalizer,
@@ -86,6 +87,7 @@ public partial class UIStoresController : Controller
_emailSenderFactory = emailSenderFactory;
_onChainWalletParsers = onChainWalletParsers;
_userStoresController = userStoresController;
_callbackGenerator = callbackGenerator;
_uriResolver = uriResolver;
_currencyNameTable = currencyNameTable;
_eventAggregator = eventAggregator;
@@ -121,6 +123,7 @@ public partial class UIStoresController : Controller
private readonly EmailSenderFactory _emailSenderFactory;
private readonly WalletFileParsers _onChainWalletParsers;
private readonly UIUserStoresController _userStoresController;
private readonly CallbackGenerator _callbackGenerator;
private readonly UriResolver _uriResolver;
private readonly EventAggregator _eventAggregator;
private readonly IHtmlHelper _html;