Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert Users ControllersExtensions into Services #15360

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public class AccountController : AccountBaseController
private readonly IClock _clock;
private readonly IDistributedCache _distributedCache;
private readonly IEnumerable<IExternalLoginEventHandler> _externalLoginHandlers;
private readonly IUserControllerService _userControllerService;
protected readonly IHtmlLocalizer H;
protected readonly IStringLocalizer S;

Expand All @@ -57,7 +58,8 @@ public class AccountController : AccountBaseController
IClock clock,
IDistributedCache distributedCache,
IDataProtectionProvider dataProtectionProvider,
IEnumerable<IExternalLoginEventHandler> externalLoginHandlers)
IEnumerable<IExternalLoginEventHandler> externalLoginHandlers,
IUserControllerService userControllerService)
{
_signInManager = signInManager;
_userManager = userManager;
Expand All @@ -70,7 +72,7 @@ public class AccountController : AccountBaseController
_distributedCache = distributedCache;
_dataProtectionProvider = dataProtectionProvider;
_externalLoginHandlers = externalLoginHandlers;

_userControllerService = userControllerService;
H = htmlLocalizer;
S = stringLocalizer;
}
Expand Down Expand Up @@ -424,13 +426,13 @@ public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null,

if (noInformationRequired)
{
iUser = await this.RegisterUser(new RegisterViewModel()
iUser = await _userControllerService.RegisterUser(this, new RegisterViewModel()
{
UserName = externalLoginViewModel.UserName,
Email = externalLoginViewModel.Email,
Password = null,
ConfirmPassword = null
}, S["Confirm your account"], _logger);
}, S["Confirm your account"]);

