From d1b35deb437066e6f2359d939771f3f6822bd150 Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 21 Oct 2020 16:51:00 +1100 Subject: [PATCH] Migrates remaining backofficecontroller but still a bunch of work to do , streamlines Backoffice to BackOffice (but is that what we want?) --- .../BackOffice/BackOfficeIdentityUser.cs | 3 +- .../Configuration/Models/SecuritySettings.cs | 2 +- .../HybridBackofficeSecurityAccessor.cs | 6 +- .../IBackofficeSecurityFactory.cs | 8 +- src/Umbraco.Core/IUmbracoContext.cs | 2 +- .../PublishedCache/DefaultCultureAccessor.cs | 1 + .../Security/IBackofficeSecurity.cs | 2 +- .../Security/IBackofficeSecurityAccessor.cs | 4 +- .../BackOffice/IBackOfficeUserManager.cs | 3 + .../InstallSteps/StarterKitDownloadStep.cs | 8 +- .../InstallSteps/StarterKitInstallStep.cs | 6 +- .../Mapping/MemberTabsAndPropertiesMapper.cs | 10 +- .../Scheduling/ScheduledPublishing.cs | 6 +- .../Scheduling/SchedulerComponent.cs | 4 +- .../WebAssets/BackOfficeWebAssets.cs | 8 +- .../UmbracoTestServerTestBase.cs | 4 +- .../Testing/UmbracoIntegrationTest.cs | 2 +- .../Filters/ContentModelValidatorTests.cs | 8 +- .../Objects/TestUmbracoContextFactory.cs | 4 +- .../AppendUserModifiedHeaderAttributeTests.cs | 4 +- ...terAllowedOutgoingContentAttributeTests.cs | 10 +- .../Controllers/SurfaceControllerTests.cs | 16 +- .../PublishedContentCacheTests.cs | 2 +- .../PublishedContentSnapshotTestBase.cs | 2 +- .../Scoping/ScopedNuCacheTests.cs | 2 +- .../TestControllerActivatorBase.cs | 2 +- .../TestHelpers/TestWithDatabaseBase.cs | 2 +- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 2 +- .../Web/Mvc/UmbracoViewPageTests.cs | 2 +- .../Web/WebExtensionMethodTests.cs | 6 +- .../Controllers/AuthenticationController.cs | 12 +- .../Controllers/BackOfficeController.cs | 236 ++++++++++- .../Controllers/ContentController.cs | 58 +-- .../Controllers/ContentTypeController.cs | 14 +- .../Controllers/CurrentUserController.cs | 40 +- .../Controllers/DictionaryController.cs | 12 +- .../Controllers/EntityController.cs | 14 +- .../Controllers/LogController.cs | 6 +- .../Controllers/MacrosController.cs | 8 +- .../Controllers/MediaController.cs | 26 +- .../Controllers/MediaTypeController.cs | 12 +- .../Controllers/MemberController.cs | 10 +- .../Controllers/MemberTypeController.cs | 8 +- .../Controllers/PackageController.cs | 6 +- .../Controllers/PackageInstallController.cs | 14 +- .../Controllers/PreviewController.cs | 6 +- .../RedirectUrlManagementController.cs | 8 +- .../Controllers/SectionController.cs | 12 +- .../Controllers/TourController.cs | 8 +- .../Controllers/UpdateCheckController.cs | 6 +- .../Controllers/UserGroupsController.cs | 20 +- .../Controllers/UsersController.cs | 24 +- .../Filters/AdminUsersAuthorizeAttribute.cs | 6 +- .../AppendUserModifiedHeaderAttribute.cs | 2 +- .../Filters/ContentModelValidator.cs | 8 +- .../Filters/ContentSaveModelValidator.cs | 2 +- .../Filters/ContentSaveValidationAttribute.cs | 10 +- ...EnsureUserPermissionForContentAttribute.cs | 16 +- .../EnsureUserPermissionForMediaAttribute.cs | 12 +- .../FilterAllowedOutgoingContentAttribute.cs | 2 +- .../FilterAllowedOutgoingMediaAttribute.cs | 6 +- .../IsCurrentUserModelFilterAttribute.cs | 6 +- .../MediaItemSaveValidationAttribute.cs | 8 +- .../Filters/MediaSaveModelValidator.cs | 2 +- .../Filters/MemberSaveModelValidator.cs | 4 +- .../Filters/MemberSaveValidationAttribute.cs | 6 +- .../OutgoingEditorModelEventAttribute.cs | 6 +- .../UmbracoApplicationAuthorizeAttribute.cs | 10 +- .../Filters/UmbracoTreeAuthorizeAttribute.cs | 10 +- .../UserGroupAuthorizationAttribute.cs | 6 +- .../Trees/ContentTreeController.cs | 10 +- .../Trees/ContentTreeControllerBase.cs | 22 +- .../Trees/MediaTreeController.cs | 8 +- .../Trees/MemberTreeController.cs | 6 +- .../Install/InstallController.cs | 6 +- .../Middleware/UmbracoRequestMiddleware.cs | 6 +- .../Runtime/AspNetCoreComposer.cs | 4 +- .../Security/BackOfficeSignInManager.cs | 4 +- .../Security/BackofficeSecurity.cs | 2 +- .../Security/BackofficeSecurityFactory.cs | 16 +- .../Security/ExternalAuthenticationOptions.cs | 13 + .../Security/ExternalSignInAutoLinkOptions.cs | 50 +-- .../UmbracoContext/UmbracoContext.cs | 4 +- .../UmbracoContext/UmbracoContextFactory.cs | 6 +- .../Editors/BackOfficeController.cs | 371 ------------------ src/Umbraco.Web/Mvc/BackOfficeArea.cs | 13 +- .../Mvc/UmbracoAuthorizeAttribute.cs | 10 +- src/Umbraco.Web/Mvc/UmbracoController.cs | 2 +- .../AuthenticationOptionsExtensions.cs | 198 +++++----- .../Security/BackofficeSecurity.cs | 10 +- .../Security/IdentityAuditEventArgs.cs | 6 +- src/Umbraco.Web/Umbraco.Web.csproj | 4 +- src/Umbraco.Web/UmbracoContext.cs | 4 +- src/Umbraco.Web/UmbracoContextFactory.cs | 2 +- src/Umbraco.Web/UmbracoHttpHandler.cs | 2 +- src/Umbraco.Web/UmbracoWebService.cs | 2 +- .../WebApi/UmbracoApiControllerBase.cs | 2 +- .../WebApi/UmbracoAuthorizeAttribute.cs | 10 +- 98 files changed, 712 insertions(+), 904 deletions(-) create mode 100644 src/Umbraco.Web.Common/Security/ExternalAuthenticationOptions.cs rename src/{Umbraco.Web => Umbraco.Web.Common}/Security/ExternalSignInAutoLinkOptions.cs (50%) delete mode 100644 src/Umbraco.Web/Editors/BackOfficeController.cs diff --git a/src/Umbraco.Core/BackOffice/BackOfficeIdentityUser.cs b/src/Umbraco.Core/BackOffice/BackOfficeIdentityUser.cs index bd04b44b18..601291c14a 100644 --- a/src/Umbraco.Core/BackOffice/BackOfficeIdentityUser.cs +++ b/src/Umbraco.Core/BackOffice/BackOfficeIdentityUser.cs @@ -40,7 +40,7 @@ namespace Umbraco.Core.BackOffice /// This is allowed to be null (but would need to be filled in if trying to persist this instance) /// /// - public static BackOfficeIdentityUser CreateNew(GlobalSettings globalSettings, string username, string email, string culture) + public static BackOfficeIdentityUser CreateNew(GlobalSettings globalSettings, string username, string email, string culture, string name = null) { if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(username)); if (string.IsNullOrWhiteSpace(culture)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(culture)); @@ -54,6 +54,7 @@ namespace Umbraco.Core.BackOffice user._id = int.MinValue; user._hasIdentity = false; user._culture = culture; + user._name = name; user.EnableChangeTracking(); return user; } diff --git a/src/Umbraco.Core/Configuration/Models/SecuritySettings.cs b/src/Umbraco.Core/Configuration/Models/SecuritySettings.cs index f40160d69b..55bd3a5bf7 100644 --- a/src/Umbraco.Core/Configuration/Models/SecuritySettings.cs +++ b/src/Umbraco.Core/Configuration/Models/SecuritySettings.cs @@ -4,7 +4,7 @@ { public bool KeepUserLoggedIn { get; set; } = false; - public bool HideDisabledUsersInBackoffice { get; set; } = false; + public bool HideDisabledUsersInBackOffice { get; set; } = false; public bool AllowPasswordReset { get; set; } = true; diff --git a/src/Umbraco.Core/HybridBackofficeSecurityAccessor.cs b/src/Umbraco.Core/HybridBackofficeSecurityAccessor.cs index a953ed8b82..4549227c89 100644 --- a/src/Umbraco.Core/HybridBackofficeSecurityAccessor.cs +++ b/src/Umbraco.Core/HybridBackofficeSecurityAccessor.cs @@ -6,7 +6,7 @@ using Umbraco.Web.Security; namespace Umbraco.Core { - public class HybridBackofficeSecurityAccessor : HybridAccessorBase, IBackofficeSecurityAccessor + public class HybridBackofficeSecurityAccessor : HybridAccessorBase, IBackOfficeSecurityAccessor { /// /// Initializes a new instance of the class. @@ -19,9 +19,9 @@ namespace Umbraco.Core protected override string ItemKey => "Umbraco.Web.HybridBackofficeSecurityAccessor"; /// - /// Gets or sets the object. + /// Gets or sets the object. /// - public IBackofficeSecurity BackofficeSecurity + public IBackOfficeSecurity BackOfficeSecurity { get => Value; set => Value = value; diff --git a/src/Umbraco.Core/IBackofficeSecurityFactory.cs b/src/Umbraco.Core/IBackofficeSecurityFactory.cs index 9f8f791e4c..5176682e61 100644 --- a/src/Umbraco.Core/IBackofficeSecurityFactory.cs +++ b/src/Umbraco.Core/IBackofficeSecurityFactory.cs @@ -3,13 +3,13 @@ namespace Umbraco.Core { /// - /// Creates and manages instances. + /// Creates and manages instances. /// - public interface IBackofficeSecurityFactory + public interface IBackOfficeSecurityFactory { /// - /// Ensures that a current exists. + /// Ensures that a current exists. /// - void EnsureBackofficeSecurity(); + void EnsureBackOfficeSecurity(); } } diff --git a/src/Umbraco.Core/IUmbracoContext.cs b/src/Umbraco.Core/IUmbracoContext.cs index 03fb305fb6..e65b7b9d80 100644 --- a/src/Umbraco.Core/IUmbracoContext.cs +++ b/src/Umbraco.Core/IUmbracoContext.cs @@ -18,7 +18,7 @@ namespace Umbraco.Web /// /// Gets the BackofficeSecurity class /// - IBackofficeSecurity Security { get; } + IBackOfficeSecurity Security { get; } /// /// Gets the uri that is handled by ASP.NET after server-side rewriting took place. diff --git a/src/Umbraco.Core/PublishedCache/DefaultCultureAccessor.cs b/src/Umbraco.Core/PublishedCache/DefaultCultureAccessor.cs index ef6a6dd8da..dffe2274aa 100644 --- a/src/Umbraco.Core/PublishedCache/DefaultCultureAccessor.cs +++ b/src/Umbraco.Core/PublishedCache/DefaultCultureAccessor.cs @@ -23,6 +23,7 @@ namespace Umbraco.Web.PublishedCache /// public string DefaultCulture => _runtimeLevel == RuntimeLevel.Run ? _localizationService.GetDefaultLanguageIsoCode() ?? "" // fast + // TODO: Shouldn't this come from GlobalSettings.DefaultUILanguage? : "en-US"; // default for install and upgrade, when the service is n/a } } diff --git a/src/Umbraco.Core/Security/IBackofficeSecurity.cs b/src/Umbraco.Core/Security/IBackofficeSecurity.cs index 3a0e0baa1d..187d5d172d 100644 --- a/src/Umbraco.Core/Security/IBackofficeSecurity.cs +++ b/src/Umbraco.Core/Security/IBackofficeSecurity.cs @@ -4,7 +4,7 @@ using Umbraco.Core.Models.Membership; namespace Umbraco.Web.Security { - public interface IBackofficeSecurity + public interface IBackOfficeSecurity { /// /// Gets the current user. diff --git a/src/Umbraco.Core/Security/IBackofficeSecurityAccessor.cs b/src/Umbraco.Core/Security/IBackofficeSecurityAccessor.cs index d3cea99f9f..03c1035cb9 100644 --- a/src/Umbraco.Core/Security/IBackofficeSecurityAccessor.cs +++ b/src/Umbraco.Core/Security/IBackofficeSecurityAccessor.cs @@ -2,8 +2,8 @@ namespace Umbraco.Core.Security { - public interface IBackofficeSecurityAccessor + public interface IBackOfficeSecurityAccessor { - IBackofficeSecurity BackofficeSecurity { get; set; } + IBackOfficeSecurity BackOfficeSecurity { get; set; } } } diff --git a/src/Umbraco.Infrastructure/BackOffice/IBackOfficeUserManager.cs b/src/Umbraco.Infrastructure/BackOffice/IBackOfficeUserManager.cs index 5fd7c4dff0..cc169f31f9 100644 --- a/src/Umbraco.Infrastructure/BackOffice/IBackOfficeUserManager.cs +++ b/src/Umbraco.Infrastructure/BackOffice/IBackOfficeUserManager.cs @@ -14,6 +14,9 @@ namespace Umbraco.Core.BackOffice public interface IBackOfficeUserManager: IDisposable where TUser : BackOfficeIdentityUser { + Task DeleteAsync(TUser user); + + Task FindByLoginAsync(string loginProvider, string providerKey); /// /// Finds and returns a user, if any, who has the specified . diff --git a/src/Umbraco.Infrastructure/Install/InstallSteps/StarterKitDownloadStep.cs b/src/Umbraco.Infrastructure/Install/InstallSteps/StarterKitDownloadStep.cs index d060db2c43..77385eb2fa 100644 --- a/src/Umbraco.Infrastructure/Install/InstallSteps/StarterKitDownloadStep.cs +++ b/src/Umbraco.Infrastructure/Install/InstallSteps/StarterKitDownloadStep.cs @@ -18,13 +18,13 @@ namespace Umbraco.Web.Install.InstallSteps internal class StarterKitDownloadStep : InstallSetupStep { private readonly InstallHelper _installHelper; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IUmbracoVersion _umbracoVersion; private readonly IUmbracoApplicationLifetime _umbracoApplicationLifetime; private readonly IContentService _contentService; private readonly IPackagingService _packageService; - public StarterKitDownloadStep(IContentService contentService, IPackagingService packageService, InstallHelper installHelper, IBackofficeSecurityAccessor backofficeSecurityAccessor, IUmbracoVersion umbracoVersion, IUmbracoApplicationLifetime umbracoApplicationLifetime) + public StarterKitDownloadStep(IContentService contentService, IPackagingService packageService, InstallHelper installHelper, IBackOfficeSecurityAccessor backofficeSecurityAccessor, IUmbracoVersion umbracoVersion, IUmbracoApplicationLifetime umbracoApplicationLifetime) { _installHelper = installHelper; _backofficeSecurityAccessor = backofficeSecurityAccessor; @@ -68,7 +68,7 @@ namespace Umbraco.Web.Install.InstallSteps private async Task<(string packageFile, int packageId)> DownloadPackageFilesAsync(Guid kitGuid) { //Go get the package file from the package repo - var packageFile = await _packageService.FetchPackageFileAsync(kitGuid, _umbracoVersion.Current, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var packageFile = await _packageService.FetchPackageFileAsync(kitGuid, _umbracoVersion.Current, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); if (packageFile == null) throw new InvalidOperationException("Could not fetch package file " + kitGuid); //add an entry to the installedPackages.config @@ -78,7 +78,7 @@ namespace Umbraco.Web.Install.InstallSteps _packageService.SaveInstalledPackage(packageDefinition); - _packageService.InstallCompiledPackageFiles(packageDefinition, packageFile, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(-1)); + _packageService.InstallCompiledPackageFiles(packageDefinition, packageFile, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(-1)); return (compiledPackage.PackageFile.Name, packageDefinition.Id); } diff --git a/src/Umbraco.Infrastructure/Install/InstallSteps/StarterKitInstallStep.cs b/src/Umbraco.Infrastructure/Install/InstallSteps/StarterKitInstallStep.cs index 0f2394dcf4..4cd25c16bb 100644 --- a/src/Umbraco.Infrastructure/Install/InstallSteps/StarterKitInstallStep.cs +++ b/src/Umbraco.Infrastructure/Install/InstallSteps/StarterKitInstallStep.cs @@ -16,10 +16,10 @@ namespace Umbraco.Web.Install.InstallSteps internal class StarterKitInstallStep : InstallSetupStep { private readonly IUmbracoApplicationLifetime _umbracoApplicationLifetime; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IPackagingService _packagingService; - public StarterKitInstallStep(IUmbracoApplicationLifetime umbracoApplicationLifetime, IBackofficeSecurityAccessor backofficeSecurityAccessor, IPackagingService packagingService) + public StarterKitInstallStep(IUmbracoApplicationLifetime umbracoApplicationLifetime, IBackOfficeSecurityAccessor backofficeSecurityAccessor, IPackagingService packagingService) { _umbracoApplicationLifetime = umbracoApplicationLifetime; _backofficeSecurityAccessor = backofficeSecurityAccessor; @@ -49,7 +49,7 @@ namespace Umbraco.Web.Install.InstallSteps var packageFile = new FileInfo(definition.PackagePath); - _packagingService.InstallCompiledPackageData(definition, packageFile, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(-1)); + _packagingService.InstallCompiledPackageData(definition, packageFile, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(-1)); } public override bool RequiresExecution(object model) diff --git a/src/Umbraco.Infrastructure/Models/Mapping/MemberTabsAndPropertiesMapper.cs b/src/Umbraco.Infrastructure/Models/Mapping/MemberTabsAndPropertiesMapper.cs index abc32fc008..bb7e30aaf2 100644 --- a/src/Umbraco.Infrastructure/Models/Mapping/MemberTabsAndPropertiesMapper.cs +++ b/src/Umbraco.Infrastructure/Models/Mapping/MemberTabsAndPropertiesMapper.cs @@ -28,7 +28,7 @@ namespace Umbraco.Web.Models.Mapping /// public class MemberTabsAndPropertiesMapper : TabsAndPropertiesMapper { - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly ILocalizedTextService _localizedTextService; private readonly IMemberTypeService _memberTypeService; private readonly IMemberService _memberService; @@ -37,7 +37,7 @@ namespace Umbraco.Web.Models.Mapping private readonly PropertyEditorCollection _propertyEditorCollection; public MemberTabsAndPropertiesMapper(ICultureDictionary cultureDictionary, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILocalizedTextService localizedTextService, IMemberTypeService memberTypeService, IMemberService memberService, @@ -80,8 +80,8 @@ namespace Umbraco.Web.Models.Mapping isLockedOutProperty.Value = _localizedTextService.Localize("general/no"); } - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser != null - && _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.AllowedSections.Any(x => x.Equals(Constants.Applications.Settings))) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser != null + && _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.AllowedSections.Any(x => x.Equals(Constants.Applications.Settings))) { var memberTypeLink = string.Format("#/member/memberTypes/edit/{0}", source.ContentTypeId); @@ -195,7 +195,7 @@ namespace Umbraco.Web.Models.Mapping // check if this property is flagged as sensitive var isSensitiveProperty = memberType.IsSensitiveProperty(prop.Alias); // check permissions for viewing sensitive data - if (isSensitiveProperty && (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.HasAccessToSensitiveData() == false)) + if (isSensitiveProperty && (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasAccessToSensitiveData() == false)) { // mark this property as sensitive prop.IsSensitive = true; diff --git a/src/Umbraco.Infrastructure/Scheduling/ScheduledPublishing.cs b/src/Umbraco.Infrastructure/Scheduling/ScheduledPublishing.cs index 81dd8f92af..9a7f40cdaa 100644 --- a/src/Umbraco.Infrastructure/Scheduling/ScheduledPublishing.cs +++ b/src/Umbraco.Infrastructure/Scheduling/ScheduledPublishing.cs @@ -14,14 +14,14 @@ namespace Umbraco.Web.Scheduling private readonly IMainDom _mainDom; private readonly IRuntimeState _runtime; private readonly IServerMessenger _serverMessenger; - private readonly IBackofficeSecurityFactory _backofficeSecurityFactory; + private readonly IBackOfficeSecurityFactory _backofficeSecurityFactory; private readonly IServerRegistrar _serverRegistrar; private readonly IUmbracoContextFactory _umbracoContextFactory; public ScheduledPublishing(IBackgroundTaskRunner runner, int delayMilliseconds, int periodMilliseconds, IRuntimeState runtime, IMainDom mainDom, IServerRegistrar serverRegistrar, IContentService contentService, - IUmbracoContextFactory umbracoContextFactory, ILogger logger, IServerMessenger serverMessenger, IBackofficeSecurityFactory backofficeSecurityFactory) + IUmbracoContextFactory umbracoContextFactory, ILogger logger, IServerMessenger serverMessenger, IBackOfficeSecurityFactory backofficeSecurityFactory) : base(runner, delayMilliseconds, periodMilliseconds) { _runtime = runtime; @@ -78,7 +78,7 @@ namespace Umbraco.Web.Scheduling // but then what should be its "scope"? could we attach it to scopes? // - and we should definitively *not* have to flush it here (should be auto) // - _backofficeSecurityFactory.EnsureBackofficeSecurity(); + _backofficeSecurityFactory.EnsureBackOfficeSecurity(); using (var contextReference = _umbracoContextFactory.EnsureUmbracoContext()) { try diff --git a/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs b/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs index c96071ff04..d1dea43469 100644 --- a/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs +++ b/src/Umbraco.Infrastructure/Scheduling/SchedulerComponent.cs @@ -42,7 +42,7 @@ namespace Umbraco.Web.Scheduling private readonly HealthChecksSettings _healthChecksSettings; private readonly IServerMessenger _serverMessenger; private readonly IRequestAccessor _requestAccessor; - private readonly IBackofficeSecurityFactory _backofficeSecurityFactory; + private readonly IBackOfficeSecurityFactory _backofficeSecurityFactory; private readonly LoggingSettings _loggingSettings; private readonly KeepAliveSettings _keepAliveSettings; private readonly IHostingEnvironment _hostingEnvironment; @@ -65,7 +65,7 @@ namespace Umbraco.Web.Scheduling IServerMessenger serverMessenger, IRequestAccessor requestAccessor, IOptions loggingSettings, IOptions keepAliveSettings, IHostingEnvironment hostingEnvironment, - IBackofficeSecurityFactory backofficeSecurityFactory) + IBackOfficeSecurityFactory backofficeSecurityFactory) { _runtime = runtime; _mainDom = mainDom; diff --git a/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs b/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs index 5e4a1e2c7a..93250ef981 100644 --- a/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs +++ b/src/Umbraco.Infrastructure/WebAssets/BackOfficeWebAssets.cs @@ -75,13 +75,13 @@ namespace Umbraco.Web.WebAssets _runtimeMinifier.CreateJsBundle( UmbracoJsBundleName, FormatPaths( - GetScriptsForBackoffice( + GetScriptsForBackOffice( propertyEditorAssets.TryGetValue(AssetType.Javascript, out var scripts) ? scripts : Enumerable.Empty()))); _runtimeMinifier.CreateCssBundle( UmbracoCssBundleName, FormatPaths( - GetStylesheetsForBackoffice( + GetStylesheetsForBackOffice( propertyEditorAssets.TryGetValue(AssetType.Css, out var styles) ? styles : Enumerable.Empty()))); } @@ -89,7 +89,7 @@ namespace Umbraco.Web.WebAssets /// Returns scripts used to load the back office /// /// - private string[] GetScriptsForBackoffice(IEnumerable propertyEditorScripts) + private string[] GetScriptsForBackOffice(IEnumerable propertyEditorScripts) { var umbracoInit = GetInitBackOfficeScripts(); var scripts = new HashSet(); @@ -117,7 +117,7 @@ namespace Umbraco.Web.WebAssets /// Returns stylesheets used to load the back office /// /// - private string[] GetStylesheetsForBackoffice(IEnumerable propertyEditorStyles) + private string[] GetStylesheetsForBackOffice(IEnumerable propertyEditorStyles) { var stylesheets = new HashSet(); diff --git a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs index 2aacd7b8fb..037dab5d9e 100644 --- a/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs +++ b/src/Umbraco.Tests.Integration/TestServerTest/UmbracoTestServerTestBase.cs @@ -89,7 +89,7 @@ namespace Umbraco.Tests.Integration.TestServerTest { var url = LinkGenerator.GetUmbracoApiService(methodSelector); - var backofficeSecurityFactory = GetRequiredService(); + var backofficeSecurityFactory = GetRequiredService(); var umbracoContextFactory = GetRequiredService(); var httpContextAccessor = GetRequiredService(); @@ -104,7 +104,7 @@ namespace Umbraco.Tests.Integration.TestServerTest } }; - backofficeSecurityFactory.EnsureBackofficeSecurity(); + backofficeSecurityFactory.EnsureBackOfficeSecurity(); umbracoContextFactory.EnsureUmbracoContext(); return url; diff --git a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs index 795fc07f79..c50d292c97 100644 --- a/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs +++ b/src/Umbraco.Tests.Integration/Testing/UmbracoIntegrationTest.cs @@ -274,7 +274,7 @@ namespace Umbraco.Tests.Integration.Testing public virtual void Configure(IApplicationBuilder app) { - Services.GetRequiredService().EnsureBackofficeSecurity(); + Services.GetRequiredService().EnsureBackOfficeSecurity(); Services.GetRequiredService().EnsureUmbracoContext(); // get the currently set options diff --git a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs index 75713c808b..60d6a0fce8 100644 --- a/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs +++ b/src/Umbraco.Tests.Integration/Umbraco.Web.BackOffice/Filters/ContentModelValidatorTests.cs @@ -135,14 +135,14 @@ namespace Umbraco.Tests.Web.Validation public void Validating_ContentItemSave() { var logger = Services.GetRequiredService>(); - var backofficeSecurityFactory = Services.GetRequiredService(); - backofficeSecurityFactory.EnsureBackofficeSecurity(); - var backofficeSecurityAccessor = Services.GetRequiredService(); + var backofficeSecurityFactory = Services.GetRequiredService(); + backofficeSecurityFactory.EnsureBackOfficeSecurity(); + var backofficeSecurityAccessor = Services.GetRequiredService(); var localizedTextService = Services.GetRequiredService(); var propertyValidationService = Services.GetRequiredService(); var umbracoMapper = Services.GetRequiredService(); - var validator = new ContentSaveModelValidator(logger, backofficeSecurityAccessor.BackofficeSecurity, localizedTextService, propertyValidationService); + var validator = new ContentSaveModelValidator(logger, backofficeSecurityAccessor.BackOfficeSecurity, localizedTextService, propertyValidationService); var content = ContentBuilder.CreateTextpageContent(_contentType, "test", -1); diff --git a/src/Umbraco.Tests.UnitTests/TestHelpers/Objects/TestUmbracoContextFactory.cs b/src/Umbraco.Tests.UnitTests/TestHelpers/Objects/TestUmbracoContextFactory.cs index 8960eb5319..6853a02314 100644 --- a/src/Umbraco.Tests.UnitTests/TestHelpers/Objects/TestUmbracoContextFactory.cs +++ b/src/Umbraco.Tests.UnitTests/TestHelpers/Objects/TestUmbracoContextFactory.cs @@ -38,8 +38,8 @@ namespace Umbraco.Tests.UnitTests.TestHelpers.Objects snapshotService.Setup(x => x.CreatePublishedSnapshot(It.IsAny())).Returns(snapshot.Object); var hostingEnvironment = Mock.Of(); - var backofficeSecurityAccessorMock = new Mock(); - backofficeSecurityAccessorMock.Setup(x => x.BackofficeSecurity).Returns(Mock.Of()); + var backofficeSecurityAccessorMock = new Mock(); + backofficeSecurityAccessorMock.Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var umbracoContextFactory = new UmbracoContextFactory( diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs index 6c725d1049..8222347664 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttributeTests.cs @@ -91,7 +91,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters .SetupGet(x => x.Id) .Returns(100); - var backofficeSecurityMock = new Mock(); + var backofficeSecurityMock = new Mock(); backofficeSecurityMock .SetupGet(x => x.CurrentUser) .Returns(currentUserMock.Object); @@ -99,7 +99,7 @@ namespace Umbraco.Tests.UnitTests.Umbraco.Web.BackOffice.Filters var serviceProviderMock = new Mock(); serviceProviderMock - .Setup(x => x.GetService(typeof(IBackofficeSecurity))) + .Setup(x => x.GetService(typeof(IBackOfficeSecurity))) .Returns(backofficeSecurityMock.Object); httpContext.RequestServices = serviceProviderMock.Object; diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttributeTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttributeTests.cs index 5c186c890c..3740f83168 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttributeTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttributeTests.cs @@ -30,7 +30,7 @@ namespace Umbraco.Tests.Web.Controllers ActionBrowse.ActionLetter, Mock.Of(), Mock.Of(), - Mock.Of() ); + Mock.Of() ); var result = att.GetValueFromResponse(new ObjectResult(expected)); @@ -48,7 +48,7 @@ namespace Umbraco.Tests.Web.Controllers ActionBrowse.ActionLetter, Mock.Of(), Mock.Of(), - Mock.Of() ); + Mock.Of() ); var result = att.GetValueFromResponse(new ObjectResult(container)); @@ -66,7 +66,7 @@ namespace Umbraco.Tests.Web.Controllers ActionBrowse.ActionLetter, Mock.Of(), Mock.Of(), - Mock.Of() ); + Mock.Of() ); var actual = att.GetValueFromResponse(new ObjectResult(container)); @@ -91,7 +91,7 @@ namespace Umbraco.Tests.Web.Controllers ActionBrowse.ActionLetter, userService, entityService, - Mock.Of() ); + Mock.Of() ); var path = ""; for (var i = 0; i < 10; i++) @@ -139,7 +139,7 @@ namespace Umbraco.Tests.Web.Controllers ActionBrowse.ActionLetter, userService, Mock.Of(), - Mock.Of() ); + Mock.Of() ); att.FilterBasedOnPermissions(list, user); Assert.AreEqual(3, list.Count); diff --git a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs index ee2d5f3eab..b8c49456c0 100644 --- a/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs +++ b/src/Umbraco.Tests.UnitTests/Umbraco.Web.Website/Controllers/SurfaceControllerTests.cs @@ -39,8 +39,8 @@ namespace Umbraco.Tests.Integration { var httpContextAccessor = Mock.Of(); var hostingEnvironment = Mock.Of(); - var backofficeSecurityAccessor = Mock.Of(); - Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackofficeSecurity).Returns(Mock.Of()); + var backofficeSecurityAccessor = Mock.Of(); + Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var globalSettings = new GlobalSettings(); var umbracoContextFactory = new UmbracoContextFactory( @@ -75,8 +75,8 @@ namespace Umbraco.Tests.Integration var globalSettings = new GlobalSettings(); var httpContextAccessor = Mock.Of(); var hostingEnvironment = Mock.Of(); - var backofficeSecurityAccessor = Mock.Of(); - Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackofficeSecurity).Returns(Mock.Of()); + var backofficeSecurityAccessor = Mock.Of(); + Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var umbracoContextFactory = new UmbracoContextFactory( _umbracoContextAccessor, Mock.Of(), @@ -108,8 +108,8 @@ namespace Umbraco.Tests.Integration publishedSnapshot.Setup(x => x.Members).Returns(Mock.Of()); var content = new Mock(); content.Setup(x => x.Id).Returns(2); - var backofficeSecurityAccessor = Mock.Of(); - Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackofficeSecurity).Returns(Mock.Of()); + var backofficeSecurityAccessor = Mock.Of(); + Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var publishedSnapshotService = new Mock(); var httpContextAccessor = Mock.Of(); var hostingEnvironment = Mock.Of(); @@ -151,8 +151,8 @@ namespace Umbraco.Tests.Integration var globalSettings = new GlobalSettings(); var httpContextAccessor = Mock.Of(); var hostingEnvironment = Mock.Of(); - var backofficeSecurityAccessor = Mock.Of(); - Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackofficeSecurity).Returns(Mock.Of()); + var backofficeSecurityAccessor = Mock.Of(); + Mock.Get(backofficeSecurityAccessor).Setup(x => x.BackOfficeSecurity).Returns(Mock.Of()); var umbracoContextFactory = new UmbracoContextFactory( _umbracoContextAccessor, Mock.Of(), diff --git a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs index 75e4d1cfd2..2f93fa2739 100644 --- a/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs +++ b/src/Umbraco.Tests/Cache/PublishedCache/PublishedContentCacheTests.cs @@ -81,7 +81,7 @@ namespace Umbraco.Tests.Cache.PublishedCache _umbracoContext = new UmbracoContext( httpContextAccessor, publishedSnapshotService.Object, - Mock.Of(), + Mock.Of(), globalSettings, HostingEnvironment, new TestVariationContextAccessor(), diff --git a/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs b/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs index 92e17ec9cd..e1b96b9a73 100644 --- a/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs +++ b/src/Umbraco.Tests/PublishedContent/PublishedContentSnapshotTestBase.cs @@ -76,7 +76,7 @@ namespace Umbraco.Tests.PublishedContent var umbracoContext = new UmbracoContext( httpContextAccessor, publishedSnapshotService.Object, - Mock.Of(), + Mock.Of(), globalSettings, HostingEnvironment, new TestVariationContextAccessor(), diff --git a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs index 68e1c4a2e2..cf0285f907 100644 --- a/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopedNuCacheTests.cs @@ -118,7 +118,7 @@ namespace Umbraco.Tests.Scoping var umbracoContext = new UmbracoContext( httpContextAccessor, service, - Mock.Of(), + Mock.Of(), globalSettings, HostingEnvironment, new TestVariationContextAccessor(), diff --git a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs index 379c176099..8eb98ac655 100644 --- a/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs +++ b/src/Umbraco.Tests/TestHelpers/ControllerTesting/TestControllerActivatorBase.cs @@ -95,7 +95,7 @@ namespace Umbraco.Tests.TestHelpers.ControllerTesting var backofficeIdentity = (UmbracoBackOfficeIdentity) owinContext.Authentication.User.Identity; - var backofficeSecurity = new Mock(); + var backofficeSecurity = new Mock(); //mock CurrentUser var groups = new List(); diff --git a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs index 7d565d70b2..fd832f94fa 100644 --- a/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs +++ b/src/Umbraco.Tests/TestHelpers/TestWithDatabaseBase.cs @@ -374,7 +374,7 @@ namespace Umbraco.Tests.TestHelpers var umbracoContext = new UmbracoContext( httpContextAccessor, service, - Mock.Of(), + Mock.Of(), globalSettings ?? new GlobalSettings(), HostingEnvironment, new TestVariationContextAccessor(), diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index 347545068c..9d156ca722 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -329,7 +329,7 @@ namespace Umbraco.Tests.Testing Composition.RegisterUnique(); Composition.RegisterUnique(); - Composition.RegisterUnique(); + Composition.RegisterUnique(); Composition.RegisterUnique(); Composition.RegisterUnique(); Composition.RegisterUnique(); diff --git a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs index c7ab297076..44cb4fe300 100644 --- a/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs +++ b/src/Umbraco.Tests/Web/Mvc/UmbracoViewPageTests.cs @@ -437,7 +437,7 @@ namespace Umbraco.Tests.Web.Mvc var ctx = new UmbracoContext( httpContextAccessor, _service, - Mock.Of(), + Mock.Of(), globalSettings, HostingEnvironment, new TestVariationContextAccessor(), diff --git a/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs b/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs index 0e5b963d9f..a588e09ea6 100644 --- a/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs +++ b/src/Umbraco.Tests/Web/WebExtensionMethodTests.cs @@ -32,7 +32,7 @@ namespace Umbraco.Tests.Web var umbCtx = new UmbracoContext( httpContextAccessor, Mock.Of(), - Mock.Of(), + Mock.Of(), TestObjects.GetGlobalSettings(), HostingEnvironment, new TestVariationContextAccessor(), @@ -53,7 +53,7 @@ namespace Umbraco.Tests.Web var umbCtx = new UmbracoContext( httpContextAccessor, Mock.Of(), - Mock.Of(), + Mock.Of(), TestObjects.GetGlobalSettings(), HostingEnvironment, new TestVariationContextAccessor(), @@ -84,7 +84,7 @@ namespace Umbraco.Tests.Web var umbCtx = new UmbracoContext( httpContextAccessor, Mock.Of(), - Mock.Of(), + Mock.Of(), TestObjects.GetGlobalSettings(), HostingEnvironment, new TestVariationContextAccessor(), diff --git a/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs b/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs index fa95733440..d96efb6005 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/AuthenticationController.cs @@ -47,7 +47,7 @@ namespace Umbraco.Web.BackOffice.Controllers [IsBackOffice] // TODO: This could be applied with our Application Model conventions public class AuthenticationController : UmbracoApiControllerBase { - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IBackOfficeUserManager _userManager; private readonly BackOfficeSignInManager _signInManager; private readonly IUserService _userService; @@ -68,7 +68,7 @@ namespace Umbraco.Web.BackOffice.Controllers // TODO: We need to review all _userManager.Raise calls since many/most should be on the usermanager or signinmanager, very few should be here public AuthenticationController( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IBackOfficeUserManager backOfficeUserManager, BackOfficeSignInManager signInManager, IUserService userService, @@ -110,7 +110,7 @@ namespace Umbraco.Web.BackOffice.Controllers [UmbracoAuthorize] public IDictionary GetPasswordConfig(int userId) { - return _passwordConfiguration.GetConfiguration(userId != _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + return _passwordConfiguration.GetConfiguration(userId != _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); } /// @@ -202,7 +202,7 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] public bool IsAuthenticated() { - var attempt = _backofficeSecurityAccessor.BackofficeSecurity.AuthorizeRequest(); + var attempt = _backofficeSecurityAccessor.BackOfficeSecurity.AuthorizeRequest(); if (attempt == ValidateRequestAttempt.Success) { return true; @@ -224,7 +224,7 @@ namespace Umbraco.Web.BackOffice.Controllers //[CheckIfUserTicketDataIsStale] // TODO: Migrate this, though it will need to be done differently at the cookie auth level public UserDetail GetCurrentUser() { - var user = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var result = _umbracoMapper.Map(user); //set their remaining seconds @@ -245,7 +245,7 @@ namespace Umbraco.Web.BackOffice.Controllers [SetAngularAntiForgeryTokens] public ActionResult GetCurrentInvitedUser() { - var user = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; if (user.IsApproved) { diff --git a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs index 7a8adca44f..0fcca3ae8d 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/BackOfficeController.cs @@ -26,9 +26,10 @@ using Umbraco.Web.Common.Attributes; using Umbraco.Web.Common.Filters; using Umbraco.Web.Common.Security; using Umbraco.Web.Models; -using Umbraco.Web.Security; using Umbraco.Web.WebAssets; using Constants = Umbraco.Core.Constants; +using Microsoft.AspNetCore.Identity; +using System.Security.Claims; namespace Umbraco.Web.BackOffice.Controllers { @@ -46,9 +47,10 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly BackOfficeServerVariables _backOfficeServerVariables; private readonly AppCaches _appCaches; private readonly BackOfficeSignInManager _signInManager; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly ILogger _logger; private readonly IJsonSerializer _jsonSerializer; + private readonly IExternalAuthenticationOptions _externalAuthenticationOptions; public BackOfficeController( IBackOfficeUserManager userManager, @@ -60,9 +62,10 @@ namespace Umbraco.Web.BackOffice.Controllers BackOfficeServerVariables backOfficeServerVariables, AppCaches appCaches, BackOfficeSignInManager signInManager, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILogger logger, - IJsonSerializer jsonSerializer) + IJsonSerializer jsonSerializer, + IExternalAuthenticationOptions externalAuthenticationOptions) { _userManager = userManager; _runtimeMinifier = runtimeMinifier; @@ -76,6 +79,7 @@ namespace Umbraco.Web.BackOffice.Controllers _backofficeSecurityAccessor = backofficeSecurityAccessor; _logger = logger; _jsonSerializer = jsonSerializer; + _externalAuthenticationOptions = externalAuthenticationOptions; } [HttpGet] @@ -95,7 +99,7 @@ namespace Umbraco.Web.BackOffice.Controllers //if you are hitting VerifyInvite, you're already signed in as a different user, and the token is invalid //you'll exit on one of the return RedirectToAction(nameof(Default)) but you're still logged in so you just get //dumped at the default admin view with no detail - if (_backofficeSecurityAccessor.BackofficeSecurity.IsAuthenticated()) + if (_backofficeSecurityAccessor.BackOfficeSecurity.IsAuthenticated()) { await _signInManager.SignOutAsync(); } @@ -188,7 +192,7 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] public Dictionary> LocalizedText(string culture = null) { - var isAuthenticated = _backofficeSecurityAccessor.BackofficeSecurity.IsAuthenticated(); + var isAuthenticated = _backofficeSecurityAccessor.BackOfficeSecurity.IsAuthenticated(); var cultureInfo = string.IsNullOrWhiteSpace(culture) //if the user is logged in, get their culture, otherwise default to 'en' @@ -247,6 +251,33 @@ namespace Umbraco.Web.BackOffice.Controllers return new JavaScriptResult(result); } + [HttpPost] + public ActionResult ExternalLogin(string provider, string redirectUrl = null) + { + if (redirectUrl == null) + { + redirectUrl = Url.Action("Default", "BackOffice"); + } + + var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); + return Challenge(properties, provider); + } + + /// + /// Called when a user links an external login provider in the back office + /// + /// + /// + [UmbracoAuthorize] + [HttpPost] + public ActionResult LinkLogin(string provider) + { + // Request a redirect to the external login provider to link a login for the current user + var redirectUrl = Url.Action("ExternalLinkLoginCallback", "BackOffice"); + var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.Identity.GetUserId()); + return Challenge(properties, provider); + } + [HttpGet] public async Task ValidatePasswordResetCode([Bind(Prefix = "u")]int userId, [Bind(Prefix = "r")]string resetCode) { @@ -267,12 +298,52 @@ namespace Umbraco.Web.BackOffice.Controllers return RedirectToLocal(Url.Action("Default", "BackOffice")); } + /// + /// Callback path when the user initiates a link login request from the back office to the external provider from the action + /// + [UmbracoAuthorize] + [HttpGet] + public async Task ExternalLinkLoginCallback() + { + var loginInfo = await _signInManager.GetExternalLoginInfoAsync(); + + if (loginInfo == null) + { + //Add error and redirect for it to be displayed + TempData[ViewDataExtensions.TokenExternalSignInError] = new[] { "An error occurred, could not get external login info" }; + return RedirectToLocal(Url.Action("Default", "BackOffice")); + } + + var user = await _userManager.FindByIdAsync(User.Identity.GetUserId()); + if (user == null) + { + // ... this should really not happen + TempData[ViewDataExtensions.TokenExternalSignInError] = new[] { "Local user does not exist" }; + return RedirectToLocal(Url.Action("Default", "BackOffice")); + } + + var result2 = await _userManager.AddLoginAsync(user, loginInfo); + if (result2.Succeeded) + { + // Update any authentication tokens if login succeeded + // TODO: This is a new thing that we need to implement and because we can store data with the external login now, this is exactly + // what this is for but we'll need to peek under the code here to figure out exactly what goes on. + //await _signInManager.UpdateExternalAuthenticationTokensAsync(loginInfo); + + return RedirectToLocal(Url.Action("Default", "BackOffice")); + } + + //Add errors and redirect for it to be displayed + TempData[ViewDataExtensions.TokenExternalSignInError] = result2.Errors; + return RedirectToLocal(Url.Action("Default", "BackOffice")); + } + /// /// Used by Default and AuthorizeUpgrade to render as per normal if there's no external login info, /// otherwise process the external login info. /// /// - private Task RenderDefaultOrProcessExternalLoginAsync( + private async Task RenderDefaultOrProcessExternalLoginAsync( Func defaultResponse, Func externalSignInResponse) { @@ -284,25 +355,152 @@ namespace Umbraco.Web.BackOffice.Controllers //check if there is the TempData with the any token name specified, if so, assign to view bag and render the view if (ViewData.FromTempData(TempData, ViewDataExtensions.TokenExternalSignInError) || ViewData.FromTempData(TempData, ViewDataExtensions.TokenPasswordResetCode)) - return Task.FromResult(defaultResponse()); - - return Task.FromResult(defaultResponse()); + return defaultResponse(); //First check if there's external login info, if there's not proceed as normal - // TODO: Review this, not sure if this will work as expected until we integrate OAuth - // TODO: Do we pass in XsrfKey ? need to investigate how this all works now - //var loginInfo = await _signInManager.GetExternalLoginInfoAsync(); + var loginInfo = await _signInManager.GetExternalLoginInfoAsync(); + if (loginInfo == null || loginInfo.Principal == null) + { + return defaultResponse(); + } - //if (loginInfo == null || loginInfo.ExternalIdentity.IsAuthenticated == false) - //{ - // return defaultResponse(); - //} + //we're just logging in with an external source, not linking accounts + return await ExternalSignInAsync(loginInfo, externalSignInResponse); + } - ////we're just logging in with an external source, not linking accounts - //return await ExternalSignInAsync(loginInfo, externalSignInResponse); + private async Task ExternalSignInAsync(ExternalLoginInfo loginInfo, Func response) + { + if (loginInfo == null) throw new ArgumentNullException(nameof(loginInfo)); + if (response == null) throw new ArgumentNullException(nameof(response)); + ExternalSignInAutoLinkOptions autoLinkOptions = null; + + var authType = (await _signInManager.GetExternalAuthenticationSchemesAsync()) + .FirstOrDefault(x => x.Name == loginInfo.LoginProvider); + + if (authType == null) + { + _logger.LogWarning("Could not find external authentication provider registered: {LoginProvider}", loginInfo.LoginProvider); + } + else + { + autoLinkOptions = _externalAuthenticationOptions.Get(authType.Name); + } + + // Sign in the user with this external login provider if the user already has a login + + var user = await _userManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); + if (user != null) + { + // TODO: It might be worth keeping some of the claims associated with the ExternalLoginInfo, in which case we + // wouldn't necessarily sign the user in here with the standard login, instead we'd update the + // UseUmbracoBackOfficeExternalCookieAuthentication extension method to have the correct provider and claims factory, + // ticket format, etc.. to create our back office user including the claims assigned and in this method we'd just ensure + // that the ticket is created and stored and that the user is logged in. + + var shouldSignIn = true; + if (autoLinkOptions != null && autoLinkOptions.OnExternalLogin != null) + { + shouldSignIn = autoLinkOptions.OnExternalLogin(user, loginInfo); + if (shouldSignIn == false) + { + _logger.LogWarning("The AutoLinkOptions of the external authentication provider '{LoginProvider}' have refused the login based on the OnExternalLogin method. Affected user id: '{UserId}'", loginInfo.LoginProvider, user.Id); + } + } + + if (shouldSignIn) + { + //sign in + await _signInManager.SignInAsync(user, false); + } + } + else + { + if (await AutoLinkAndSignInExternalAccount(loginInfo, autoLinkOptions) == false) + { + ViewData.SetExternalSignInError(new[] { "The requested provider (" + loginInfo.LoginProvider + ") has not been linked to an account" }); + } + + //Remove the cookie otherwise this message will keep appearing + Response.Cookies.Delete(Constants.Security.BackOfficeExternalCookieName); + } + + return response(); + } + + private async Task AutoLinkAndSignInExternalAccount(ExternalLoginInfo loginInfo, ExternalSignInAutoLinkOptions autoLinkOptions) + { + if (autoLinkOptions == null) + return false; + + if (autoLinkOptions.AutoLinkExternalAccount == false) + return true; // TODO: This seems weird to return true, but it was like that before so must be a reason? + + var email = loginInfo.Principal.FindFirstValue(ClaimTypes.Email); + + //we are allowing auto-linking/creating of local accounts + if (email.IsNullOrWhiteSpace()) + { + ViewData.SetExternalSignInError(new[] { $"The requested provider ({loginInfo.LoginProvider}) has not provided the email claim {ClaimTypes.Email}, the account cannot be linked." }); + } + else + { + //Now we need to perform the auto-link, so first we need to lookup/create a user with the email address + var autoLinkUser = await _userManager.FindByEmailAsync(email); + if (autoLinkUser != null) + { + // TODO This will be filled out with 8.9 changes + throw new NotImplementedException("Merge 8.9 changes in!"); + } + else + { + var name = loginInfo.Principal?.Identity?.Name; + + if (name.IsNullOrWhiteSpace()) throw new InvalidOperationException("The Name value cannot be null"); + + autoLinkUser = BackOfficeIdentityUser.CreateNew(_globalSettings, email, email, autoLinkOptions.GetUserAutoLinkCulture(_globalSettings), name); + + foreach (var userGroup in autoLinkOptions.DefaultUserGroups) + { + autoLinkUser.AddRole(userGroup); + } + + //call the callback if one is assigned + autoLinkOptions.OnAutoLinking?.Invoke(autoLinkUser, loginInfo); + + var userCreationResult = await _userManager.CreateAsync(autoLinkUser); + + if (userCreationResult.Succeeded == false) + { + ViewData.SetExternalSignInError(userCreationResult.Errors.Select(x => x.Description).ToList()); + } + else + { + var linkResult = await _userManager.AddLoginAsync(autoLinkUser, loginInfo); + if (linkResult.Succeeded == false) + { + ViewData.SetExternalSignInError(linkResult.Errors.Select(x => x.Description).ToList()); + + //If this fails, we should really delete the user since it will be in an inconsistent state! + var deleteResult = await _userManager.DeleteAsync(autoLinkUser); + if (deleteResult.Succeeded == false) + { + //DOH! ... this isn't good, combine all errors to be shown + ViewData.SetExternalSignInError(linkResult.Errors.Concat(deleteResult.Errors).Select(x => x.Description).ToList()); + } + } + else + { + //sign in + await _signInManager.SignInAsync(autoLinkUser, isPersistent: false); + } + } + } + } + return true; } // Used for XSRF protection when adding external logins + // TODO: This is duplicated in BackOfficeSignInManager private const string XsrfKey = "XsrfId"; private IActionResult RedirectToLocal(string returnUrl) diff --git a/src/Umbraco.Web.BackOffice/Controllers/ContentController.cs b/src/Umbraco.Web.BackOffice/Controllers/ContentController.cs index 96f0689b52..58242851bd 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ContentController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ContentController.cs @@ -56,7 +56,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IContentService _contentService; private readonly ILocalizedTextService _localizedTextService; private readonly IUserService _userService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IEntityService _entityService; private readonly IContentTypeService _contentTypeService; private readonly UmbracoMapper _umbracoMapper; @@ -85,7 +85,7 @@ namespace Umbraco.Web.BackOffice.Controllers PropertyEditorCollection propertyEditors, IContentService contentService, IUserService userService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IContentTypeService contentTypeService, UmbracoMapper umbracoMapper, @@ -430,7 +430,7 @@ namespace Umbraco.Web.BackOffice.Controllers private ContentItemDisplay GetEmpty(IContentType contentType, int parentId) { - var emptyContent = _contentService.Create("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var emptyContent = _contentService.Create("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); var mapped = MapToDisplay(emptyContent); // translate the content type name if applicable mapped.ContentTypeName = _localizedTextService.UmbracoDictionaryTranslate(CultureDictionary, mapped.ContentTypeName); @@ -599,9 +599,9 @@ namespace Umbraco.Web.BackOffice.Controllers EnsureUniqueName(name, content, nameof(name)); - var blueprint = _contentService.CreateContentFromBlueprint(content, name, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var blueprint = _contentService.CreateContentFromBlueprint(content, name, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); - _contentService.SaveBlueprint(blueprint, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + _contentService.SaveBlueprint(blueprint, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); var notificationModel = new SimpleNotificationModel(); notificationModel.AddSuccessNotification( @@ -635,7 +635,7 @@ namespace Umbraco.Web.BackOffice.Controllers { EnsureUniqueName(content.Name, content, "Name"); - _contentService.SaveBlueprint(contentItem.PersistedContent, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _contentService.SaveBlueprint(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); //we need to reuse the underlying logic so return the result that it wants return OperationResult.Succeed(new EventMessages()); }, @@ -660,7 +660,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var contentItemDisplay = PostSaveInternal( contentItem, - content => _contentService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id), + content => _contentService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id), MapToDisplay); return contentItemDisplay; @@ -762,7 +762,7 @@ namespace Umbraco.Web.BackOffice.Controllers case ContentSaveAction.SendPublish: case ContentSaveAction.SendPublishNew: - var sendResult = _contentService.SendToPublication(contentItem.PersistedContent, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var sendResult = _contentService.SendToPublication(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); wasCancelled = sendResult == false; if (sendResult) { @@ -1206,7 +1206,7 @@ namespace Umbraco.Web.BackOffice.Controllers //if this item's path has already been denied or if the user doesn't have access to it, add to the deny list if (denied.Any(x => c.Path.StartsWith($"{x.Path},")) || (ContentPermissionsHelper.CheckPermissions(c, - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, _userService, _entityService, + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, _userService, _entityService, ActionPublish.ActionLetter) == ContentPermissionsHelper.ContentAccess.Denied)) { denied.Add(c); @@ -1223,7 +1223,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (!contentItem.PersistedContent.ContentType.VariesByCulture()) { //its invariant, proceed normally - var publishStatus = _contentService.SaveAndPublishBranch(contentItem.PersistedContent, force, userId: _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var publishStatus = _contentService.SaveAndPublishBranch(contentItem.PersistedContent, force, userId: _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); // TODO: Deal with multiple cancellations wasCancelled = publishStatus.Any(x => x.Result == PublishResultType.FailedPublishCancelledByEvent); successfulCultures = null; //must be null! this implies invariant @@ -1258,7 +1258,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (canPublish) { //proceed to publish if all validation still succeeds - var publishStatus = _contentService.SaveAndPublishBranch(contentItem.PersistedContent, force, culturesToPublish, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var publishStatus = _contentService.SaveAndPublishBranch(contentItem.PersistedContent, force, culturesToPublish, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); // TODO: Deal with multiple cancellations wasCancelled = publishStatus.Any(x => x.Result == PublishResultType.FailedPublishCancelledByEvent); successfulCultures = contentItem.Variants.Where(x => x.Publish).Select(x => x.Culture).ToArray(); @@ -1267,7 +1267,7 @@ namespace Umbraco.Web.BackOffice.Controllers else { //can only save - var saveResult = _contentService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var saveResult = _contentService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); var publishStatus = new[] { new PublishResult(PublishResultType.FailedPublishMandatoryCultureMissing, null, contentItem.PersistedContent) @@ -1295,7 +1295,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (!contentItem.PersistedContent.ContentType.VariesByCulture()) { //its invariant, proceed normally - var publishStatus = _contentService.SaveAndPublish(contentItem.PersistedContent, userId: _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var publishStatus = _contentService.SaveAndPublish(contentItem.PersistedContent, userId: _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); wasCancelled = publishStatus.Result == PublishResultType.FailedPublishCancelledByEvent; successfulCultures = null; //must be null! this implies invariant return publishStatus; @@ -1340,7 +1340,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (canPublish) { //proceed to publish if all validation still succeeds - var publishStatus = _contentService.SaveAndPublish(contentItem.PersistedContent, culturesToPublish, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var publishStatus = _contentService.SaveAndPublish(contentItem.PersistedContent, culturesToPublish, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); wasCancelled = publishStatus.Result == PublishResultType.FailedPublishCancelledByEvent; successfulCultures = culturesToPublish; return publishStatus; @@ -1348,7 +1348,7 @@ namespace Umbraco.Web.BackOffice.Controllers else { //can only save - var saveResult = _contentService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var saveResult = _contentService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); var publishStatus = new PublishResult(PublishResultType.FailedPublishMandatoryCultureMissing, null, contentItem.PersistedContent); wasCancelled = saveResult.Result == OperationResultType.FailedCancelledByEvent; successfulCultures = Array.Empty(); @@ -1503,7 +1503,7 @@ namespace Umbraco.Web.BackOffice.Controllers return HandleContentNotFound(id, false); } - var publishResult = _contentService.SaveAndPublish(foundContent, userId: _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var publishResult = _contentService.SaveAndPublish(foundContent, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); if (publishResult.Success == false) { var notificationModel = new SimpleNotificationModel(); @@ -1555,7 +1555,7 @@ namespace Umbraco.Web.BackOffice.Controllers //if the current item is in the recycle bin if (foundContent.Trashed == false) { - var moveResult = _contentService.MoveToRecycleBin(foundContent, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var moveResult = _contentService.MoveToRecycleBin(foundContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); if (moveResult.Success == false) { //returning an object of INotificationModel will ensure that any pending @@ -1565,7 +1565,7 @@ namespace Umbraco.Web.BackOffice.Controllers } else { - var deleteResult = _contentService.Delete(foundContent, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var deleteResult = _contentService.Delete(foundContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); if (deleteResult.Success == false) { //returning an object of INotificationModel will ensure that any pending @@ -1589,7 +1589,7 @@ namespace Umbraco.Web.BackOffice.Controllers [EnsureUserPermissionForContent(Constants.System.RecycleBinContent, ActionDelete.ActionLetter)] public IActionResult EmptyRecycleBin() { - _contentService.EmptyRecycleBin(_backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); + _contentService.EmptyRecycleBin(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); return new UmbracoNotificationSuccessResponse(_localizedTextService.Localize("defaultdialogs/recycleBinIsEmpty")); } @@ -1618,7 +1618,7 @@ namespace Umbraco.Web.BackOffice.Controllers var contentService = _contentService; // Save content with new sort order and update content xml in db accordingly - var sortResult = contentService.Sort(sorted.IdSortOrder, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var sortResult = contentService.Sort(sorted.IdSortOrder, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); if (!sortResult.Success) { _logger.LogWarning("Content sorting failed, this was probably caused by an event being cancelled"); @@ -1645,7 +1645,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var toMove = ValidateMoveOrCopy(move); - _contentService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + _contentService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); return Content(toMove.Path, MediaTypeNames.Text.Plain, Encoding.UTF8); } @@ -1660,7 +1660,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var toCopy = ValidateMoveOrCopy(copy); - var c = _contentService.Copy(toCopy, copy.ParentId, copy.RelateToOriginal, copy.Recursive, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var c = _contentService.Copy(toCopy, copy.ParentId, copy.RelateToOriginal, copy.Recursive, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); return Content(c.Path, MediaTypeNames.Text.Plain, Encoding.UTF8); } @@ -1683,7 +1683,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (model.Cultures.Length == 0 || model.Cultures.Length == languageCount) { //this means that the entire content item will be unpublished - var unpublishResult = _contentService.Unpublish(foundContent, userId: _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var unpublishResult = _contentService.Unpublish(foundContent, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); var content = MapToDisplay(foundContent); @@ -1706,7 +1706,7 @@ namespace Umbraco.Web.BackOffice.Controllers var results = new Dictionary(); foreach (var c in model.Cultures) { - var result = _contentService.Unpublish(foundContent, culture: c, userId: _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var result = _contentService.Unpublish(foundContent, culture: c, userId: _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); results[c] = result; if (result.Result == PublishResultType.SuccessUnpublishMandatoryCulture) { @@ -1774,7 +1774,7 @@ namespace Umbraco.Web.BackOffice.Controllers return NotFound("There is no content node with id {model.NodeId}."); } - var permission = _userService.GetPermissions(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, node.Path); + var permission = _userService.GetPermissions(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, node.Path); if (permission.AssignedPermissions.Contains(ActionAssignDomain.ActionLetter.ToString(), StringComparer.Ordinal) == false) @@ -2262,7 +2262,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var display = _umbracoMapper.Map(content, context => { - context.Items["CurrentUser"] = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + context.Items["CurrentUser"] = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; }); display.AllowPreview = display.AllowPreview && content.Trashed == false && content.ContentType.IsElement == false; return display; @@ -2277,7 +2277,7 @@ namespace Umbraco.Web.BackOffice.Controllers var content = _contentService.GetById(contentId); if (content == null) return NotFound(); - var userNotifications = _notificationService.GetUserNotifications(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, content.Path).ToList(); + var userNotifications = _notificationService.GetUserNotifications(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, content.Path).ToList(); foreach (var a in _actionCollection.Where(x => x.ShowInNotifier)) { @@ -2299,7 +2299,7 @@ namespace Umbraco.Web.BackOffice.Controllers var content = _contentService.GetById(contentId); if (content == null) return NotFound(); - _notificationService.SetNotifications(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, content, notifyOptions); + _notificationService.SetNotifications(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, content, notifyOptions); return NoContent(); } @@ -2364,7 +2364,7 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpPost] public IActionResult PostRollbackContent(int contentId, int versionId, string culture = "*") { - var rollbackResult = _contentService.Rollback(contentId, versionId, culture, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var rollbackResult = _contentService.Rollback(contentId, versionId, culture, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); if (rollbackResult.Success) return Ok(); diff --git a/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs index 6d15333abd..06f1cc37a4 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/ContentTypeController.cs @@ -57,7 +57,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IIOHelper _ioHelper; private readonly IContentTypeService _contentTypeService; private readonly UmbracoMapper _umbracoMapper; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IDataTypeService _dataTypeService; private readonly IShortStringHelper _shortStringHelper; private readonly ILocalizedTextService _localizedTextService; @@ -83,7 +83,7 @@ namespace Umbraco.Web.BackOffice.Controllers PropertyEditorCollection propertyEditors, IScopeProvider scopeProvider, IIOHelper ioHelper, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IDataTypeService dataTypeService, IShortStringHelper shortStringHelper, IFileService fileService, @@ -211,7 +211,7 @@ namespace Umbraco.Web.BackOffice.Controllers throw new HttpResponseException(HttpStatusCode.NotFound); } - _contentTypeService.Delete(foundType, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _contentTypeService.Delete(foundType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return Ok(); } @@ -310,14 +310,14 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpPost] public IActionResult DeleteContainer(int id) { - _contentTypeService.DeleteContainer(id, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _contentTypeService.DeleteContainer(id, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return Ok(); } public IActionResult PostCreateContainer(int parentId, string name) { - var result = _contentTypeService.CreateContainer(parentId, name, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var result = _contentTypeService.CreateContainer(parentId, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return result ? Ok(result.Result) //return the id @@ -326,7 +326,7 @@ namespace Umbraco.Web.BackOffice.Controllers public IActionResult PostRenameContainer(int id, string name) { - var result = _contentTypeService.RenameContainer(id, name, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var result = _contentTypeService.RenameContainer(id, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return result ? Ok(result.Result) //return the id @@ -626,7 +626,7 @@ namespace Umbraco.Web.BackOffice.Controllers var xd = new XmlDocument {XmlResolver = null}; xd.Load(filePath); - var userId = _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0); + var userId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0); var element = XElement.Parse(xd.InnerXml); dataInstaller.ImportDocumentType(element, userId); diff --git a/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs b/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs index 8efe13782a..a394428606 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/CurrentUserController.cs @@ -40,7 +40,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly ContentSettings _contentSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IImageUrlGenerator _imageUrlGenerator; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IUserService _userService; private readonly UmbracoMapper _umbracoMapper; private readonly IBackOfficeUserManager _backOfficeUserManager; @@ -54,7 +54,7 @@ namespace Umbraco.Web.BackOffice.Controllers IOptions contentSettings, IHostingEnvironment hostingEnvironment, IImageUrlGenerator imageUrlGenerator, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IUserService userService, UmbracoMapper umbracoMapper, IBackOfficeUserManager backOfficeUserManager, @@ -87,7 +87,7 @@ namespace Umbraco.Web.BackOffice.Controllers public Dictionary GetPermissions(int[] nodeIds) { var permissions = _userService - .GetPermissions(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, nodeIds); + .GetPermissions(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, nodeIds); var permissionsDictionary = new Dictionary(); foreach (var nodeId in nodeIds) @@ -108,7 +108,7 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] public bool HasPermission(string permissionToCheck, int nodeId) { - var p = _userService.GetPermissions(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, nodeId).GetAllPermissions(); + var p = _userService.GetPermissions(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, nodeId).GetAllPermissions(); if (p.Contains(permissionToCheck.ToString(CultureInfo.InvariantCulture))) { return true; @@ -127,15 +127,15 @@ namespace Umbraco.Web.BackOffice.Controllers if (status == null) throw new ArgumentNullException(nameof(status)); List userTours; - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.TourData.IsNullOrWhiteSpace()) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData.IsNullOrWhiteSpace()) { userTours = new List { status }; - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.TourData = JsonConvert.SerializeObject(userTours); - _userService.Save(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser); + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData = JsonConvert.SerializeObject(userTours); + _userService.Save(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser); return userTours; } - userTours = JsonConvert.DeserializeObject>(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.TourData).ToList(); + userTours = JsonConvert.DeserializeObject>(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData).ToList(); var found = userTours.FirstOrDefault(x => x.Alias == status.Alias); if (found != null) { @@ -143,8 +143,8 @@ namespace Umbraco.Web.BackOffice.Controllers userTours.Remove(found); } userTours.Add(status); - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.TourData = JsonConvert.SerializeObject(userTours); - _userService.Save(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser); + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData = JsonConvert.SerializeObject(userTours); + _userService.Save(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser); return userTours; } @@ -154,10 +154,10 @@ namespace Umbraco.Web.BackOffice.Controllers /// public IEnumerable GetUserTours() { - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.TourData.IsNullOrWhiteSpace()) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData.IsNullOrWhiteSpace()) return Enumerable.Empty(); - var userTours = JsonConvert.DeserializeObject>(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.TourData); + var userTours = JsonConvert.DeserializeObject>(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.TourData); return userTours; } @@ -173,7 +173,7 @@ namespace Umbraco.Web.BackOffice.Controllers [UmbracoAuthorize(redirectToUmbracoLogin: false, requireApproval : true)] public async Task PostSetInvitedUserPassword([FromBody]string newPassword) { - var user = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0).ToString()); + var user = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0).ToString()); if (user == null) throw new InvalidOperationException("Could not find user"); var result = await _backOfficeUserManager.AddPasswordAsync(user, newPassword); @@ -188,13 +188,13 @@ namespace Umbraco.Web.BackOffice.Controllers } //They've successfully set their password, we can now update their user account to be approved - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsApproved = true; + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsApproved = true; //They've successfully set their password, and will now get fully logged into the back office, so the lastlogindate is set so the backoffice shows they have logged in - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.LastLoginDate = DateTime.UtcNow; - _userService.Save(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser); + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.LastLoginDate = DateTime.UtcNow; + _userService.Save(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser); //now we can return their full object since they are now really logged into the back office - var userDisplay = _umbracoMapper.Map(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser); + var userDisplay = _umbracoMapper.Map(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser); userDisplay.SecondsUntilTimeout = HttpContext.User.GetRemainingAuthSeconds(); return userDisplay; @@ -204,7 +204,7 @@ namespace Umbraco.Web.BackOffice.Controllers public async Task PostSetAvatar(IList files) { //borrow the logic from the user controller - return await UsersController.PostSetAvatarInternal(files, _userService, _appCaches.RuntimeCache, _mediaFileSystem, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + return await UsersController.PostSetAvatarInternal(files, _userService, _appCaches.RuntimeCache, _mediaFileSystem, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); } /// @@ -217,7 +217,7 @@ namespace Umbraco.Web.BackOffice.Controllers public async Task> PostChangePassword(ChangingPasswordModel data) { var passwordChanger = new PasswordChanger(_loggerFactory.CreateLogger()); - var passwordChangeResult = await passwordChanger.ChangePasswordWithIdentityAsync(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, data, _backOfficeUserManager); + var passwordChangeResult = await passwordChanger.ChangePasswordWithIdentityAsync(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, data, _backOfficeUserManager); if (passwordChangeResult.Success) { @@ -239,7 +239,7 @@ namespace Umbraco.Web.BackOffice.Controllers [ValidateAngularAntiForgeryToken] public async Task> GetCurrentUserLinkedLogins() { - var identityUser = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0).ToString()); + var identityUser = await _backOfficeUserManager.FindByIdAsync(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0).ToString()); return identityUser.Logins.ToDictionary(x => x.LoginProvider, x => x.ProviderKey); } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs b/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs index dded7dad30..785264d816 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/DictionaryController.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Controllers { private readonly ILogger _logger; private readonly ILocalizationService _localizationService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly GlobalSettings _globalSettings; private readonly ILocalizedTextService _localizedTextService; private readonly UmbracoMapper _umbracoMapper; @@ -43,7 +43,7 @@ namespace Umbraco.Web.BackOffice.Controllers public DictionaryController( ILogger logger, ILocalizationService localizationService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IOptions globalSettings, ILocalizedTextService localizedTextService, UmbracoMapper umbracoMapper @@ -75,10 +75,10 @@ namespace Umbraco.Web.BackOffice.Controllers foreach (var dictionaryItem in foundDictionaryDescendants) { - _localizationService.Delete(dictionaryItem, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _localizationService.Delete(dictionaryItem, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); } - _localizationService.Delete(foundDictionary, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _localizationService.Delete(foundDictionary, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return Ok(); } @@ -105,7 +105,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var message = _localizedTextService.Localize( "dictionaryItem/changeKeyError", - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.GetUserCulture(_localizedTextService, _globalSettings), + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetUserCulture(_localizedTextService, _globalSettings), new Dictionary { { "0", key } }); throw HttpResponseException.CreateNotificationValidationErrorResponse(message); } @@ -219,7 +219,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (dictionaryItem == null) throw HttpResponseException.CreateNotificationValidationErrorResponse("Dictionary item does not exist"); - var userCulture = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.GetUserCulture(_localizedTextService, _globalSettings); + var userCulture = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetUserCulture(_localizedTextService, _globalSettings); if (dictionary.NameIsDirty) { diff --git a/src/Umbraco.Web.BackOffice/Controllers/EntityController.cs b/src/Umbraco.Web.BackOffice/Controllers/EntityController.cs index 35d9c51cd4..5b104d2f9b 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/EntityController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/EntityController.cs @@ -54,7 +54,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IPublishedContentQuery _publishedContentQuery; private readonly IShortStringHelper _shortStringHelper; private readonly IEntityService _entityService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IPublishedUrlProvider _publishedUrlProvider; private readonly IContentService _contentService; private readonly UmbracoMapper _umbracoMapper; @@ -75,7 +75,7 @@ namespace Umbraco.Web.BackOffice.Controllers IPublishedContentQuery publishedContentQuery, IShortStringHelper shortStringHelper, IEntityService entityService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IPublishedUrlProvider publishedUrlProvider, IContentService contentService, UmbracoMapper umbracoMapper, @@ -176,7 +176,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (string.IsNullOrEmpty(query)) return result; - var allowedSections = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.AllowedSections.ToArray(); + var allowedSections = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.AllowedSections.ToArray(); foreach (var searchableTree in _searchableTreeCollection.SearchableApplicationTrees.OrderBy(t => t.Value.SortOrder)) { @@ -722,9 +722,9 @@ namespace Umbraco.Web.BackOffice.Controllers switch (type) { case UmbracoEntityTypes.Document: - return _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService); + return _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService); case UmbracoEntityTypes.Media: - return _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService); + return _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService); default: return Array.Empty(); } @@ -863,10 +863,10 @@ namespace Umbraco.Web.BackOffice.Controllers switch (entityType) { case UmbracoEntityTypes.Document: - aids = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService); + aids = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService); break; case UmbracoEntityTypes.Media: - aids = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService); + aids = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService); break; } diff --git a/src/Umbraco.Web.BackOffice/Controllers/LogController.cs b/src/Umbraco.Web.BackOffice/Controllers/LogController.cs index 7dd2b1af44..4d816624de 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/LogController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/LogController.cs @@ -27,7 +27,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IImageUrlGenerator _imageUrlGenerator; private readonly IAuditService _auditService; private readonly UmbracoMapper _umbracoMapper; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IUserService _userService; private readonly AppCaches _appCaches; private readonly ISqlContext _sqlContext; @@ -37,7 +37,7 @@ namespace Umbraco.Web.BackOffice.Controllers IImageUrlGenerator imageUrlGenerator, IAuditService auditService, UmbracoMapper umbracoMapper, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IUserService userService, AppCaches appCaches, ISqlContext sqlContext) @@ -90,7 +90,7 @@ namespace Umbraco.Web.BackOffice.Controllers long totalRecords; var dateQuery = sinceDate.HasValue ? _sqlContext.Query().Where(x => x.CreateDate >= sinceDate) : null; - var userId = _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0); + var userId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0); var result = _auditService.GetPagedItemsByUser(userId, pageNumber - 1, pageSize, out totalRecords, orderDirection, customFilter:dateQuery); var mapped = _umbracoMapper.MapEnumerable(result); return new PagedResult(totalRecords, pageNumber, pageSize) diff --git a/src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs b/src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs index 9b6878dcbe..e4ef90b30c 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs @@ -33,7 +33,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly ParameterEditorCollection _parameterEditorCollection; private readonly IMacroService _macroService; private readonly IShortStringHelper _shortStringHelper; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly ILogger _logger; private readonly IHostingEnvironment _hostingEnvironment; private readonly UmbracoMapper _umbracoMapper; @@ -42,7 +42,7 @@ namespace Umbraco.Web.BackOffice.Controllers ParameterEditorCollection parameterEditorCollection, IMacroService macroService, IShortStringHelper shortStringHelper, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILogger logger, IHostingEnvironment hostingEnvironment, UmbracoMapper umbracoMapper @@ -96,7 +96,7 @@ namespace Umbraco.Web.BackOffice.Controllers MacroSource = string.Empty }; - _macroService.Save(macro, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _macroService.Save(macro, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return macro.Id; } @@ -216,7 +216,7 @@ namespace Umbraco.Web.BackOffice.Controllers try { - _macroService.Save(macro, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _macroService.Save(macro, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); macroDisplay.Notifications.Clear(); diff --git a/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs b/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs index 5bf6798170..3e92747c21 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MediaController.cs @@ -56,7 +56,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IMediaTypeService _mediaTypeService; private readonly IMediaService _mediaService; private readonly IEntityService _entityService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly UmbracoMapper _umbracoMapper; private readonly IDataTypeService _dataTypeService; private readonly ILocalizedTextService _localizedTextService; @@ -76,7 +76,7 @@ namespace Umbraco.Web.BackOffice.Controllers IMediaTypeService mediaTypeService, IMediaService mediaService, IEntityService entityService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, UmbracoMapper umbracoMapper, IDataTypeService dataTypeService, ISqlContext sqlContext, @@ -122,7 +122,7 @@ namespace Umbraco.Web.BackOffice.Controllers throw new HttpResponseException(HttpStatusCode.NotFound); } - var emptyContent = _mediaService.CreateMedia("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); + var emptyContent = _mediaService.CreateMedia("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); var mapped = _umbracoMapper.Map(emptyContent); //remove the listview app if it exists @@ -284,7 +284,7 @@ namespace Umbraco.Web.BackOffice.Controllers protected int[] UserStartNodes { - get { return _userStartNodes ?? (_userStartNodes = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService)); } + get { return _userStartNodes ?? (_userStartNodes = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService)); } } /// @@ -441,7 +441,7 @@ namespace Umbraco.Web.BackOffice.Controllers //if the current item is in the recycle bin if (foundMedia.Trashed == false) { - var moveResult = _mediaService.MoveToRecycleBin(foundMedia, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); + var moveResult = _mediaService.MoveToRecycleBin(foundMedia, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); if (moveResult == false) { //returning an object of INotificationModel will ensure that any pending @@ -451,7 +451,7 @@ namespace Umbraco.Web.BackOffice.Controllers } else { - var deleteResult = _mediaService.Delete(foundMedia, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); + var deleteResult = _mediaService.Delete(foundMedia, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); if (deleteResult == false) { //returning an object of INotificationModel will ensure that any pending @@ -475,7 +475,7 @@ namespace Umbraco.Web.BackOffice.Controllers var destinationParentID = move.ParentId; var sourceParentID = toMove.ParentId; - var moveResult = _mediaService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); + var moveResult = _mediaService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); if (sourceParentID == destinationParentID) { @@ -549,7 +549,7 @@ namespace Umbraco.Web.BackOffice.Controllers } //save the item - var saveStatus = _mediaService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); + var saveStatus = _mediaService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); //return the updated model var display = _umbracoMapper.Map(contentItem.PersistedContent); @@ -595,7 +595,7 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpPost] public IActionResult EmptyRecycleBin() { - _mediaService.EmptyRecycleBin(_backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); + _mediaService.EmptyRecycleBin(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId)); return new UmbracoNotificationSuccessResponse(_localizedTextService.Localize("defaultdialogs/recycleBinIsEmpty")); } @@ -652,7 +652,7 @@ namespace Umbraco.Web.BackOffice.Controllers var mediaService = _mediaService; var f = mediaService.CreateMedia(folder.Name, parentId.Value, Constants.Conventions.MediaTypes.Folder); - mediaService.Save(f, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + mediaService.Save(f, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return _umbracoMapper.Map(f); } @@ -760,7 +760,7 @@ namespace Umbraco.Web.BackOffice.Controllers var mediaItemName = fileName.ToFriendlyName(); - var f = mediaService.CreateMedia(mediaItemName, parentId.Value, mediaType, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var f = mediaService.CreateMedia(mediaItemName, parentId.Value, mediaType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); await using (var stream = formFile.OpenReadStream()) @@ -769,7 +769,7 @@ namespace Umbraco.Web.BackOffice.Controllers } - var saveResult = mediaService.Save(f, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var saveResult = mediaService.Save(f, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); if (saveResult == false) { AddCancelMessage(tempFiles, @@ -862,7 +862,7 @@ namespace Umbraco.Web.BackOffice.Controllers //ensure the user has access to this folder by parent id! if (validatePermissions && CheckPermissions( new Dictionary(), - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, _mediaService, _entityService, intParentId) == false) diff --git a/src/Umbraco.Web.BackOffice/Controllers/MediaTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/MediaTypeController.cs index 31cc5d63cd..cd834e79fb 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MediaTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MediaTypeController.cs @@ -37,7 +37,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IMediaTypeService _mediaTypeService; private readonly IShortStringHelper _shortStringHelper; private readonly UmbracoMapper _umbracoMapper; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public MediaTypeController(ICultureDictionary cultureDictionary, EditorValidatorCollection editorValidatorCollection, @@ -49,7 +49,7 @@ namespace Umbraco.Web.BackOffice.Controllers IShortStringHelper shortStringHelper, IEntityService entityService, IMediaService mediaService, - IBackofficeSecurityAccessor backofficeSecurityAccessor) + IBackOfficeSecurityAccessor backofficeSecurityAccessor) : base( cultureDictionary, editorValidatorCollection, @@ -148,7 +148,7 @@ namespace Umbraco.Web.BackOffice.Controllers throw new HttpResponseException(HttpStatusCode.NotFound); } - _mediaTypeService.Delete(foundType, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _mediaTypeService.Delete(foundType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return Ok(); } @@ -242,14 +242,14 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpPost] public IActionResult DeleteContainer(int id) { - _mediaTypeService.DeleteContainer(id, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _mediaTypeService.DeleteContainer(id, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return Ok(); } public IActionResult PostCreateContainer(int parentId, string name) { - var result = _mediaTypeService.CreateContainer(parentId, name, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var result = _mediaTypeService.CreateContainer(parentId, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return result ? Ok(result.Result) //return the id @@ -258,7 +258,7 @@ namespace Umbraco.Web.BackOffice.Controllers public IActionResult PostRenameContainer(int id, string name) { - var result = _mediaTypeService.RenameContainer(id, name, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + var result = _mediaTypeService.RenameContainer(id, name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return result ? Ok(result.Result) //return the id diff --git a/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs b/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs index fd4d5c96cc..95baeb489b 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MemberController.cs @@ -54,7 +54,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IMemberTypeService _memberTypeService; private readonly IDataTypeService _dataTypeService; private readonly ILocalizedTextService _localizedTextService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IJsonSerializer _jsonSerializer; public MemberController( @@ -70,7 +70,7 @@ namespace Umbraco.Web.BackOffice.Controllers IMemberService memberService, IMemberTypeService memberTypeService, IDataTypeService dataTypeService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IJsonSerializer jsonSerializer) : base(cultureDictionary, loggerFactory, shortStringHelper, eventMessages, localizedTextService) { @@ -332,13 +332,13 @@ namespace Umbraco.Web.BackOffice.Controllers /// private void UpdateMemberData(MemberSave contentItem) { - contentItem.PersistedContent.WriterId = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id; + contentItem.PersistedContent.WriterId = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id; // If the user doesn't have access to sensitive values, then we need to check if any of the built in member property types // have been marked as sensitive. If that is the case we cannot change these persisted values no matter what value has been posted. // There's only 3 special ones we need to deal with that are part of the MemberSave instance: Comments, IsApproved, IsLockedOut // but we will take care of this in a generic way below so that it works for all props. - if (!_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.HasAccessToSensitiveData()) + if (!_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasAccessToSensitiveData()) { var memberType = _memberTypeService.Get(contentItem.PersistedContent.ContentTypeId); var sensitiveProperties = memberType @@ -464,7 +464,7 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpGet] public IActionResult ExportMemberData(Guid key) { - var currentUser = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var currentUser = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; if (currentUser.HasAccessToSensitiveData() == false) { diff --git a/src/Umbraco.Web.BackOffice/Controllers/MemberTypeController.cs b/src/Umbraco.Web.BackOffice/Controllers/MemberTypeController.cs index 69188e1636..3557680ab1 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/MemberTypeController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/MemberTypeController.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Controllers public class MemberTypeController : ContentTypeControllerBase { private readonly IMemberTypeService _memberTypeService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IShortStringHelper _shortStringHelper; private readonly UmbracoMapper _umbracoMapper; private readonly ILocalizedTextService _localizedTextService; @@ -48,7 +48,7 @@ namespace Umbraco.Web.BackOffice.Controllers IMemberTypeService memberTypeService, UmbracoMapper umbracoMapper, ILocalizedTextService localizedTextService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IShortStringHelper shortStringHelper) : base(cultureDictionary, editorValidatorCollection, @@ -143,7 +143,7 @@ namespace Umbraco.Web.BackOffice.Controllers throw new HttpResponseException(HttpStatusCode.NotFound); } - _memberTypeService.Delete(foundType, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + _memberTypeService.Delete(foundType, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); return Ok(); } @@ -203,7 +203,7 @@ namespace Umbraco.Web.BackOffice.Controllers var ctId = Convert.ToInt32(contentTypeSave.Id); var ct = ctId > 0 ? _memberTypeService.Get(ctId) : null; - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.HasAccessToSensitiveData() == false) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasAccessToSensitiveData() == false) { //We need to validate if any properties on the contentTypeSave have had their IsSensitiveValue changed, //and if so, we need to check if the current user has access to sensitive values. If not, we have to return an error diff --git a/src/Umbraco.Web.BackOffice/Controllers/PackageController.cs b/src/Umbraco.Web.BackOffice/Controllers/PackageController.cs index fa16288fb5..69d23d606b 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/PackageController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/PackageController.cs @@ -28,12 +28,12 @@ namespace Umbraco.Web.BackOffice.Controllers { private readonly IHostingEnvironment _hostingEnvironment; private readonly IPackagingService _packagingService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public PackageController( IHostingEnvironment hostingEnvironment, IPackagingService packagingService, - IBackofficeSecurityAccessor backofficeSecurityAccessor) + IBackOfficeSecurityAccessor backofficeSecurityAccessor) { _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment)); _packagingService = packagingService ?? throw new ArgumentNullException(nameof(packagingService)); @@ -91,7 +91,7 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpDelete] public IActionResult DeleteCreatedPackage(int packageId) { - _packagingService.DeleteCreatedPackage(packageId, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + _packagingService.DeleteCreatedPackage(packageId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); return Ok(); } diff --git a/src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs b/src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs index 4959ffe2aa..05631173c9 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs @@ -39,7 +39,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IRuntimeMinifier _runtimeMinifier; private readonly IPackagingService _packagingService; private readonly ILogger _logger; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly ILocalizedTextService _localizedTextService; public PackageInstallController( @@ -49,7 +49,7 @@ namespace Umbraco.Web.BackOffice.Controllers IRuntimeMinifier runtimeMinifier, IPackagingService packagingService, ILogger logger, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILocalizedTextService localizedTextService) { _umbracoVersion = umbracoVersion ?? throw new ArgumentNullException(nameof(umbracoVersion)); @@ -88,14 +88,14 @@ namespace Umbraco.Web.BackOffice.Controllers var package = _packagingService.GetInstalledPackageById(packageId); if (package == null) return NotFound(); - var summary = _packagingService.UninstallPackage(package.Name, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var summary = _packagingService.UninstallPackage(package.Name, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); //now get all other packages by this name since we'll uninstall all versions foreach (var installed in _packagingService.GetAllInstalledPackages() .Where(x => x.Name == package.Name && x.Id != package.Id)) { //remove from the xml - _packagingService.DeleteInstalledPackage(installed.Id, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + _packagingService.DeleteInstalledPackage(installed.Id, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); } } catch (Exception ex) @@ -224,7 +224,7 @@ namespace Umbraco.Web.BackOffice.Controllers var packageFile = await _packagingService.FetchPackageFileAsync( Guid.Parse(packageGuid), _umbracoVersion.Current, - _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); fileName = packageFile.Name; } @@ -311,7 +311,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (definition == null) throw new InvalidOperationException("Not package definition found with id " + model.Id); var zipFile = new FileInfo(definition.PackagePath); - var installedFiles = _packagingService.InstallCompiledPackageFiles(definition, zipFile, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var installedFiles = _packagingService.InstallCompiledPackageFiles(definition, zipFile, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); //set a restarting marker and reset the app pool _umbracoApplicationLifetime.Restart(); @@ -343,7 +343,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (definition == null) throw new InvalidOperationException("Not package definition found with id " + model.Id); var zipFile = new FileInfo(definition.PackagePath); - var installSummary = _packagingService.InstallCompiledPackageData(definition, zipFile, _backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var installSummary = _packagingService.InstallCompiledPackageData(definition, zipFile, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); return model; } diff --git a/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs b/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs index fb6d597d9e..defdd9f9df 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/PreviewController.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly UmbracoFeatures _features; private readonly GlobalSettings _globalSettings; private readonly IPublishedSnapshotService _publishedSnapshotService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly ILocalizationService _localizationService; private readonly IHostingEnvironment _hostingEnvironment; private readonly ICookieManager _cookieManager; @@ -46,7 +46,7 @@ namespace Umbraco.Web.BackOffice.Controllers UmbracoFeatures features, IOptions globalSettings, IPublishedSnapshotService publishedSnapshotService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILocalizationService localizationService, IHostingEnvironment hostingEnvironment, ICookieManager cookieManager, @@ -110,7 +110,7 @@ namespace Umbraco.Web.BackOffice.Controllers [UmbracoAuthorize] public ActionResult Frame(int id, string culture) { - var user = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var previewToken = _publishedSnapshotService.EnterPreview(user, id); diff --git a/src/Umbraco.Web.BackOffice/Controllers/RedirectUrlManagementController.cs b/src/Umbraco.Web.BackOffice/Controllers/RedirectUrlManagementController.cs index 898cf123a5..4a1798dbf0 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/RedirectUrlManagementController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/RedirectUrlManagementController.cs @@ -24,7 +24,7 @@ namespace Umbraco.Web.BackOffice.Controllers { private readonly ILogger _logger; private readonly WebRoutingSettings _webRoutingSettings; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IRedirectUrlService _redirectUrlService; private readonly UmbracoMapper _umbracoMapper; private readonly IHostingEnvironment _hostingEnvironment; @@ -33,7 +33,7 @@ namespace Umbraco.Web.BackOffice.Controllers public RedirectUrlManagementController( ILogger logger, IOptions webRoutingSettings, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IRedirectUrlService redirectUrlService, UmbracoMapper umbracoMapper, IHostingEnvironment hostingEnvironment, @@ -56,7 +56,7 @@ namespace Umbraco.Web.BackOffice.Controllers public IActionResult GetEnableState() { var enabled = _webRoutingSettings.DisableRedirectUrlTracking == false; - var userIsAdmin = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsAdmin(); + var userIsAdmin = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin(); return Ok(new { enabled, userIsAdmin }); } @@ -112,7 +112,7 @@ namespace Umbraco.Web.BackOffice.Controllers [HttpPost] public IActionResult ToggleUrlTracker(bool disable) { - var userIsAdmin = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsAdmin(); + var userIsAdmin = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin(); if (userIsAdmin == false) { var errorMessage = "User is not a member of the administrators group and so is not allowed to toggle the URL tracker"; diff --git a/src/Umbraco.Web.BackOffice/Controllers/SectionController.cs b/src/Umbraco.Web.BackOffice/Controllers/SectionController.cs index 982dab6dec..0d77eedd47 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/SectionController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/SectionController.cs @@ -30,10 +30,10 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly ISectionService _sectionService; private readonly ITreeService _treeService; private readonly UmbracoMapper _umbracoMapper; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public SectionController( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILocalizedTextService localizedTextService, IDashboardService dashboardService, ISectionService sectionService, ITreeService treeService, UmbracoMapper umbracoMapper, IControllerFactory controllerFactory, @@ -51,7 +51,7 @@ namespace Umbraco.Web.BackOffice.Controllers public IEnumerable
GetSections() { - var sections = _sectionService.GetAllowedSections(_backofficeSecurityAccessor.BackofficeSecurity.GetUserId().ResultOr(0)); + var sections = _sectionService.GetAllowedSections(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(0)); var sectionModels = sections.Select(_umbracoMapper.Map
).ToArray(); @@ -63,7 +63,7 @@ namespace Umbraco.Web.BackOffice.Controllers ControllerContext = ControllerContext }; - var dashboards = _dashboardService.GetDashboards(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser); + var dashboards = _dashboardService.GetDashboards(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser); //now we can add metadata for each section so that the UI knows if there's actually anything at all to render for //a dashboard for a given section, then the UI can deal with it accordingly (i.e. redirect to the first tree) @@ -109,10 +109,10 @@ namespace Umbraco.Web.BackOffice.Controllers { var sections = _sectionService.GetSections(); var mapped = sections.Select(_umbracoMapper.Map
); - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsAdmin()) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin()) return mapped; - return mapped.Where(x => _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.AllowedSections.Contains(x.Alias)).ToArray(); + return mapped.Where(x => _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.AllowedSections.Contains(x.Alias)).ToArray(); } } } diff --git a/src/Umbraco.Web.BackOffice/Controllers/TourController.cs b/src/Umbraco.Web.BackOffice/Controllers/TourController.cs index 818b4edf66..340025972f 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/TourController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/TourController.cs @@ -22,14 +22,14 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly TourFilterCollection _filters; private readonly IHostingEnvironment _hostingEnvironment; private readonly TourSettings _tourSettings; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IContentTypeService _contentTypeService; public TourController( TourFilterCollection filters, IHostingEnvironment hostingEnvironment, IOptions tourSettings, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IContentTypeService contentTypeService) { _filters = filters; @@ -47,7 +47,7 @@ namespace Umbraco.Web.BackOffice.Controllers if (_tourSettings.EnableTours == false) return result; - var user = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; if (user == null) return result; @@ -189,7 +189,7 @@ namespace Umbraco.Web.BackOffice.Controllers var backOfficeTours = tours.Where(x => aliasFilters.Count == 0 || aliasFilters.All(filter => filter.IsMatch(x.Alias)) == false); - var user = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var localizedTours = backOfficeTours.Where(x => string.IsNullOrWhiteSpace(x.Culture) || x.Culture.Equals(user.Language, diff --git a/src/Umbraco.Web.BackOffice/Controllers/UpdateCheckController.cs b/src/Umbraco.Web.BackOffice/Controllers/UpdateCheckController.cs index 71dc97c835..4b4d48dcba 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/UpdateCheckController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/UpdateCheckController.cs @@ -24,14 +24,14 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IUpgradeService _upgradeService; private readonly IUmbracoVersion _umbracoVersion; private readonly ICookieManager _cookieManager; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly GlobalSettings _globalSettings; public UpdateCheckController( IUpgradeService upgradeService, IUmbracoVersion umbracoVersion, ICookieManager cookieManager, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IOptions globalSettings) { _upgradeService = upgradeService ?? throw new ArgumentNullException(nameof(upgradeService)); @@ -46,7 +46,7 @@ namespace Umbraco.Web.BackOffice.Controllers { var updChkCookie = _cookieManager.GetCookieValue("UMB_UPDCHK"); var updateCheckCookie = updChkCookie ?? string.Empty; - if (_globalSettings.VersionCheckPeriod > 0 && string.IsNullOrEmpty(updateCheckCookie) && _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsAdmin()) + if (_globalSettings.VersionCheckPeriod > 0 && string.IsNullOrEmpty(updateCheckCookie) && _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin()) { try { diff --git a/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs b/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs index 6d641c9cf9..f0c5702298 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs @@ -28,13 +28,13 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly IContentService _contentService; private readonly IEntityService _entityService; private readonly IMediaService _mediaService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly UmbracoMapper _umbracoMapper; private readonly ILocalizedTextService _localizedTextService; private readonly IShortStringHelper _shortStringHelper; public UserGroupsController(IUserService userService, IContentService contentService, - IEntityService entityService, IMediaService mediaService, IBackofficeSecurityAccessor backofficeSecurityAccessor, + IEntityService entityService, IMediaService mediaService, IBackOfficeSecurityAccessor backofficeSecurityAccessor, UmbracoMapper umbracoMapper, ILocalizedTextService localizedTextService, IShortStringHelper shortStringHelper) { @@ -58,19 +58,19 @@ namespace Umbraco.Web.BackOffice.Controllers var authHelper = new UserGroupEditorAuthorizationHelper( _userService, _contentService, _mediaService, _entityService); - var isAuthorized = authHelper.AuthorizeGroupAccess(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, userGroupSave.Alias); + var isAuthorized = authHelper.AuthorizeGroupAccess(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, userGroupSave.Alias); if (isAuthorized == false) throw new HttpResponseException(HttpStatusCode.Unauthorized, isAuthorized.Result); //if sections were added we need to check that the current user has access to that section - isAuthorized = authHelper.AuthorizeSectionChanges(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, + isAuthorized = authHelper.AuthorizeSectionChanges(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, userGroupSave.PersistedUserGroup.AllowedSections, userGroupSave.Sections); if (isAuthorized == false) throw new HttpResponseException(HttpStatusCode.Unauthorized, isAuthorized.Result); //if start nodes were changed we need to check that the current user has access to them - isAuthorized = authHelper.AuthorizeStartNodeChanges(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, + isAuthorized = authHelper.AuthorizeStartNodeChanges(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, userGroupSave.PersistedUserGroup.StartContentId, userGroupSave.StartContentId, userGroupSave.PersistedUserGroup.StartMediaId, @@ -112,18 +112,18 @@ namespace Umbraco.Web.BackOffice.Controllers private void EnsureNonAdminUserIsInSavedUserGroup(UserGroupSave userGroupSave) { - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsAdmin()) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin()) { return; } var userIds = userGroupSave.Users.ToList(); - if (userIds.Contains(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id)) + if (userIds.Contains(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id)) { return; } - userIds.Add(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Id); + userIds.Add(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id); userGroupSave.Users = userIds; } @@ -145,7 +145,7 @@ namespace Umbraco.Web.BackOffice.Controllers var allGroups = _umbracoMapper.MapEnumerable(_userService.GetAllUserGroups()) .ToList(); - var isAdmin = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsAdmin(); + var isAdmin = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin(); if (isAdmin) return allGroups; if (onlyCurrentUserGroups == false) @@ -156,7 +156,7 @@ namespace Umbraco.Web.BackOffice.Controllers } //we cannot return user groups that this user does not have access to - var currentUserGroups = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Groups.Select(x => x.Alias).ToArray(); + var currentUserGroups = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Groups.Select(x => x.Alias).ToArray(); return allGroups.Where(x => currentUserGroups.Contains(x.Alias)).ToArray(); } diff --git a/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs b/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs index d45951a3df..25c6d712c5 100644 --- a/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs +++ b/src/Umbraco.Web.BackOffice/Controllers/UsersController.cs @@ -62,7 +62,7 @@ namespace Umbraco.Web.BackOffice.Controllers private readonly SecuritySettings _securitySettings; private readonly IRequestAccessor _requestAccessor; private readonly IEmailSender _emailSender; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly AppCaches _appCaches; private readonly IShortStringHelper _shortStringHelper; private readonly IUserService _userService; @@ -85,7 +85,7 @@ namespace Umbraco.Web.BackOffice.Controllers IOptions securitySettings, IRequestAccessor requestAccessor, IEmailSender emailSender, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, AppCaches appCaches, IShortStringHelper shortStringHelper, IUserService userService, @@ -128,7 +128,7 @@ namespace Umbraco.Web.BackOffice.Controllers /// public string[] GetCurrentUserAvatarUrls() { - var urls = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.GetUserAvatarUrls(_appCaches.RuntimeCache, _mediaFileSystem, _imageUrlGenerator); + var urls = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetUserAvatarUrls(_appCaches.RuntimeCache, _mediaFileSystem, _imageUrlGenerator); if (urls == null) throw new HttpResponseException(HttpStatusCode.BadRequest, "Could not access Gravatar endpoint"); @@ -292,9 +292,9 @@ namespace Umbraco.Web.BackOffice.Controllers // so to do that here, we'll need to check if this current user is an admin and if not we should exclude all user who are // also admins - var hideDisabledUsers = _securitySettings.HideDisabledUsersInBackoffice; + var hideDisabledUsers = _securitySettings.HideDisabledUsersInBackOffice; var excludeUserGroups = new string[0]; - var isAdmin = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsAdmin(); + var isAdmin = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin(); if (isAdmin == false) { //this user is not an admin so in that case we need to exclude all admin users @@ -303,7 +303,7 @@ namespace Umbraco.Web.BackOffice.Controllers var filterQuery = _sqlContext.Query(); - if (!_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.IsSuper()) + if (!_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsSuper()) { // only super can see super - but don't use IsSuper, cannot be mapped to SQL //filterQuery.Where(x => !x.IsSuper()); @@ -364,7 +364,7 @@ namespace Umbraco.Web.BackOffice.Controllers //Perform authorization here to see if the current user can actually save this user with the info being requested var authHelper = new UserEditorAuthorizationHelper(_contentService,_mediaService, _userService, _entityService); - var canSaveUser = authHelper.IsAuthorized(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, null, null, null, userSave.UserGroups); + var canSaveUser = authHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, null, null, null, userSave.UserGroups); if (canSaveUser == false) { throw new HttpResponseException(HttpStatusCode.Unauthorized, canSaveUser.Result); @@ -448,7 +448,7 @@ namespace Umbraco.Web.BackOffice.Controllers //Perform authorization here to see if the current user can actually save this user with the info being requested var authHelper = new UserEditorAuthorizationHelper(_contentService,_mediaService, _userService, _entityService); - var canSaveUser = authHelper.IsAuthorized(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, user, null, null, userSave.UserGroups); + var canSaveUser = authHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, user, null, null, userSave.UserGroups); if (canSaveUser == false) { throw new HttpResponseException(HttpStatusCode.Unauthorized, canSaveUser.Result); @@ -483,7 +483,7 @@ namespace Umbraco.Web.BackOffice.Controllers //send the email - await SendUserInviteEmailAsync(display, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Name, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Email, user, userSave.Message); + await SendUserInviteEmailAsync(display, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Email, user, userSave.Message); display.AddSuccessNotification(_localizedTextService.Localize("speechBubbles/resendInviteHeader"), _localizedTextService.Localize("speechBubbles/resendInviteSuccess", new[] { user.Name })); @@ -579,7 +579,7 @@ namespace Umbraco.Web.BackOffice.Controllers //Perform authorization here to see if the current user can actually save this user with the info being requested var authHelper = new UserEditorAuthorizationHelper(_contentService,_mediaService, _userService, _entityService); - var canSaveUser = authHelper.IsAuthorized(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, found, userSave.StartContentIds, userSave.StartMediaIds, userSave.UserGroups); + var canSaveUser = authHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, found, userSave.StartContentIds, userSave.StartMediaIds, userSave.UserGroups); if (canSaveUser == false) { throw new HttpResponseException(HttpStatusCode.Unauthorized, canSaveUser.Result); @@ -662,7 +662,7 @@ namespace Umbraco.Web.BackOffice.Controllers } var passwordChanger = new PasswordChanger(_loggerFactory.CreateLogger()); - var passwordChangeResult = await passwordChanger.ChangePasswordWithIdentityAsync(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, found, changingPasswordModel, _backOfficeUserManager); + var passwordChangeResult = await passwordChanger.ChangePasswordWithIdentityAsync(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, found, changingPasswordModel, _backOfficeUserManager); if (passwordChangeResult.Success) { @@ -687,7 +687,7 @@ namespace Umbraco.Web.BackOffice.Controllers [AdminUsersAuthorize("userIds")] public IActionResult PostDisableUsers([FromQuery]int[] userIds) { - var tryGetCurrentUserId = _backofficeSecurityAccessor.BackofficeSecurity.GetUserId(); + var tryGetCurrentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId(); if (tryGetCurrentUserId && userIds.Contains(tryGetCurrentUserId.Result)) { throw HttpResponseException.CreateNotificationValidationErrorResponse("The current user cannot disable itself"); diff --git a/src/Umbraco.Web.BackOffice/Filters/AdminUsersAuthorizeAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/AdminUsersAuthorizeAttribute.cs index 4920b6351a..867b2c0a24 100644 --- a/src/Umbraco.Web.BackOffice/Filters/AdminUsersAuthorizeAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/AdminUsersAuthorizeAttribute.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Filters private readonly IContentService _contentService; private readonly IMediaService _mediaService; private readonly IEntityService _entityService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public AdminUsersAuthorizeFilter( IRequestAccessor requestAccessor, @@ -43,7 +43,7 @@ namespace Umbraco.Web.BackOffice.Filters IContentService contentService, IMediaService mediaService, IEntityService entityService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, string parameterName) { _requestAccessor = requestAccessor; @@ -87,7 +87,7 @@ namespace Umbraco.Web.BackOffice.Filters var users = _userService.GetUsersById(userIds); var authHelper = new UserEditorAuthorizationHelper(_contentService, _mediaService, _userService, _entityService); - return users.All(user => authHelper.IsAuthorized(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, user, null, null, null) != false); + return users.All(user => authHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, user, null, null, null) != false); } } diff --git a/src/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttribute.cs index c484de3bfb..3c2efec3a3 100644 --- a/src/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/AppendUserModifiedHeaderAttribute.cs @@ -43,7 +43,7 @@ namespace Umbraco.Web.BackOffice.Filters throw new InvalidOperationException($"No argument found for the current action with the name: {_userIdParameter}"); } - var backofficeSecurity = context.HttpContext.RequestServices.GetService(); + var backofficeSecurity = context.HttpContext.RequestServices.GetService(); var user = backofficeSecurity.CurrentUser; if (user == null) { diff --git a/src/Umbraco.Web.BackOffice/Filters/ContentModelValidator.cs b/src/Umbraco.Web.BackOffice/Filters/ContentModelValidator.cs index 812e4e0a73..1ce72d8723 100644 --- a/src/Umbraco.Web.BackOffice/Filters/ContentModelValidator.cs +++ b/src/Umbraco.Web.BackOffice/Filters/ContentModelValidator.cs @@ -22,14 +22,14 @@ namespace Umbraco.Web.BackOffice.Filters internal abstract class ContentModelValidator { - protected IBackofficeSecurity BackofficeSecurity { get; } + protected IBackOfficeSecurity BackOfficeSecurity { get; } public IPropertyValidationService PropertyValidationService { get; } protected ILogger Logger { get; } - protected ContentModelValidator(ILogger logger, IBackofficeSecurity backofficeSecurity, IPropertyValidationService propertyValidationService) + protected ContentModelValidator(ILogger logger, IBackOfficeSecurity backofficeSecurity, IPropertyValidationService propertyValidationService) { Logger = logger ?? throw new ArgumentNullException(nameof(logger)); - BackofficeSecurity = backofficeSecurity ?? throw new ArgumentNullException(nameof(backofficeSecurity)); + BackOfficeSecurity = backofficeSecurity ?? throw new ArgumentNullException(nameof(backofficeSecurity)); PropertyValidationService = propertyValidationService ?? throw new ArgumentNullException(nameof(propertyValidationService)); } } @@ -53,7 +53,7 @@ namespace Umbraco.Web.BackOffice.Filters protected ContentModelValidator( ILogger logger, - IBackofficeSecurity backofficeSecurity, + IBackOfficeSecurity backofficeSecurity, ILocalizedTextService textService, IPropertyValidationService propertyValidationService) : base(logger, backofficeSecurity, propertyValidationService) diff --git a/src/Umbraco.Web.BackOffice/Filters/ContentSaveModelValidator.cs b/src/Umbraco.Web.BackOffice/Filters/ContentSaveModelValidator.cs index bf28b2ff63..ef50f4fa74 100644 --- a/src/Umbraco.Web.BackOffice/Filters/ContentSaveModelValidator.cs +++ b/src/Umbraco.Web.BackOffice/Filters/ContentSaveModelValidator.cs @@ -13,7 +13,7 @@ namespace Umbraco.Web.BackOffice.Filters { public ContentSaveModelValidator( ILogger logger, - IBackofficeSecurity backofficeSecurity, + IBackOfficeSecurity backofficeSecurity, ILocalizedTextService textService, IPropertyValidationService propertyValidationService) : base(logger, backofficeSecurity, textService, propertyValidationService) diff --git a/src/Umbraco.Web.BackOffice/Filters/ContentSaveValidationAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/ContentSaveValidationAttribute.cs index c2717f7335..2553232185 100644 --- a/src/Umbraco.Web.BackOffice/Filters/ContentSaveValidationAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/ContentSaveValidationAttribute.cs @@ -35,12 +35,12 @@ namespace Umbraco.Web.BackOffice.Filters private readonly ILoggerFactory _loggerFactory; private readonly ILocalizedTextService _textService; private readonly IUserService _userService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public ContentSaveValidationFilter( ILoggerFactory loggerFactory, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILocalizedTextService textService, IContentService contentService, IUserService userService, @@ -59,11 +59,11 @@ namespace Umbraco.Web.BackOffice.Filters public void OnActionExecuting(ActionExecutingContext context) { var model = (ContentItemSave) context.ActionArguments["contentItem"]; - var contentItemValidator = new ContentSaveModelValidator(_loggerFactory.CreateLogger(), _backofficeSecurityAccessor.BackofficeSecurity, _textService, _propertyValidationService); + var contentItemValidator = new ContentSaveModelValidator(_loggerFactory.CreateLogger(), _backofficeSecurityAccessor.BackOfficeSecurity, _textService, _propertyValidationService); if (!ValidateAtLeastOneVariantIsBeingSaved(model, context)) return; if (!contentItemValidator.ValidateExistingContent(model, context)) return; - if (!ValidateUserAccess(model, context, _backofficeSecurityAccessor.BackofficeSecurity)) return; + if (!ValidateUserAccess(model, context, _backofficeSecurityAccessor.BackOfficeSecurity)) return; //validate for each variant that is being updated foreach (var variant in model.Variants.Where(x => x.Save)) @@ -103,7 +103,7 @@ namespace Umbraco.Web.BackOffice.Filters /// /// private bool ValidateUserAccess(ContentItemSave contentItem, ActionExecutingContext actionContext, - IBackofficeSecurity backofficeSecurity) + IBackOfficeSecurity backofficeSecurity) { // We now need to validate that the user is allowed to be doing what they are doing. // Based on the action we need to check different permissions. diff --git a/src/Umbraco.Web.BackOffice/Filters/EnsureUserPermissionForContentAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/EnsureUserPermissionForContentAttribute.cs index 1c271d93e6..6e0095b4b4 100644 --- a/src/Umbraco.Web.BackOffice/Filters/EnsureUserPermissionForContentAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/EnsureUserPermissionForContentAttribute.cs @@ -75,7 +75,7 @@ namespace Umbraco.Web.BackOffice.Filters private sealed class EnsureUserPermissionForContentFilter : IActionFilter { private readonly int? _nodeId; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IEntityService _entityService; private readonly IUserService _userService; private readonly IContentService _contentService; @@ -83,7 +83,7 @@ namespace Umbraco.Web.BackOffice.Filters private readonly char? _permissionToCheck; public EnsureUserPermissionForContentFilter( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IUserService userService, IContentService contentService, @@ -94,7 +94,7 @@ namespace Umbraco.Web.BackOffice.Filters } public EnsureUserPermissionForContentFilter( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IUserService userService, IContentService contentService, @@ -106,7 +106,7 @@ namespace Umbraco.Web.BackOffice.Filters } public EnsureUserPermissionForContentFilter( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IUserService userService, IContentService contentService, @@ -116,7 +116,7 @@ namespace Umbraco.Web.BackOffice.Filters } public EnsureUserPermissionForContentFilter( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IUserService userService, IContentService contentService, @@ -128,7 +128,7 @@ namespace Umbraco.Web.BackOffice.Filters private EnsureUserPermissionForContentFilter( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IUserService userService, IContentService contentService, @@ -156,7 +156,7 @@ namespace Umbraco.Web.BackOffice.Filters public void OnActionExecuting(ActionExecutingContext context) { - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser == null) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser == null) { //not logged in throw new HttpResponseException(HttpStatusCode.Unauthorized); @@ -213,7 +213,7 @@ namespace Umbraco.Web.BackOffice.Filters } var permissionResult = ContentPermissionsHelper.CheckPermissions(nodeId, - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, _userService, _contentService, _entityService, diff --git a/src/Umbraco.Web.BackOffice/Filters/EnsureUserPermissionForMediaAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/EnsureUserPermissionForMediaAttribute.cs index 3bf3bd8730..8a4346c2ac 100644 --- a/src/Umbraco.Web.BackOffice/Filters/EnsureUserPermissionForMediaAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/EnsureUserPermissionForMediaAttribute.cs @@ -41,7 +41,7 @@ namespace Umbraco.Web.WebApi.Filters { private readonly int? _nodeId; private readonly string _paramName; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IEntityService _entityService; private readonly IMediaService _mediaService; @@ -49,7 +49,7 @@ namespace Umbraco.Web.WebApi.Filters /// This constructor will only be able to test the start node access ///
public EnsureUserPermissionForMediaFilter( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IMediaService mediaService, int nodeId) @@ -59,7 +59,7 @@ namespace Umbraco.Web.WebApi.Filters } public EnsureUserPermissionForMediaFilter( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IMediaService mediaService, string paramName) @@ -71,7 +71,7 @@ namespace Umbraco.Web.WebApi.Filters } private EnsureUserPermissionForMediaFilter( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IEntityService entityService, IMediaService mediaService, int? nodeId, string paramName) @@ -118,7 +118,7 @@ namespace Umbraco.Web.WebApi.Filters public void OnActionExecuting(ActionExecutingContext context) { - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser == null) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser == null) { throw new HttpResponseException(System.Net.HttpStatusCode.Unauthorized); } @@ -159,7 +159,7 @@ namespace Umbraco.Web.WebApi.Filters if (MediaController.CheckPermissions( context.HttpContext.Items, - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, _mediaService, _entityService, nodeId)) diff --git a/src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttribute.cs index c67bbefd89..e6735d01e8 100644 --- a/src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttribute.cs @@ -61,7 +61,7 @@ namespace Umbraco.Web.BackOffice.Filters - public FilterAllowedOutgoingContentFilter(Type outgoingType, string propertyName, char permissionToCheck, IUserService userService, IEntityService entityService, IBackofficeSecurityAccessor backofficeSecurityAccessor) + public FilterAllowedOutgoingContentFilter(Type outgoingType, string propertyName, char permissionToCheck, IUserService userService, IEntityService entityService, IBackOfficeSecurityAccessor backofficeSecurityAccessor) : base(entityService, backofficeSecurityAccessor, outgoingType, propertyName) { _userService = userService ?? throw new ArgumentNullException(nameof(userService)); diff --git a/src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingMediaAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingMediaAttribute.cs index a6325e0650..9ef5093ff3 100644 --- a/src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingMediaAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingMediaAttribute.cs @@ -34,10 +34,10 @@ namespace Umbraco.Web.WebApi.Filters { private readonly Type _outgoingType; private readonly IEntityService _entityService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly string _propertyName; - public FilterAllowedOutgoingMediaFilter(IEntityService entityService, IBackofficeSecurityAccessor backofficeSecurityAccessor, Type outgoingType, string propertyName) + public FilterAllowedOutgoingMediaFilter(IEntityService entityService, IBackOfficeSecurityAccessor backofficeSecurityAccessor, Type outgoingType, string propertyName) { _entityService = entityService ?? throw new ArgumentNullException(nameof(entityService)); _backofficeSecurityAccessor = backofficeSecurityAccessor ?? throw new ArgumentNullException(nameof(backofficeSecurityAccessor)); @@ -57,7 +57,7 @@ namespace Umbraco.Web.WebApi.Filters { if (context.Result == null) return; - var user = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; if (user == null) return; var objectContent = context.Result as ObjectResult; diff --git a/src/Umbraco.Web.BackOffice/Filters/IsCurrentUserModelFilterAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/IsCurrentUserModelFilterAttribute.cs index 380995db4d..0ba343cfbc 100644 --- a/src/Umbraco.Web.BackOffice/Filters/IsCurrentUserModelFilterAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/IsCurrentUserModelFilterAttribute.cs @@ -16,9 +16,9 @@ namespace Umbraco.Web.BackOffice.Filters private class IsCurrentUserModelFilter : IActionFilter { - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; - public IsCurrentUserModelFilter(IBackofficeSecurityAccessor backofficeSecurityAccessor) + public IsCurrentUserModelFilter(IBackOfficeSecurityAccessor backofficeSecurityAccessor) { _backofficeSecurityAccessor = backofficeSecurityAccessor; } @@ -28,7 +28,7 @@ namespace Umbraco.Web.BackOffice.Filters { if (context.Result == null) return; - var user = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; if (user == null) return; var objectContent = context.Result as ObjectResult; diff --git a/src/Umbraco.Web.BackOffice/Filters/MediaItemSaveValidationAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/MediaItemSaveValidationAttribute.cs index d30cf7c7ea..fa1ee568f0 100644 --- a/src/Umbraco.Web.BackOffice/Filters/MediaItemSaveValidationAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/MediaItemSaveValidationAttribute.cs @@ -30,11 +30,11 @@ namespace Umbraco.Web.BackOffice.Filters private readonly IMediaService _mediaService; private readonly ILocalizedTextService _textService; private readonly ILoggerFactory _loggerFactory; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public MediaItemSaveValidationFilter( ILoggerFactory loggerFactory, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILocalizedTextService textService, IMediaService mediaService, IEntityService entityService, @@ -51,7 +51,7 @@ namespace Umbraco.Web.BackOffice.Filters public void OnActionExecuting(ActionExecutingContext context) { var model = (MediaItemSave) context.ActionArguments["contentItem"]; - var contentItemValidator = new MediaSaveModelValidator(_loggerFactory.CreateLogger(), _backofficeSecurityAccessor.BackofficeSecurity, _textService, _propertyValidationService); + var contentItemValidator = new MediaSaveModelValidator(_loggerFactory.CreateLogger(), _backofficeSecurityAccessor.BackOfficeSecurity, _textService, _propertyValidationService); if (ValidateUserAccess(model, context)) { @@ -102,7 +102,7 @@ namespace Umbraco.Web.BackOffice.Filters if (MediaController.CheckPermissions( actionContext.HttpContext.Items, - _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, + _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, _mediaService, _entityService, contentIdToCheck, contentToCheck) == false) { diff --git a/src/Umbraco.Web.BackOffice/Filters/MediaSaveModelValidator.cs b/src/Umbraco.Web.BackOffice/Filters/MediaSaveModelValidator.cs index e906226809..925d52e948 100644 --- a/src/Umbraco.Web.BackOffice/Filters/MediaSaveModelValidator.cs +++ b/src/Umbraco.Web.BackOffice/Filters/MediaSaveModelValidator.cs @@ -13,7 +13,7 @@ namespace Umbraco.Web.BackOffice.Filters { public MediaSaveModelValidator( ILogger logger, - IBackofficeSecurity backofficeSecurity, + IBackOfficeSecurity backofficeSecurity, ILocalizedTextService textService, IPropertyValidationService propertyValidationService) : base(logger, backofficeSecurity, textService, propertyValidationService) diff --git a/src/Umbraco.Web.BackOffice/Filters/MemberSaveModelValidator.cs b/src/Umbraco.Web.BackOffice/Filters/MemberSaveModelValidator.cs index 7b3fa00835..a84b4f1c9e 100644 --- a/src/Umbraco.Web.BackOffice/Filters/MemberSaveModelValidator.cs +++ b/src/Umbraco.Web.BackOffice/Filters/MemberSaveModelValidator.cs @@ -26,7 +26,7 @@ namespace Umbraco.Web.BackOffice.Filters public MemberSaveModelValidator( ILogger logger, - IBackofficeSecurity backofficeSecurity, + IBackOfficeSecurity backofficeSecurity, ILocalizedTextService textService, IMemberTypeService memberTypeService, IMemberService memberService, @@ -96,7 +96,7 @@ namespace Umbraco.Web.BackOffice.Filters //if the user doesn't have access to sensitive values, then we need to validate the incoming properties to check //if a sensitive value is being submitted. - if (BackofficeSecurity.CurrentUser.HasAccessToSensitiveData() == false) + if (BackOfficeSecurity.CurrentUser.HasAccessToSensitiveData() == false) { var contentType = _memberTypeService.Get(model.PersistedContent.ContentTypeId); var sensitiveProperties = contentType diff --git a/src/Umbraco.Web.BackOffice/Filters/MemberSaveValidationAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/MemberSaveValidationAttribute.cs index 1bbe4a80b7..7ba86f525e 100644 --- a/src/Umbraco.Web.BackOffice/Filters/MemberSaveValidationAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/MemberSaveValidationAttribute.cs @@ -23,7 +23,7 @@ namespace Umbraco.Web.BackOffice.Filters private sealed class MemberSaveValidationFilter : IActionFilter { private readonly ILoggerFactory _loggerFactory; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly ILocalizedTextService _textService; private readonly IMemberTypeService _memberTypeService; private readonly IMemberService _memberService; @@ -32,7 +32,7 @@ namespace Umbraco.Web.BackOffice.Filters public MemberSaveValidationFilter( ILoggerFactory loggerFactory, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILocalizedTextService textService, IMemberTypeService memberTypeService, IMemberService memberService, @@ -51,7 +51,7 @@ namespace Umbraco.Web.BackOffice.Filters public void OnActionExecuting(ActionExecutingContext context) { var model = (MemberSave)context.ActionArguments["contentItem"]; - var contentItemValidator = new MemberSaveModelValidator(_loggerFactory.CreateLogger(), _backofficeSecurityAccessor.BackofficeSecurity, _textService, _memberTypeService, _memberService, _shortStringHelper, _propertyValidationService); + var contentItemValidator = new MemberSaveModelValidator(_loggerFactory.CreateLogger(), _backofficeSecurityAccessor.BackOfficeSecurity, _textService, _memberTypeService, _memberService, _shortStringHelper, _propertyValidationService); //now do each validation step if (contentItemValidator.ValidateExistingContent(model, context)) if (contentItemValidator.ValidateProperties(model, model, context)) diff --git a/src/Umbraco.Web.BackOffice/Filters/OutgoingEditorModelEventAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/OutgoingEditorModelEventAttribute.cs index 9952eb52f9..b2a6ab099e 100644 --- a/src/Umbraco.Web.BackOffice/Filters/OutgoingEditorModelEventAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/OutgoingEditorModelEventAttribute.cs @@ -14,9 +14,9 @@ namespace Umbraco.Web.WebApi.Filters internal sealed class OutgoingEditorModelEventAttribute : ActionFilterAttribute { private readonly IUmbracoContextAccessor _umbracoContextAccessor; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; - public OutgoingEditorModelEventAttribute(IUmbracoContextAccessor umbracoContextAccessor, IBackofficeSecurityAccessor backofficeSecurityAccessor) + public OutgoingEditorModelEventAttribute(IUmbracoContextAccessor umbracoContextAccessor, IBackOfficeSecurityAccessor backofficeSecurityAccessor) { _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); _backofficeSecurityAccessor = backofficeSecurityAccessor ?? throw new ArgumentNullException(nameof(backofficeSecurityAccessor)); @@ -27,7 +27,7 @@ namespace Umbraco.Web.WebApi.Filters if (context.Result == null) return; var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); - var user = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var user = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; if (user == null) return; if (context.Result is ObjectResult objectContent) diff --git a/src/Umbraco.Web.BackOffice/Filters/UmbracoApplicationAuthorizeAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/UmbracoApplicationAuthorizeAttribute.cs index 3850682cf2..cc1bdd4cd5 100644 --- a/src/Umbraco.Web.BackOffice/Filters/UmbracoApplicationAuthorizeAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/UmbracoApplicationAuthorizeAttribute.cs @@ -23,7 +23,7 @@ namespace Umbraco.Web.BackOffice.Filters ///
internal static bool Enable = true; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly string[] _appNames; /// @@ -33,7 +33,7 @@ namespace Umbraco.Web.BackOffice.Filters /// /// If the user has access to any of the specified apps, they will be authorized. /// - public UmbracoApplicationAuthorizeFilter(IBackofficeSecurityAccessor backofficeSecurityAccessor, params string[] appName) + public UmbracoApplicationAuthorizeFilter(IBackOfficeSecurityAccessor backofficeSecurityAccessor, params string[] appName) { _backofficeSecurityAccessor = backofficeSecurityAccessor; _appNames = appName; @@ -55,9 +55,9 @@ namespace Umbraco.Web.BackOffice.Filters return true; } - var authorized = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser != null - && _appNames.Any(app => _backofficeSecurityAccessor.BackofficeSecurity.UserHasSectionAccess( - app, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser)); + var authorized = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser != null + && _appNames.Any(app => _backofficeSecurityAccessor.BackOfficeSecurity.UserHasSectionAccess( + app, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser)); return authorized; } diff --git a/src/Umbraco.Web.BackOffice/Filters/UmbracoTreeAuthorizeAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/UmbracoTreeAuthorizeAttribute.cs index 5f6e00e82e..eef7469322 100644 --- a/src/Umbraco.Web.BackOffice/Filters/UmbracoTreeAuthorizeAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/UmbracoTreeAuthorizeAttribute.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Filters private readonly string[] _treeAliases; private readonly ITreeService _treeService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; /// /// Constructor to set authorization to be based on a tree alias for which application security will be applied @@ -46,7 +46,7 @@ namespace Umbraco.Web.BackOffice.Filters /// If the user has access to the application that the treeAlias is specified in, they will be authorized. /// Multiple trees may be specified. /// - public UmbracoTreeAuthorizeFilter(ITreeService treeService, IBackofficeSecurityAccessor backofficeSecurityAccessor, + public UmbracoTreeAuthorizeFilter(ITreeService treeService, IBackOfficeSecurityAccessor backofficeSecurityAccessor, params string[] treeAliases) { _treeService = treeService ?? throw new ArgumentNullException(nameof(treeService)); @@ -76,9 +76,9 @@ namespace Umbraco.Web.BackOffice.Filters .Distinct() .ToArray(); - return _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser != null - && apps.Any(app => _backofficeSecurityAccessor.BackofficeSecurity.UserHasSectionAccess( - app, _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser)); + return _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser != null + && apps.Any(app => _backofficeSecurityAccessor.BackOfficeSecurity.UserHasSectionAccess( + app, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser)); } } } diff --git a/src/Umbraco.Web.BackOffice/Filters/UserGroupAuthorizationAttribute.cs b/src/Umbraco.Web.BackOffice/Filters/UserGroupAuthorizationAttribute.cs index d867cc90bc..5fa9dd54be 100644 --- a/src/Umbraco.Web.BackOffice/Filters/UserGroupAuthorizationAttribute.cs +++ b/src/Umbraco.Web.BackOffice/Filters/UserGroupAuthorizationAttribute.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.BackOffice.Filters private readonly IContentService _contentService; private readonly IMediaService _mediaService; private readonly IEntityService _entityService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public UserGroupAuthorizationFilter( IRequestAccessor requestAccessor, @@ -43,7 +43,7 @@ namespace Umbraco.Web.BackOffice.Filters IContentService contentService, IMediaService mediaService, IEntityService entityService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, string parameterName) { _requestAccessor = requestAccessor; @@ -65,7 +65,7 @@ namespace Umbraco.Web.BackOffice.Filters private bool IsAuthorized(AuthorizationFilterContext actionContext) { - var currentUser = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser; + var currentUser = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var queryString = actionContext.HttpContext.Request.Query; diff --git a/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs index 1685b329dd..2a05e0fbd9 100644 --- a/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs @@ -45,7 +45,7 @@ namespace Umbraco.Web.Trees private readonly ActionCollection _actions; private readonly GlobalSettings _globalSettings; private readonly IMenuItemCollectionFactory _menuItemCollectionFactory; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly IContentService _contentService; private readonly IEntityService _entityService; private readonly IPublicAccessService _publicAccessService; @@ -57,7 +57,7 @@ namespace Umbraco.Web.Trees UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection, IMenuItemCollectionFactory menuItemCollectionFactory, IEntityService entityService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILogger logger, ActionCollection actionCollection, IUserService userService, @@ -89,7 +89,7 @@ namespace Umbraco.Web.Trees private int[] _userStartNodes; protected override int[] UserStartNodes - => _userStartNodes ?? (_userStartNodes = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService)); + => _userStartNodes ?? (_userStartNodes = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService)); @@ -167,7 +167,7 @@ namespace Umbraco.Web.Trees menu.DefaultMenuAlias = ActionNew.ActionAlias; // we need to get the default permissions as you can't set permissions on the very root node - var permission = _userService.GetPermissions(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, Constants.System.Root).First(); + var permission = _userService.GetPermissions(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, Constants.System.Root).First(); var nodeActions = _actions.FromEntityPermission(permission) .Select(x => new MenuItem(x)); @@ -203,7 +203,7 @@ namespace Umbraco.Web.Trees } //if the user has no path access for this node, all they can do is refresh - if (!_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.HasContentPathAccess(item, _entityService)) + if (!_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasContentPathAccess(item, _entityService)) { var menu = _menuItemCollectionFactory.Create(); menu.Items.Add(new RefreshNode(LocalizedTextService, true)); diff --git a/src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs b/src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs index 227bfd5746..c472ddd141 100644 --- a/src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs +++ b/src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs @@ -25,7 +25,7 @@ namespace Umbraco.Web.Trees public abstract class ContentTreeControllerBase : TreeController, ITreeNodeController { private readonly IEntityService _entityService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly ILogger _logger; private readonly ActionCollection _actionCollection; private readonly IUserService _userService; @@ -38,7 +38,7 @@ namespace Umbraco.Web.Trees UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection, IMenuItemCollectionFactory menuItemCollectionFactory, IEntityService entityService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILogger logger, ActionCollection actionCollection, IUserService userService, @@ -147,12 +147,12 @@ namespace Umbraco.Web.Trees switch (RecycleBinId) { case Constants.System.RecycleBinMedia: - startNodeIds = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService); - startNodePaths = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.GetMediaStartNodePaths(_entityService); + startNodeIds = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService); + startNodePaths = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetMediaStartNodePaths(_entityService); break; case Constants.System.RecycleBinContent: - startNodeIds = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService); - startNodePaths = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.GetContentStartNodePaths(_entityService); + startNodeIds = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateContentStartNodeIds(_entityService); + startNodePaths = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetContentStartNodePaths(_entityService); break; default: throw new NotSupportedException("Path access is only determined on content or media"); @@ -196,7 +196,7 @@ namespace Umbraco.Web.Trees // TODO: in the future we could return a validation statement so we can have some UI to notify the user they don't have access if (ignoreUserStartNodes == false && HasPathAccess(id, queryStrings) == false) { - _logger.LogWarning("User {Username} does not have access to node with id {Id}", _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.Username, id); + _logger.LogWarning("User {Username} does not have access to node with id {Id}", _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Username, id); return nodes; } @@ -312,8 +312,8 @@ namespace Umbraco.Web.Trees { if (entity == null) return false; return RecycleBinId == Constants.System.RecycleBinContent - ? _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.HasContentPathAccess(entity, _entityService) - : _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.HasMediaPathAccess(entity, _entityService); + ? _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasContentPathAccess(entity, _entityService) + : _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasMediaPathAccess(entity, _entityService); } /// @@ -441,7 +441,7 @@ namespace Umbraco.Web.Trees var deleteAction = _actionCollection.FirstOrDefault(y => y.Letter == ActionDelete.ActionLetter); if (deleteAction != null) { - var perms = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.GetPermissions(Constants.System.RecycleBinContentString, _userService); + var perms = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetPermissions(Constants.System.RecycleBinContentString, _userService); deleteAllowed = perms.FirstOrDefault(x => x.Contains(deleteAction.Letter)) != null; } @@ -492,7 +492,7 @@ namespace Umbraco.Web.Trees internal IEnumerable GetAllowedUserMenuItemsForNode(IUmbracoEntity dd) { - var permissionsForPath = _userService.GetPermissionsForPath(_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser, dd.Path).GetAllPermissions(); + var permissionsForPath = _userService.GetPermissionsForPath(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, dd.Path).GetAllPermissions(); return _actionCollection.GetByLetters(permissionsForPath).Select(x => new MenuItem(x)); } diff --git a/src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs index 10edcd46c7..7d001a8d90 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs @@ -40,14 +40,14 @@ namespace Umbraco.Web.Trees private readonly UmbracoTreeSearcher _treeSearcher; private readonly IMediaService _mediaService; private readonly IEntityService _entityService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public MediaTreeController( ILocalizedTextService localizedTextService, UmbracoApiControllerTypeCollection umbracoApiControllerTypeCollection, IMenuItemCollectionFactory menuItemCollectionFactory, IEntityService entityService, - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, ILogger logger, ActionCollection actionCollection, IUserService userService, @@ -68,7 +68,7 @@ namespace Umbraco.Web.Trees private int[] _userStartNodes; protected override int[] UserStartNodes - => _userStartNodes ?? (_userStartNodes = _backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService)); + => _userStartNodes ?? (_userStartNodes = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService)); /// /// Creates a tree node for a content item based on an UmbracoEntity @@ -135,7 +135,7 @@ namespace Umbraco.Web.Trees } //if the user has no path access for this node, all they can do is refresh - if (!_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.HasMediaPathAccess(item, _entityService)) + if (!_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasMediaPathAccess(item, _entityService)) { menu.Items.Add(new RefreshNode(LocalizedTextService, true)); return menu; diff --git a/src/Umbraco.Web.BackOffice/Trees/MemberTreeController.cs b/src/Umbraco.Web.BackOffice/Trees/MemberTreeController.cs index e6d18f3b72..8d349172fd 100644 --- a/src/Umbraco.Web.BackOffice/Trees/MemberTreeController.cs +++ b/src/Umbraco.Web.BackOffice/Trees/MemberTreeController.cs @@ -38,7 +38,7 @@ namespace Umbraco.Web.Trees private readonly IMenuItemCollectionFactory _menuItemCollectionFactory; private readonly IMemberService _memberService; private readonly IMemberTypeService _memberTypeService; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; public MemberTreeController( ILocalizedTextService localizedTextService, @@ -47,7 +47,7 @@ namespace Umbraco.Web.Trees IMenuItemCollectionFactory menuItemCollectionFactory, IMemberService memberService, IMemberTypeService memberTypeService, - IBackofficeSecurityAccessor backofficeSecurityAccessor) + IBackOfficeSecurityAccessor backofficeSecurityAccessor) : base(localizedTextService, umbracoApiControllerTypeCollection) { _treeSearcher = treeSearcher; @@ -146,7 +146,7 @@ namespace Umbraco.Web.Trees //add delete option for all members menu.Items.Add(LocalizedTextService, opensDialog: true); - if (_backofficeSecurityAccessor.BackofficeSecurity.CurrentUser.HasAccessToSensitiveData()) + if (_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.HasAccessToSensitiveData()) { menu.Items.Add(new ExportMember(LocalizedTextService)); } diff --git a/src/Umbraco.Web.Common/Install/InstallController.cs b/src/Umbraco.Web.Common/Install/InstallController.cs index e908b4f128..96f8ddf35e 100644 --- a/src/Umbraco.Web.Common/Install/InstallController.cs +++ b/src/Umbraco.Web.Common/Install/InstallController.cs @@ -26,7 +26,7 @@ namespace Umbraco.Web.Common.Install [Area(Umbraco.Core.Constants.Web.Mvc.InstallArea)] public class InstallController : Controller { - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly InstallHelper _installHelper; private readonly IRuntimeState _runtime; private readonly GlobalSettings _globalSettings; @@ -37,7 +37,7 @@ namespace Umbraco.Web.Common.Install private readonly IRuntimeMinifier _runtimeMinifier; public InstallController( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + IBackOfficeSecurityAccessor backofficeSecurityAccessor, InstallHelper installHelper, IRuntimeState runtime, IOptions globalSettings, @@ -73,7 +73,7 @@ namespace Umbraco.Web.Common.Install // Update ClientDependency version and delete its temp directories to make sure we get fresh caches _runtimeMinifier.Reset(); - var result = _backofficeSecurityAccessor.BackofficeSecurity.ValidateCurrentUser(false); + var result = _backofficeSecurityAccessor.BackOfficeSecurity.ValidateCurrentUser(false); switch (result) { diff --git a/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs b/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs index 3544465dfe..e274e479b7 100644 --- a/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs +++ b/src/Umbraco.Web.Common/Middleware/UmbracoRequestMiddleware.cs @@ -26,14 +26,14 @@ namespace Umbraco.Web.Common.Middleware private readonly IUmbracoRequestLifetimeManager _umbracoRequestLifetimeManager; private readonly IUmbracoContextFactory _umbracoContextFactory; private readonly IRequestCache _requestCache; - private readonly IBackofficeSecurityFactory _backofficeSecurityFactory; + private readonly IBackOfficeSecurityFactory _backofficeSecurityFactory; public UmbracoRequestMiddleware( ILogger logger, IUmbracoRequestLifetimeManager umbracoRequestLifetimeManager, IUmbracoContextFactory umbracoContextFactory, IRequestCache requestCache, - IBackofficeSecurityFactory backofficeSecurityFactory) + IBackOfficeSecurityFactory backofficeSecurityFactory) { _logger = logger; _umbracoRequestLifetimeManager = umbracoRequestLifetimeManager; @@ -52,7 +52,7 @@ namespace Umbraco.Web.Common.Middleware await next(context); return; } - _backofficeSecurityFactory.EnsureBackofficeSecurity(); // Needs to be before UmbracoContext + _backofficeSecurityFactory.EnsureBackOfficeSecurity(); // Needs to be before UmbracoContext var umbracoContextReference = _umbracoContextFactory.EnsureUmbracoContext(); diff --git a/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs b/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs index 0d91892445..83b8e5b218 100644 --- a/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs +++ b/src/Umbraco.Web.Common/Runtime/AspNetCoreComposer.cs @@ -76,8 +76,8 @@ namespace Umbraco.Web.Common.Runtime // register the umbraco context factory composition.RegisterUnique(); - composition.RegisterUnique(); - composition.RegisterUnique(); + composition.RegisterUnique(); + composition.RegisterUnique(); //register the install components //NOTE: i tried to not have these registered if we weren't installing or upgrading but post install when the site restarts diff --git a/src/Umbraco.Web.Common/Security/BackOfficeSignInManager.cs b/src/Umbraco.Web.Common/Security/BackOfficeSignInManager.cs index 4b317ba74e..bef94c0ada 100644 --- a/src/Umbraco.Web.Common/Security/BackOfficeSignInManager.cs +++ b/src/Umbraco.Web.Common/Security/BackOfficeSignInManager.cs @@ -23,7 +23,7 @@ namespace Umbraco.Web.Common.Security // borrowed from https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Core/src/SignInManager.cs private const string LoginProviderKey = "LoginProvider"; // borrowed from https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Core/src/SignInManager.cs - private const string XsrfKey = "XsrfId"; + private const string XsrfKey = "XsrfId"; // TODO: See BackOfficeController.XsrfKey private BackOfficeUserManager _userManager; @@ -264,7 +264,7 @@ namespace Umbraco.Web.Common.Security // borrowed from https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Core/src/SignInManager.cs#L422 // to replace the auth scheme - var auth = await Context.AuthenticateAsync(Constants.Security.BackOfficeAuthenticationType); + var auth = await Context.AuthenticateAsync(Constants.Security.BackOfficeExternalAuthenticationType); var items = auth?.Properties?.Items; if (auth?.Principal == null || items == null || !items.ContainsKey(LoginProviderKey)) { diff --git a/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs b/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs index c16071b68a..7ef628197e 100644 --- a/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs +++ b/src/Umbraco.Web.Common/Security/BackofficeSecurity.cs @@ -14,7 +14,7 @@ using Umbraco.Web.Security; namespace Umbraco.Web.Common.Security { - public class BackofficeSecurity : IBackofficeSecurity + public class BackofficeSecurity : IBackOfficeSecurity { private readonly IUserService _userService; private readonly GlobalSettings _globalSettings; diff --git a/src/Umbraco.Web.Common/Security/BackofficeSecurityFactory.cs b/src/Umbraco.Web.Common/Security/BackofficeSecurityFactory.cs index 7718981b27..4341b5524d 100644 --- a/src/Umbraco.Web.Common/Security/BackofficeSecurityFactory.cs +++ b/src/Umbraco.Web.Common/Security/BackofficeSecurityFactory.cs @@ -9,33 +9,33 @@ using Umbraco.Core.Services; namespace Umbraco.Web.Common.Security { - public class BackofficeSecurityFactory: IBackofficeSecurityFactory + public class BackOfficeSecurityFactory: IBackOfficeSecurityFactory { - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor; private readonly IUserService _userService; private readonly IOptions _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IHttpContextAccessor _httpContextAccessor; - public BackofficeSecurityFactory( - IBackofficeSecurityAccessor backofficeSecurityAccessor, + public BackOfficeSecurityFactory( + IBackOfficeSecurityAccessor backofficeSecurityAccessor, IUserService userService, IOptions globalSettings, IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor) { - _backofficeSecurityAccessor = backofficeSecurityAccessor; + _backOfficeSecurityAccessor = backofficeSecurityAccessor; _userService = userService; _globalSettings = globalSettings; _hostingEnvironment = hostingEnvironment; _httpContextAccessor = httpContextAccessor; } - public void EnsureBackofficeSecurity() + public void EnsureBackOfficeSecurity() { - if (_backofficeSecurityAccessor.BackofficeSecurity is null) + if (_backOfficeSecurityAccessor.BackOfficeSecurity is null) { - _backofficeSecurityAccessor.BackofficeSecurity = new BackofficeSecurity(_userService, _globalSettings, _hostingEnvironment, _httpContextAccessor); + _backOfficeSecurityAccessor.BackOfficeSecurity = new BackofficeSecurity(_userService, _globalSettings, _hostingEnvironment, _httpContextAccessor); } } diff --git a/src/Umbraco.Web.Common/Security/ExternalAuthenticationOptions.cs b/src/Umbraco.Web.Common/Security/ExternalAuthenticationOptions.cs new file mode 100644 index 0000000000..9005251835 --- /dev/null +++ b/src/Umbraco.Web.Common/Security/ExternalAuthenticationOptions.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Umbraco.Web.Common.Security +{ + // TODO: We need to implement this and extend it to support the back office external login options + public interface IExternalAuthenticationOptions + { + ExternalSignInAutoLinkOptions Get(string authenticationType); + } + +} diff --git a/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs b/src/Umbraco.Web.Common/Security/ExternalSignInAutoLinkOptions.cs similarity index 50% rename from src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs rename to src/Umbraco.Web.Common/Security/ExternalSignInAutoLinkOptions.cs index 52239f0fda..93ecf95a3e 100644 --- a/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs +++ b/src/Umbraco.Web.Common/Security/ExternalSignInAutoLinkOptions.cs @@ -1,9 +1,10 @@ -using System; -using Umbraco.Core; +using Microsoft.AspNetCore.Identity; +using System; using Umbraco.Core.BackOffice; -using Umbraco.Web.Composing; +using Umbraco.Core.Configuration.Models; +using SecurityConstants = Umbraco.Core.Constants.Security; -namespace Umbraco.Web.Security +namespace Umbraco.Web.Common.Security { /// /// Options used to configure auto-linking external OAuth providers @@ -21,13 +22,11 @@ namespace Umbraco.Web.Security string[] defaultUserGroups = null, string defaultCulture = null) { - _defaultUserGroups = defaultUserGroups ?? new[] { Constants.Security.EditorGroupAlias }; - _autoLinkExternalAccount = autoLinkExternalAccount; - _defaultCulture = defaultCulture ?? /*Current.Configs.Global().DefaultUILanguage TODO reintroduce config value*/ "en-US"; + DefaultUserGroups = defaultUserGroups ?? new[] { SecurityConstants.EditorGroupAlias }; + AutoLinkExternalAccount = autoLinkExternalAccount; + _defaultCulture = defaultCulture; } - private readonly string[] _defaultUserGroups; - /// /// A callback executed during account auto-linking and before the user is persisted /// @@ -39,39 +38,22 @@ namespace Umbraco.Web.Security /// public Func OnExternalLogin { get; set; } + /// + /// Flag indicating if logging in with the external provider should auto-link/create a local user + /// + public bool AutoLinkExternalAccount { get; } /// - /// The default User group aliases to use for auto-linking users + /// The default user groups to assign to the created local user linked /// - /// - /// - /// - public string[] GetDefaultUserGroups(IUmbracoContext umbracoContext, ExternalLoginInfo loginInfo) - { - return _defaultUserGroups; - } - - private readonly bool _autoLinkExternalAccount; - - /// - /// For private external auth providers such as Active Directory, which when set to true will automatically - /// create a local user if the external provider login was successful. - /// - /// For public auth providers this should always be false!!! - /// - public bool ShouldAutoLinkExternalAccount(IUmbracoContext umbracoContext, ExternalLoginInfo loginInfo) - { - return _autoLinkExternalAccount; - } + public string[] DefaultUserGroups { get; } private readonly string _defaultCulture; /// /// The default Culture to use for auto-linking users /// - public string GetDefaultCulture(IUmbracoContext umbracoContext, ExternalLoginInfo loginInfo) - { - return _defaultCulture; - } + // TODO: Should we use IDefaultCultureAccessor here intead? + public string GetUserAutoLinkCulture(GlobalSettings globalSettings) => _defaultCulture ?? globalSettings.DefaultUILanguage; } } diff --git a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs index 5e5b6f6910..290af371cc 100644 --- a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs +++ b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContext.cs @@ -31,7 +31,7 @@ namespace Umbraco.Web // warn: does *not* manage setting any IUmbracoContextAccessor internal UmbracoContext( IPublishedSnapshotService publishedSnapshotService, - IBackofficeSecurity backofficeSecurity, + IBackOfficeSecurity backofficeSecurity, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IVariationContextAccessor variationContextAccessor, @@ -80,7 +80,7 @@ namespace Umbraco.Web /// /// Gets the BackofficeSecurity class /// - public IBackofficeSecurity Security { get; } + public IBackOfficeSecurity Security { get; } /// /// Gets the uri that is handled by ASP.NET after server-side rewriting took place. diff --git a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContextFactory.cs b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContextFactory.cs index f50a2e2ba8..553ea07a90 100644 --- a/src/Umbraco.Web.Common/UmbracoContext/UmbracoContextFactory.cs +++ b/src/Umbraco.Web.Common/UmbracoContext/UmbracoContextFactory.cs @@ -31,7 +31,7 @@ namespace Umbraco.Web private readonly IHttpContextAccessor _httpContextAccessor; private readonly ICookieManager _cookieManager; private readonly IRequestAccessor _requestAccessor; - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor; private readonly UriUtility _uriUtility; /// @@ -49,7 +49,7 @@ namespace Umbraco.Web IHttpContextAccessor httpContextAccessor, ICookieManager cookieManager, IRequestAccessor requestAccessor, - IBackofficeSecurityAccessor backofficeSecurityAccessor) + IBackOfficeSecurityAccessor backofficeSecurityAccessor) { _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); _publishedSnapshotService = publishedSnapshotService ?? throw new ArgumentNullException(nameof(publishedSnapshotService)); @@ -80,7 +80,7 @@ namespace Umbraco.Web return new UmbracoContext( _publishedSnapshotService, - _backofficeSecurityAccessor.BackofficeSecurity, + _backofficeSecurityAccessor.BackOfficeSecurity, _globalSettings, _hostingEnvironment, _variationContextAccessor, diff --git a/src/Umbraco.Web/Editors/BackOfficeController.cs b/src/Umbraco.Web/Editors/BackOfficeController.cs deleted file mode 100644 index f8848f64f0..0000000000 --- a/src/Umbraco.Web/Editors/BackOfficeController.cs +++ /dev/null @@ -1,371 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using System.Web; -using System.Web.Mvc; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Options; -using Microsoft.Extensions.Logging; -using Microsoft.Owin.Security; -using Umbraco.Core; -using Umbraco.Core.Cache; -using Umbraco.Core.Configuration; -using Umbraco.Core.Configuration.Models; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Web.Mvc; -using Umbraco.Core.Services; -using Umbraco.Web.Features; -using Umbraco.Web.Security; -using Constants = Umbraco.Core.Constants; -using Umbraco.Core.Hosting; -using BackOfficeIdentityUser = Umbraco.Core.BackOffice.BackOfficeIdentityUser; - -namespace Umbraco.Web.Editors -{ - - /// - /// Represents a controller user to render out the default back office view and JS results. - /// - [UmbracoRequireHttps] - [DisableBrowserCache] - public class BackOfficeController : UmbracoController - { - private readonly UmbracoFeatures _features; - private BackOfficeOwinUserManager _userManager; - private BackOfficeSignInManager _signInManager; - private readonly IUmbracoVersion _umbracoVersion; - private readonly ContentSettings _contentSettings; - private readonly IHostingEnvironment _hostingEnvironment; - private readonly RuntimeSettings _runtimeSettings; - private readonly SecuritySettings _securitySettings; - private readonly IIconService _iconService; - private readonly ILogger _logger; - - public BackOfficeController( - UmbracoFeatures features, - IOptions globalSettings, - IUmbracoContextAccessor umbracoContextAccessor, - ServiceContext services, - AppCaches appCaches, - IProfilingLogger profilingLogger, - ILoggerFactory loggerFactory, - IUmbracoVersion umbracoVersion, - IOptions contentSettings, - IHostingEnvironment hostingEnvironment, - IOptions settings, - IOptions securitySettings, - IIconService iconService) - : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, loggerFactory) - - { - _features = features; - _umbracoVersion = umbracoVersion; - _contentSettings = contentSettings.Value; - _hostingEnvironment = hostingEnvironment; - _runtimeSettings = settings.Value; - _securitySettings = securitySettings.Value; - _iconService = iconService; - _logger = loggerFactory.CreateLogger(); - } - - protected BackOfficeSignInManager SignInManager => _signInManager ?? (_signInManager = OwinContext.GetBackOfficeSignInManager()); - - protected BackOfficeOwinUserManager UserManager => _userManager ?? (_userManager = OwinContext.GetBackOfficeUserManager()); - - protected IAuthenticationManager AuthenticationManager => OwinContext.Authentication; - - - // TODO: for converting to netcore, some examples: - // * https://github.com/dotnet/aspnetcore/blob/master/src/Identity/samples/IdentitySample.Mvc/Controllers/AccountController.cs - // * https://github.com/dotnet/aspnetcore/blob/master/src/MusicStore/samples/MusicStore/Controllers/AccountController.cs - [HttpPost] - public ActionResult ExternalLogin(string provider, string redirectUrl = null) - { - if (redirectUrl == null) - { - redirectUrl = Url.Action("Default", "BackOffice"); - } - - // Request a redirect to the external login provider - return new ChallengeResult(provider, redirectUrl); - } - - // TODO: for converting to netcore, some examples: - // * https://github.com/dotnet/aspnetcore/blob/master/src/Identity/samples/IdentitySample.Mvc/Controllers/AccountController.cs - // * https://github.com/dotnet/aspnetcore/blob/master/src/MusicStore/samples/MusicStore/Controllers/AccountController.cs - [UmbracoAuthorize] - [HttpPost] - public ActionResult LinkLogin(string provider) - { - // Request a redirect to the external login provider to link a login for the current user - return new ChallengeResult(provider, - Url.Action("ExternalLinkLoginCallback", "BackOffice"), - User.Identity.GetUserId()); - } - - // TODO: for converting to netcore, some examples: - // * https://github.com/dotnet/aspnetcore/blob/master/src/Identity/samples/IdentitySample.Mvc/Controllers/AccountController.cs - // * https://github.com/dotnet/aspnetcore/blob/master/src/MusicStore/samples/MusicStore/Controllers/AccountController.cs - [HttpGet] - public async Task ExternalLinkLoginCallback() - { - var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync( - Constants.Security.BackOfficeExternalAuthenticationType, - XsrfKey, User.Identity.GetUserId()); - - if (loginInfo == null) - { - //Add error and redirect for it to be displayed - TempData[ViewDataExtensions.TokenExternalSignInError] = new[] { "An error occurred, could not get external login info" }; - return RedirectToLocal(Url.Action("Default", "BackOffice")); - } - - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user == null) throw new InvalidOperationException("Could not find user"); - - var result = await UserManager.AddLoginAsync(user, - new UserLoginInfo(loginInfo.Login.LoginProvider, loginInfo.Login.ProviderKey, loginInfo.Login.LoginProvider)); - if (result.Succeeded) - { - return RedirectToLocal(Url.Action("Default", "BackOffice")); - } - - //Add errors and redirect for it to be displayed - TempData[ViewDataExtensions.TokenExternalSignInError] = result.Errors; - return RedirectToLocal(Url.Action("Default", "BackOffice")); - } - - /// - /// Used by Default and AuthorizeUpgrade to render as per normal if there's no external login info, - /// otherwise process the external login info. - /// - /// - private async Task RenderDefaultOrProcessExternalLoginAsync( - Func defaultResponse, - Func externalSignInResponse) - { - if (defaultResponse == null) throw new ArgumentNullException("defaultResponse"); - if (externalSignInResponse == null) throw new ArgumentNullException("externalSignInResponse"); - - ViewData.SetUmbracoPath(GlobalSettings.Value.GetUmbracoMvcArea(_hostingEnvironment)); - - //check if there is the TempData with the any token name specified, if so, assign to view bag and render the view - if (ViewData.FromTempData(TempData, ViewDataExtensions.TokenExternalSignInError) || - ViewData.FromTempData(TempData, ViewDataExtensions.TokenPasswordResetCode)) - return defaultResponse(); - - //First check if there's external login info, if there's not proceed as normal - var loginInfo = await OwinContext.Authentication.GetExternalLoginInfoAsync( - Constants.Security.BackOfficeExternalAuthenticationType); - - if (loginInfo == null || loginInfo.ExternalIdentity.IsAuthenticated == false) - { - return defaultResponse(); - } - - //we're just logging in with an external source, not linking accounts - return await ExternalSignInAsync(loginInfo, externalSignInResponse); - } - - // TODO: for converting to netcore, some examples: - // * https://github.com/dotnet/aspnetcore/blob/master/src/Identity/samples/IdentitySample.Mvc/Controllers/AccountController.cs - // * https://github.com/dotnet/aspnetcore/blob/master/src/MusicStore/samples/MusicStore/Controllers/AccountController.cs - private async Task ExternalSignInAsync(ExternalLoginInfo loginInfo, Func response) - { - if (loginInfo == null) throw new ArgumentNullException("loginInfo"); - if (response == null) throw new ArgumentNullException("response"); - ExternalSignInAutoLinkOptions autoLinkOptions = null; - - //Here we can check if the provider associated with the request has been configured to allow - // new users (auto-linked external accounts). This would never be used with public providers such as - // Google, unless you for some reason wanted anybody to be able to access the backend if they have a Google account - // .... not likely! - var authType = OwinContext.Authentication.GetExternalAuthenticationTypes().FirstOrDefault(x => x.AuthenticationType == loginInfo.Login.LoginProvider); - if (authType == null) - { - _logger.LogWarning("Could not find external authentication provider registered: {LoginProvider}", loginInfo.Login.LoginProvider); - } - else - { - autoLinkOptions = authType.GetExternalAuthenticationOptions(); - } - - // Sign in the user with this external login provider if the user already has a login - var user = await UserManager.FindByLoginAsync(loginInfo.Login.LoginProvider, loginInfo.Login.ProviderKey); - if (user != null) - { - // TODO: It might be worth keeping some of the claims associated with the ExternalLoginInfo, in which case we - // wouldn't necessarily sign the user in here with the standard login, instead we'd update the - // UseUmbracoBackOfficeExternalCookieAuthentication extension method to have the correct provider and claims factory, - // ticket format, etc.. to create our back office user including the claims assigned and in this method we'd just ensure - // that the ticket is created and stored and that the user is logged in. - - var shouldSignIn = true; - if (autoLinkOptions != null && autoLinkOptions.OnExternalLogin != null) - { - shouldSignIn = autoLinkOptions.OnExternalLogin(user, loginInfo); - if (shouldSignIn == false) - { - _logger.LogWarning("The AutoLinkOptions of the external authentication provider '{LoginProvider}' have refused the login based on the OnExternalLogin method. Affected user id: '{UserId}'", loginInfo.Login.LoginProvider, user.Id); - } - } - - if (shouldSignIn) - { - //sign in - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - } - else - { - if (await AutoLinkAndSignInExternalAccount(loginInfo, autoLinkOptions) == false) - { - ViewData.SetExternalSignInError(new[] { "The requested provider (" + loginInfo.Login.LoginProvider + ") has not been linked to an account" }); - } - - //Remove the cookie otherwise this message will keep appearing - if (Response.Cookies[Constants.Security.BackOfficeExternalCookieName] != null) - { - Response.Cookies[Constants.Security.BackOfficeExternalCookieName].Expires = DateTime.MinValue; - } - } - - return response(); - } - - private async Task AutoLinkAndSignInExternalAccount(ExternalLoginInfo loginInfo, ExternalSignInAutoLinkOptions autoLinkOptions) - { - if (autoLinkOptions == null) - return false; - - if (autoLinkOptions.ShouldAutoLinkExternalAccount(UmbracoContext, loginInfo) == false) - return true; - - //we are allowing auto-linking/creating of local accounts - if (loginInfo.Email.IsNullOrWhiteSpace()) - { - ViewData.SetExternalSignInError(new[] { "The requested provider (" + loginInfo.Login.LoginProvider + ") has not provided an email address, the account cannot be linked." }); - } - else - { - //Now we need to perform the auto-link, so first we need to lookup/create a user with the email address - var foundByEmail = Services.UserService.GetByEmail(loginInfo.Email); - if (foundByEmail != null) - { - ViewData.SetExternalSignInError(new[] { "A user with this email address already exists locally. You will need to login locally to Umbraco and link this external provider: " + loginInfo.Login.LoginProvider }); - } - else - { - if (loginInfo.Email.IsNullOrWhiteSpace()) throw new InvalidOperationException("The Email value cannot be null"); - if (loginInfo.ExternalIdentity.Name.IsNullOrWhiteSpace()) throw new InvalidOperationException("The Name value cannot be null"); - - var groups = Services.UserService.GetUserGroupsByAlias(autoLinkOptions.GetDefaultUserGroups(UmbracoContext, loginInfo)); - - var autoLinkUser = BackOfficeIdentityUser.CreateNew(GlobalSettings.Value, - loginInfo.Email, - loginInfo.Email, - autoLinkOptions.GetDefaultCulture(UmbracoContext, loginInfo)); - autoLinkUser.Name = loginInfo.ExternalIdentity.Name; - foreach (var userGroup in groups) - { - autoLinkUser.AddRole(userGroup.Alias); - } - - //call the callback if one is assigned - if (autoLinkOptions.OnAutoLinking != null) - { - autoLinkOptions.OnAutoLinking(autoLinkUser, loginInfo); - } - - var userCreationResult = await UserManager.CreateAsync(autoLinkUser); - - if (userCreationResult.Succeeded == false) - { - ViewData.SetExternalSignInError(userCreationResult.Errors.Select(x => x.Description).ToList()); - } - else - { - var linkResult = await UserManager.AddLoginAsync(autoLinkUser, - new UserLoginInfo(loginInfo.Login.LoginProvider, loginInfo.Login.ProviderKey, loginInfo.Login.LoginProvider)); - if (linkResult.Succeeded == false) - { - ViewData.SetExternalSignInError(linkResult.Errors.Select(x => x.Description).ToList()); - - //If this fails, we should really delete the user since it will be in an inconsistent state! - var deleteResult = await UserManager.DeleteAsync(autoLinkUser); - if (deleteResult.Succeeded == false) - { - //DOH! ... this isn't good, combine all errors to be shown - ViewData.SetExternalSignInError(linkResult.Errors.Concat(deleteResult.Errors).Select(x => x.Description).ToList()); - } - } - else - { - //sign in - await SignInManager.SignInAsync(autoLinkUser, isPersistent: false, rememberBrowser: false); - } - } - } - - } - return true; - } - - private ActionResult RedirectToLocal(string returnUrl) - { - if (Url.IsLocalUrl(returnUrl)) - { - return Redirect(returnUrl); - } - return Redirect("/"); - } - - // Used for XSRF protection when adding external logins - private const string XsrfKey = "XsrfId"; - - private class ChallengeResult : HttpUnauthorizedResult - { - public ChallengeResult(string provider, string redirectUri, string userId = null) - { - LoginProvider = provider; - RedirectUri = redirectUri; - UserId = userId; - } - - private string LoginProvider { get; set; } - private string RedirectUri { get; set; } - private string UserId { get; set; } - - public override void ExecuteResult(ControllerContext context) - { - //Ensure the forms auth module doesn't do a redirect! - context.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; - - var owinCtx = context.HttpContext.GetOwinContext(); - - //First, see if a custom challenge result callback is specified for the provider - // and use it instead of the default if one is supplied. - var loginProvider = owinCtx.Authentication - .GetExternalAuthenticationTypes() - .FirstOrDefault(p => p.AuthenticationType == LoginProvider); - if (loginProvider != null) - { - var providerChallengeResult = loginProvider.GetSignInChallengeResult(owinCtx); - if (providerChallengeResult != null) - { - owinCtx.Authentication.Challenge(providerChallengeResult, LoginProvider); - return; - } - } - - var properties = new AuthenticationProperties() { RedirectUri = RedirectUri.EnsureEndsWith('/') }; - if (UserId != null) - { - properties.Dictionary[XsrfKey] = UserId; - } - owinCtx.Authentication.Challenge(properties, LoginProvider); - } - } - } -} diff --git a/src/Umbraco.Web/Mvc/BackOfficeArea.cs b/src/Umbraco.Web/Mvc/BackOfficeArea.cs index eeb48c3b38..2c15f83f14 100644 --- a/src/Umbraco.Web/Mvc/BackOfficeArea.cs +++ b/src/Umbraco.Web/Mvc/BackOfficeArea.cs @@ -7,6 +7,7 @@ using Umbraco.Web.Editors; namespace Umbraco.Web.Mvc { // TODO: This has been ported to netcore, can be removed + // Has preview been migrated? internal class BackOfficeArea : AreaRegistration { private readonly GlobalSettings _globalSettings; @@ -35,18 +36,6 @@ namespace Umbraco.Web.Mvc new {controller = "Preview", action = "Index", editor = UrlParameter.Optional}, new[] { "Umbraco.Web.Editors" }); - context.MapRoute( - "Umbraco_back_office", - AreaName + "/{action}/{id}", - new {controller = "BackOffice", action = "Default", id = UrlParameter.Optional}, - //limit the action/id to only allow characters - this is so this route doesn't hog all other - // routes like: /umbraco/channels/word.aspx, etc... - new - { - action = @"[a-zA-Z]*", - id = @"[a-zA-Z]*" - }, - new[] {typeof (BackOfficeController).Namespace}); } public override string AreaName => _globalSettings.GetUmbracoMvcArea(_hostingEnvironment); diff --git a/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs b/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs index 6148535d46..a9127aca17 100644 --- a/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs +++ b/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs @@ -15,22 +15,22 @@ namespace Umbraco.Web.Mvc public sealed class UmbracoAuthorizeAttribute : AuthorizeAttribute { // see note in HttpInstallAuthorizeAttribute - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor; private readonly IRuntimeState _runtimeState; private readonly string _redirectUrl; private IRuntimeState RuntimeState => _runtimeState ?? Current.RuntimeState; - private IBackofficeSecurity BackofficeSecurity => _backofficeSecurityAccessor.BackofficeSecurity ?? Current.UmbracoContext.Security; + private IBackOfficeSecurity BackOfficeSecurity => _backOfficeSecurityAccessor.BackOfficeSecurity ?? Current.UmbracoContext.Security; /// /// THIS SHOULD BE ONLY USED FOR UNIT TESTS /// /// /// - public UmbracoAuthorizeAttribute(IBackofficeSecurityAccessor backofficeSecurityAccessor, IRuntimeState runtimeState) + public UmbracoAuthorizeAttribute(IBackOfficeSecurityAccessor backofficeSecurityAccessor, IRuntimeState runtimeState) { - _backofficeSecurityAccessor = backofficeSecurityAccessor ?? throw new ArgumentNullException(nameof(backofficeSecurityAccessor)); + _backOfficeSecurityAccessor = backofficeSecurityAccessor ?? throw new ArgumentNullException(nameof(backofficeSecurityAccessor)); _runtimeState = runtimeState ?? throw new ArgumentNullException(nameof(runtimeState)); } @@ -76,7 +76,7 @@ namespace Umbraco.Web.Mvc // otherwise we need to ensure that a user is logged in return RuntimeState.Level == RuntimeLevel.Install || RuntimeState.Level == RuntimeLevel.Upgrade - || BackofficeSecurity.ValidateCurrentUser(); + || BackOfficeSecurity.ValidateCurrentUser(); } catch (Exception) { diff --git a/src/Umbraco.Web/Mvc/UmbracoController.cs b/src/Umbraco.Web/Mvc/UmbracoController.cs index be46c30dd9..2e95cd9d8f 100644 --- a/src/Umbraco.Web/Mvc/UmbracoController.cs +++ b/src/Umbraco.Web/Mvc/UmbracoController.cs @@ -69,7 +69,7 @@ namespace Umbraco.Web.Mvc /// /// Gets the web security helper. /// - public virtual IBackofficeSecurity Security => UmbracoContext.Security; + public virtual IBackOfficeSecurity Security => UmbracoContext.Security; protected UmbracoController() : this( diff --git a/src/Umbraco.Web/Security/AuthenticationOptionsExtensions.cs b/src/Umbraco.Web/Security/AuthenticationOptionsExtensions.cs index 73156cec45..e7afbea6a1 100644 --- a/src/Umbraco.Web/Security/AuthenticationOptionsExtensions.cs +++ b/src/Umbraco.Web/Security/AuthenticationOptionsExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.Owin; using Microsoft.Owin.Security; using Umbraco.Core; using Umbraco.Core.Composing; +using Umbraco.Core.Security; using Current = Umbraco.Web.Composing.Current; @@ -11,112 +12,113 @@ namespace Umbraco.Web.Security { public static class AuthenticationOptionsExtensions { + // TODO: Migrate this! - /// - /// When trying to implement an Azure AD B2C provider or other OAuth provider that requires a customized Challenge Result in order to work then - /// this must be used. - /// - /// - /// - /// - /// See: http://issues.umbraco.org/issue/U4-7353 - /// - public static void SetSignInChallengeResultCallback( - this AuthenticationOptions authOptions, - Func authProperties) - { - authOptions.Description.Properties["ChallengeResultCallback"] = authProperties; - } + ///// + ///// When trying to implement an Azure AD B2C provider or other OAuth provider that requires a customized Challenge Result in order to work then + ///// this must be used. + ///// + ///// + ///// + ///// + ///// See: http://issues.umbraco.org/issue/U4-7353 + ///// + //public static void SetSignInChallengeResultCallback( + // this AuthenticationOptions authOptions, + // Func authProperties) + //{ + // authOptions.Description.Properties["ChallengeResultCallback"] = authProperties; + //} - public static AuthenticationProperties GetSignInChallengeResult(this AuthenticationDescription authenticationDescription, IOwinContext ctx) - { - if (authenticationDescription.Properties.ContainsKey("ChallengeResultCallback") == false) return null; - var cb = authenticationDescription.Properties["ChallengeResultCallback"] as Func; - if (cb == null) return null; - return cb(ctx); - } + //public static AuthenticationProperties GetSignInChallengeResult(this AuthenticationDescription authenticationDescription, IOwinContext ctx) + //{ + // if (authenticationDescription.Properties.ContainsKey("ChallengeResultCallback") == false) return null; + // var cb = authenticationDescription.Properties["ChallengeResultCallback"] as Func; + // if (cb == null) return null; + // return cb(ctx); + //} - /// - /// Used during the External authentication process to assign external sign-in options - /// that are used by the Umbraco authentication process. - /// - /// - /// - public static void SetExternalSignInAutoLinkOptions( - this AuthenticationOptions authOptions, - ExternalSignInAutoLinkOptions options) - { - authOptions.Description.Properties["ExternalSignInAutoLinkOptions"] = options; - } + ///// + ///// Used during the External authentication process to assign external sign-in options + ///// that are used by the Umbraco authentication process. + ///// + ///// + ///// + //public static void SetExternalSignInAutoLinkOptions( + // this AuthenticationOptions authOptions, + // ExternalSignInAutoLinkOptions options) + //{ + // authOptions.Description.Properties["ExternalSignInAutoLinkOptions"] = options; + //} - /// - /// Used during the External authentication process to retrieve external sign-in options - /// that have been set with SetExternalAuthenticationOptions - /// - /// - public static ExternalSignInAutoLinkOptions GetExternalAuthenticationOptions(this AuthenticationDescription authenticationDescription) - { - if (authenticationDescription.Properties.ContainsKey("ExternalSignInAutoLinkOptions") == false) return null; - var options = authenticationDescription.Properties["ExternalSignInAutoLinkOptions"] as ExternalSignInAutoLinkOptions; - return options; - } + ///// + ///// Used during the External authentication process to retrieve external sign-in options + ///// that have been set with SetExternalAuthenticationOptions + ///// + ///// + //public static ExternalSignInAutoLinkOptions GetExternalAuthenticationOptions(this AuthenticationDescription authenticationDescription) + //{ + // if (authenticationDescription.Properties.ContainsKey("ExternalSignInAutoLinkOptions") == false) return null; + // var options = authenticationDescription.Properties["ExternalSignInAutoLinkOptions"] as ExternalSignInAutoLinkOptions; + // return options; + //} - /// - /// Configures the properties of the authentication description instance for use with Umbraco back office - /// - /// - /// - /// - /// - /// This is important if the identity provider is to be able to authenticate when upgrading Umbraco. We will try to extract this from - /// any options passed in via reflection since none of the default OWIN providers inherit from a base class but so far all of them have a consistent - /// name for the 'CallbackPath' property which is of type PathString. So we'll try to extract it if it's not found or supplied. - /// - /// If a value is extracted or supplied, this will be added to an internal list which the UmbracoModule will use to allow the request to pass - /// through without redirecting to the installer. - /// - public static void ForUmbracoBackOffice(this AuthenticationOptions options, string style, string icon, string callbackPath = null) - { - if (options == null) throw new ArgumentNullException(nameof(options)); - if (string.IsNullOrEmpty(options.AuthenticationType)) throw new InvalidOperationException("The authentication type can't be null or empty."); + ///// + ///// Configures the properties of the authentication description instance for use with Umbraco back office + ///// + ///// + ///// + ///// + ///// + ///// This is important if the identity provider is to be able to authenticate when upgrading Umbraco. We will try to extract this from + ///// any options passed in via reflection since none of the default OWIN providers inherit from a base class but so far all of them have a consistent + ///// name for the 'CallbackPath' property which is of type PathString. So we'll try to extract it if it's not found or supplied. + ///// + ///// If a value is extracted or supplied, this will be added to an internal list which the UmbracoModule will use to allow the request to pass + ///// through without redirecting to the installer. + ///// + //public static void ForUmbracoBackOffice(this AuthenticationOptions options, string style, string icon, string callbackPath = null) + //{ + // if (options == null) throw new ArgumentNullException(nameof(options)); + // if (string.IsNullOrEmpty(options.AuthenticationType)) throw new InvalidOperationException("The authentication type can't be null or empty."); - //Ensure the prefix is set - if (options.AuthenticationType.StartsWith(Constants.Security.BackOfficeExternalAuthenticationTypePrefix) == false) - { - options.AuthenticationType = Constants.Security.BackOfficeExternalAuthenticationTypePrefix + options.AuthenticationType; - } + // //Ensure the prefix is set + // if (options.AuthenticationType.StartsWith(Constants.Security.BackOfficeExternalAuthenticationTypePrefix) == false) + // { + // options.AuthenticationType = Constants.Security.BackOfficeExternalAuthenticationTypePrefix + options.AuthenticationType; + // } - options.Description.Properties["SocialStyle"] = style; - options.Description.Properties["SocialIcon"] = icon; + // options.Description.Properties["SocialStyle"] = style; + // options.Description.Properties["SocialIcon"] = icon; - //flag for use in back office - options.Description.Properties["UmbracoBackOffice"] = true; + // //flag for use in back office + // options.Description.Properties["UmbracoBackOffice"] = true; - if (callbackPath.IsNullOrWhiteSpace()) - { - try - { - //try to get it with reflection - var prop = options.GetType().GetProperty("CallbackPath"); - if (prop != null && TypeHelper.IsTypeAssignableFrom(prop.PropertyType)) - { - //get the value - var path = (PathString) prop.GetValue(options); - if (path.HasValue) - { - RoutableDocumentFilter.ReservedPaths.TryAdd(path.ToString()); - } - } - } - catch (System.Exception ex) - { - Current.Logger.LogError(ex, "Could not read AuthenticationOptions properties"); - } - } - else - { - RoutableDocumentFilter.ReservedPaths.TryAdd(callbackPath); - } - } + // if (callbackPath.IsNullOrWhiteSpace()) + // { + // try + // { + // //try to get it with reflection + // var prop = options.GetType().GetProperty("CallbackPath"); + // if (prop != null && TypeHelper.IsTypeAssignableFrom(prop.PropertyType)) + // { + // //get the value + // var path = (PathString) prop.GetValue(options); + // if (path.HasValue) + // { + // RoutableDocumentFilter.ReservedPaths.TryAdd(path.ToString()); + // } + // } + // } + // catch (System.Exception ex) + // { + // Current.Logger.LogError(ex, "Could not read AuthenticationOptions properties"); + // } + // } + // else + // { + // RoutableDocumentFilter.ReservedPaths.TryAdd(callbackPath); + // } + //} } } diff --git a/src/Umbraco.Web/Security/BackofficeSecurity.cs b/src/Umbraco.Web/Security/BackofficeSecurity.cs index e5e46ea37f..fb25159e48 100644 --- a/src/Umbraco.Web/Security/BackofficeSecurity.cs +++ b/src/Umbraco.Web/Security/BackofficeSecurity.cs @@ -1,20 +1,12 @@ using System; -using System.Security; -using System.Web; using Umbraco.Core; -using Umbraco.Core.Services; using Umbraco.Core.Models.Membership; -using Microsoft.Owin; -using Umbraco.Core.BackOffice; -using Umbraco.Core.Configuration; -using Umbraco.Core.Hosting; -using Umbraco.Core.Models; namespace Umbraco.Web.Security { // NOTE: Moved to netcore - public class BackofficeSecurity : IBackofficeSecurity + public class BackOfficeSecurity : IBackOfficeSecurity { public IUser CurrentUser => throw new NotImplementedException(); diff --git a/src/Umbraco.Web/Security/IdentityAuditEventArgs.cs b/src/Umbraco.Web/Security/IdentityAuditEventArgs.cs index d37974276c..58d864601e 100644 --- a/src/Umbraco.Web/Security/IdentityAuditEventArgs.cs +++ b/src/Umbraco.Web/Security/IdentityAuditEventArgs.cs @@ -64,7 +64,7 @@ namespace Umbraco.Web.Security AffectedUser = affectedUser; PerformingUser = performingUser == -1 - ? GetCurrentRequestBackofficeUserId() + ? GetCurrentRequestBackOfficeUserId() : performingUser; } @@ -97,7 +97,7 @@ namespace Umbraco.Web.Security Comment = comment; PerformingUser = performingUser == -1 - ? GetCurrentRequestBackofficeUserId() + ? GetCurrentRequestBackOfficeUserId() : performingUser; } @@ -105,7 +105,7 @@ namespace Umbraco.Web.Security /// Returns the current logged in backoffice user's Id logging if there is one /// /// - protected int GetCurrentRequestBackofficeUserId() + protected int GetCurrentRequestBackOfficeUserId() { var userId = -1; var backOfficeIdentity = Thread.CurrentPrincipal.GetUmbracoIdentity(); diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 5f1c733572..fb04f02232 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -157,7 +157,7 @@ - + @@ -247,7 +247,6 @@ - @@ -296,7 +295,6 @@ - diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index a4b6e1dd14..b1ca469dfb 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -30,7 +30,7 @@ namespace Umbraco.Web // warn: does *not* manage setting any IUmbracoContextAccessor internal UmbracoContext(IHttpContextAccessor httpContextAccessor, IPublishedSnapshotService publishedSnapshotService, - IBackofficeSecurity backofficeSecurity, + IBackOfficeSecurity backofficeSecurity, GlobalSettings globalSettings, IHostingEnvironment hostingEnvironment, IVariationContextAccessor variationContextAccessor, @@ -89,7 +89,7 @@ namespace Umbraco.Web /// /// Gets the BackofficeSecurity class /// - public IBackofficeSecurity Security { get; } + public IBackOfficeSecurity Security { get; } /// /// Gets the uri that is handled by ASP.NET after server-side rewriting took place. diff --git a/src/Umbraco.Web/UmbracoContextFactory.cs b/src/Umbraco.Web/UmbracoContextFactory.cs index cc0bd59fa1..fda8026762 100644 --- a/src/Umbraco.Web/UmbracoContextFactory.cs +++ b/src/Umbraco.Web/UmbracoContextFactory.cs @@ -68,7 +68,7 @@ namespace Umbraco.Web _variationContextAccessor.VariationContext = new VariationContext(_defaultCultureAccessor.DefaultCulture); } - return new UmbracoContext(_httpContextAccessor, _publishedSnapshotService, new BackofficeSecurity(), _globalSettings, _hostingEnvironment, _variationContextAccessor, _uriUtility, _cookieManager); + return new UmbracoContext(_httpContextAccessor, _publishedSnapshotService, new BackOfficeSecurity(), _globalSettings, _hostingEnvironment, _variationContextAccessor, _uriUtility, _cookieManager); } /// diff --git a/src/Umbraco.Web/UmbracoHttpHandler.cs b/src/Umbraco.Web/UmbracoHttpHandler.cs index bd8d4415f4..262eeb8560 100644 --- a/src/Umbraco.Web/UmbracoHttpHandler.cs +++ b/src/Umbraco.Web/UmbracoHttpHandler.cs @@ -53,7 +53,7 @@ namespace Umbraco.Web /// /// Gets the web security helper. /// - public IBackofficeSecurity Security => UmbracoContextAccessor.UmbracoContext.Security; + public IBackOfficeSecurity Security => UmbracoContextAccessor.UmbracoContext.Security; /// /// Gets the Url helper. diff --git a/src/Umbraco.Web/UmbracoWebService.cs b/src/Umbraco.Web/UmbracoWebService.cs index 285c9f1803..368a7dd368 100644 --- a/src/Umbraco.Web/UmbracoWebService.cs +++ b/src/Umbraco.Web/UmbracoWebService.cs @@ -63,7 +63,7 @@ namespace Umbraco.Web /// /// Gets the web security helper. /// - public IBackofficeSecurity Security => UmbracoContext.Security; + public IBackOfficeSecurity Security => UmbracoContext.Security; /// /// Gets the Url helper. diff --git a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs index 3434d825fe..b040b3ad7f 100644 --- a/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs +++ b/src/Umbraco.Web/WebApi/UmbracoApiControllerBase.cs @@ -118,7 +118,7 @@ namespace Umbraco.Web.WebApi /// /// Gets the web security helper. /// - public IBackofficeSecurity Security => UmbracoContext.Security; + public IBackOfficeSecurity Security => UmbracoContext.Security; /// /// Tries to get the current HttpContext. diff --git a/src/Umbraco.Web/WebApi/UmbracoAuthorizeAttribute.cs b/src/Umbraco.Web/WebApi/UmbracoAuthorizeAttribute.cs index 83f08660d9..8e414be5ef 100644 --- a/src/Umbraco.Web/WebApi/UmbracoAuthorizeAttribute.cs +++ b/src/Umbraco.Web/WebApi/UmbracoAuthorizeAttribute.cs @@ -20,21 +20,21 @@ namespace Umbraco.Web.WebApi internal static bool Enable = true; // TODO: inject! - private readonly IBackofficeSecurityAccessor _backofficeSecurityAccessor; + private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor; private readonly IRuntimeState _runtimeState; private IRuntimeState RuntimeState => _runtimeState ?? Current.RuntimeState; - private IBackofficeSecurity BackofficeSecurity => _backofficeSecurityAccessor.BackofficeSecurity ?? Current.UmbracoContext.Security; + private IBackOfficeSecurity BackOfficeSecurity => _backOfficeSecurityAccessor.BackOfficeSecurity ?? Current.UmbracoContext.Security; /// /// THIS SHOULD BE ONLY USED FOR UNIT TESTS /// /// /// - public UmbracoAuthorizeAttribute(IBackofficeSecurityAccessor backofficeSecurityAccessor, IRuntimeState runtimeState) + public UmbracoAuthorizeAttribute(IBackOfficeSecurityAccessor backofficeSecurityAccessor, IRuntimeState runtimeState) { - _backofficeSecurityAccessor = backofficeSecurityAccessor ?? throw new ArgumentNullException(nameof(backofficeSecurityAccessor)); + _backOfficeSecurityAccessor = backofficeSecurityAccessor ?? throw new ArgumentNullException(nameof(backofficeSecurityAccessor)); _runtimeState = runtimeState ?? throw new ArgumentNullException(nameof(runtimeState)); } @@ -59,7 +59,7 @@ namespace Umbraco.Web.WebApi // otherwise we need to ensure that a user is logged in return RuntimeState.Level == RuntimeLevel.Install || RuntimeState.Level == RuntimeLevel.Upgrade - || BackofficeSecurity.ValidateCurrentUser(false, _requireApproval) == ValidateRequestAttempt.Success; + || BackOfficeSecurity.ValidateCurrentUser(false, _requireApproval) == ValidateRequestAttempt.Success; } catch (Exception) {