// If the registration was successful we can link the external provider and redirect the user.
if (iUser != null)
Expand Down Expand Up @@ -540,14 +542,14 @@ public async Task<IActionResult> RegisterExternalLogin(RegisterExternalLoginView

if (TryValidateModel(model) && ModelState.IsValid)
{
var iUser = await this.RegisterUser(
var iUser = await _userControllerService.RegisterUser(this,
new RegisterViewModel()
{
UserName = model.UserName,
Email = model.Email,
Password = model.Password,
ConfirmPassword = model.ConfirmPassword
}, S["Confirm your account"], _logger);
}, S["Confirm your account"]);

if (iUser is null)
{
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using OrchardCore.Modules;
using OrchardCore.Settings;
using OrchardCore.Users.Models;
using OrchardCore.Users.Services;
using OrchardCore.Users.ViewModels;

namespace OrchardCore.Users.Controllers
Expand All @@ -20,6 +21,7 @@ public class RegistrationController : Controller
private readonly UserManager<IUser> _userManager;
private readonly IAuthorizationService _authorizationService;
private readonly ISiteService _siteService;
private readonly IUserControllerService _userControllerService;
private readonly INotifier _notifier;
private readonly ILogger _logger;
protected readonly IStringLocalizer S;
Expand All @@ -29,6 +31,7 @@ public class RegistrationController : Controller
UserManager<IUser> userManager,
IAuthorizationService authorizationService,
ISiteService siteService,
IUserControllerService userControllerService,
INotifier notifier,
ILogger<RegistrationController> logger,
IHtmlLocalizer<RegistrationController> htmlLocalizer,
Expand All @@ -37,6 +40,7 @@ public class RegistrationController : Controller
_userManager = userManager;
_authorizationService = authorizationService;
_siteService = siteService;
_userControllerService = userControllerService;
_notifier = notifier;
_logger = logger;
H = htmlLocalizer;
Expand Down Expand Up @@ -89,7 +93,7 @@ public async Task<IActionResult> Register(RegisterViewModel model, string return

if (ModelState.IsValid)
{
var iUser = await this.RegisterUser(model, S["Confirm your account"], _logger);
var iUser = await _userControllerService.RegisterUser(this, model, S["Confirm your account"]);
// If we get a user, redirect to returnUrl
if (iUser is User user)
{
Expand Down Expand Up @@ -159,7 +163,7 @@ public async Task<IActionResult> SendVerificationEmail(string id)
var user = await _userManager.FindByIdAsync(id) as User;
if (user != null)
{
await this.SendEmailConfirmationTokenAsync(user, S["Confirm your account"]);
await _userControllerService.SendEmailConfirmationTokenAsync(this, user, S["Confirm your account"]);

await _notifier.SuccessAsync(H["Verification email sent."]);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,26 @@ public class ResetPasswordController : Controller
private readonly UserManager<IUser> _userManager;
private readonly ISiteService _siteService;
private readonly IEnumerable<IPasswordRecoveryFormEvents> _passwordRecoveryFormEvents;
private readonly IUserControllerService _userControllerService;
private readonly ILogger _logger;
protected readonly IStringLocalizer S;

public ResetPasswordController(
IUserService userService,
UserManager<IUser> userManager,
ISiteService siteService,
IStringLocalizer<ResetPasswordController> stringLocalizer,
IEnumerable<IPasswordRecoveryFormEvents> passwordRecoveryFormEvents,
IUserControllerService userControllerService,
ILogger<ResetPasswordController> logger,
IEnumerable<IPasswordRecoveryFormEvents> passwordRecoveryFormEvents)
IStringLocalizer<ResetPasswordController> stringLocalizer)
{
_userService = userService;
_userManager = userManager;
_siteService = siteService;

S = stringLocalizer;
_logger = logger;
_passwordRecoveryFormEvents = passwordRecoveryFormEvents;
_userControllerService = userControllerService;
_logger = logger;
S = stringLocalizer;
}

[HttpGet]
Expand Down Expand Up @@ -81,7 +83,7 @@ public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
user.ResetToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(user.ResetToken));
var resetPasswordUrl = Url.Action("ResetPassword", "ResetPassword", new { code = user.ResetToken }, HttpContext.Request.Scheme);
// send email with callback link
await this.SendEmailAsync(user.Email, S["Reset your password"], new LostPasswordViewModel() { User = user, LostPasswordUrl = resetPasswordUrl });
await _userControllerService.SendEmailAsync(user.Email, S["Reset your password"], new LostPasswordViewModel() { User = user, LostPasswordUrl = resetPasswordUrl });

var context = new PasswordRecoveryContext(user);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using OrchardCore.DisplayManagement;
using OrchardCore.Email;
using OrchardCore.Modules;
using OrchardCore.Settings;
using OrchardCore.Users.Events;
using OrchardCore.Users.Models;
using OrchardCore.Users.ViewModels;

namespace OrchardCore.Users.Services;

public class DefaultUserControllerService : IUserControllerService
{
private readonly ISmtpService _smtpService;
private readonly IDisplayHelper _displayHelper;
private readonly HtmlEncoder _htmlEncoder;
private readonly IEnumerable<IRegistrationFormEvents> _registrationFormEvents;
private readonly IUserService _userService;
private readonly ISiteService _siteService;
private readonly SignInManager<IUser> _signInManager;
private readonly UserManager<IUser> _userManager;
private readonly ILogger<DefaultUserControllerService> _logger;

public DefaultUserControllerService(
ISmtpService smtpService,
IDisplayHelper displayHelper,
HtmlEncoder htmlEncoder,
IEnumerable<IRegistrationFormEvents> registrationFormEvents,
IUserService userService,
ISiteService siteService,
SignInManager<IUser> signInManager,
UserManager<IUser> userManager,
ILogger<DefaultUserControllerService> logger)
{
_smtpService = smtpService;
_displayHelper = displayHelper;
_htmlEncoder = htmlEncoder;
_registrationFormEvents = registrationFormEvents;
_userService = userService;
_siteService = siteService;
_signInManager = signInManager;
_userManager = userManager;
_logger = logger;
}

public async Task<bool> SendEmailAsync(string email, string subject, IShape model)
{
var body = string.Empty;

using (var sw = new StringWriter())
{
var htmlContent = await _displayHelper.ShapeExecuteAsync(model);
htmlContent.WriteTo(sw, _htmlEncoder);
body = sw.ToString();
}

var message = new MailMessage()
{
To = email,
Subject = subject,
Body = body,
IsHtmlBody = true
};

var result = await _smtpService.SendAsync(message);

return result.Succeeded;
}

/// <summary>
/// Returns the created user, otherwise returns null.
/// </summary>
/// <param name="controller"></param>
/// <param name="model"></param>
/// <param name="confirmationEmailSubject"></param>
/// <returns></returns>
public async Task<IUser> RegisterUser(Controller controller, RegisterViewModel model, string confirmationEmailSubject)
{
var settings = (await _siteService.GetSiteSettingsAsync()).As<RegistrationSettings>();

if (settings.UsersCanRegister != UserRegistrationType.NoRegistration)
{
await _registrationFormEvents.InvokeAsync((e, modelState) => e.RegistrationValidationAsync((key, message) => modelState.AddModelError(key, message)), controller.ModelState, _logger);

if (controller.ModelState.IsValid)
{
var user = await _userService.CreateUserAsync(new User { UserName = model.UserName, Email = model.Email, EmailConfirmed = !settings.UsersMustValidateEmail, IsEnabled = !settings.UsersAreModerated }, model.Password, (key, message) => controller.ModelState.AddModelError(key, message)) as User;

if (user != null && controller.ModelState.IsValid)
{
if (settings.UsersMustValidateEmail && !user.EmailConfirmed)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
await SendEmailConfirmationTokenAsync(controller, user, confirmationEmailSubject);
}
else if (!(settings.UsersAreModerated && !user.IsEnabled))
{
await _signInManager.SignInAsync(user, isPersistent: false);
}

_logger.LogInformation(3, "User created a new account with password.");

await _registrationFormEvents.InvokeAsync((e, user) => e.RegisteredAsync(user), user, _logger);

return user;
}
}
}

return null;
}

public async Task<string> SendEmailConfirmationTokenAsync(Controller controller, User user, string subject)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = controller.Url.Action("ConfirmEmail", "Registration", new { userId = user.UserId, code }, protocol: controller.HttpContext.Request.Scheme);
await SendEmailAsync(user.Email, subject, new ConfirmEmailViewModel() { User = user, ConfirmEmailUrl = callbackUrl });

return callbackUrl;
}
}