Files
Umbraco-CMS/src/Umbraco.Web.BackOffice/Controllers/UserGroupsController.cs

236 lines
9.5 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Umbraco.Cms.Core;
Merge remote-tracking branch 'origin/v8/dev' into netcore/dev # Conflicts: # build/NuSpecs/UmbracoCms.Core.nuspec # build/NuSpecs/UmbracoCms.Web.nuspec # src/SolutionInfo.cs # src/Umbraco.Core/Cache/CacheKeys.cs # src/Umbraco.Core/Composing/TypeFinder.cs # src/Umbraco.Core/Configuration/GlobalSettings.cs # src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs # src/Umbraco.Core/Configuration/IGlobalSettings.cs # src/Umbraco.Core/Configuration/UmbracoSettings/ContentElement.cs # src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs # src/Umbraco.Core/Constants-AppSettings.cs # src/Umbraco.Core/Editors/UserEditorAuthorizationHelper.cs # src/Umbraco.Core/Extensions/StringExtensions.cs # src/Umbraco.Core/Extensions/UriExtensions.cs # src/Umbraco.Core/IO/IOHelper.cs # src/Umbraco.Core/IO/PhysicalFileSystem.cs # src/Umbraco.Core/Media/Exif/MathEx.cs # src/Umbraco.Core/Media/UploadAutoFillProperties.cs # src/Umbraco.Core/Models/Mapping/UserMapDefinition.cs # src/Umbraco.Core/Models/Membership/User.cs # src/Umbraco.Core/Models/UserExtensions.cs # src/Umbraco.Core/Packaging/PackageDefinitionXmlParser.cs # src/Umbraco.Core/PropertyEditors/ListViewConfiguration.cs # src/Umbraco.Core/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs # src/Umbraco.Core/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs # src/Umbraco.Core/Routing/AliasUrlProvider.cs # src/Umbraco.Core/Routing/DefaultUrlProvider.cs # src/Umbraco.Core/Routing/UriUtility.cs # src/Umbraco.Core/Routing/UrlProviderExtensions.cs # src/Umbraco.Core/Runtime/CoreRuntime.cs # src/Umbraco.Core/RuntimeOptions.cs # src/Umbraco.Core/RuntimeState.cs # src/Umbraco.Core/Security/BackOfficeUserStore.cs # src/Umbraco.Core/Security/ContentPermissions.cs # src/Umbraco.Core/Sync/ApplicationUrlHelper.cs # src/Umbraco.Core/Trees/TreeNode.cs # src/Umbraco.Core/Udi.cs # src/Umbraco.Examine.Lucene/BackOfficeExamineSearcher.cs # src/Umbraco.Examine/Umbraco.Examine.csproj # src/Umbraco.Infrastructure/Examine/ContentValueSetValidator.cs # src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs # src/Umbraco.Infrastructure/Packaging/PackageDataInstallation.cs # src/Umbraco.Infrastructure/Persistence/SqlSyntax/SqlServerSyntaxProvider.cs # src/Umbraco.Infrastructure/Scoping/Scope.cs # src/Umbraco.Infrastructure/Search/ExamineComponent.cs # src/Umbraco.Infrastructure/Security/IdentityMapDefinition.cs # src/Umbraco.Infrastructure/Services/Implement/ContentService.cs # src/Umbraco.Infrastructure/Services/Implement/MediaService.cs # src/Umbraco.Infrastructure/Services/Implement/NotificationService.cs # src/Umbraco.Persistence.SqlCe/SqlCeSyntaxProvider.cs # src/Umbraco.Tests.Integration/Umbraco.Infrastructure/Persistence/LocksTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Core/Models/UserExtensionsTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Editors/UserEditorAuthorizationHelperTests.cs # src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/Examine/UmbracoContentValueSetValidatorTests.cs # src/Umbraco.Tests/Configurations/UmbracoSettings/ContentElementTests.cs # src/Umbraco.Tests/Configurations/UmbracoSettings/umbracoSettings.config # src/Umbraco.Tests/TestHelpers/SettingsForTests.cs # src/Umbraco.Tests/Testing/TestDatabase.cs # src/Umbraco.Tests/Web/Controllers/ContentControllerUnitTests.cs # src/Umbraco.Tests/Web/Controllers/FilterAllowedOutgoingContentAttributeTests.cs # src/Umbraco.Tests/Web/Controllers/MediaControllerUnitTests.cs # src/Umbraco.Web.BackOffice/Controllers/BackOfficeServerVariables.cs # src/Umbraco.Web.BackOffice/Controllers/CodeFileController.cs # src/Umbraco.Web.BackOffice/Controllers/ContentController.cs # src/Umbraco.Web.BackOffice/Controllers/EntityController.cs # src/Umbraco.Web.BackOffice/Controllers/MacrosController.cs # src/Umbraco.Web.BackOffice/Controllers/MediaController.cs # src/Umbraco.Web.BackOffice/Controllers/PackageInstallController.cs # src/Umbraco.Web.BackOffice/Controllers/TourController.cs # src/Umbraco.Web.BackOffice/Controllers/UserGroupEditorAuthorizationHelper.cs # src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingContentAttribute.cs # src/Umbraco.Web.BackOffice/Filters/FilterAllowedOutgoingMediaAttribute.cs # src/Umbraco.Web.BackOffice/Mapping/ContentMapDefinition.cs # src/Umbraco.Web.BackOffice/Services/IconService.cs # src/Umbraco.Web.BackOffice/Trees/ContentTreeController.cs # src/Umbraco.Web.BackOffice/Trees/ContentTreeControllerBase.cs # src/Umbraco.Web.BackOffice/Trees/FileSystemTreeController.cs # src/Umbraco.Web.BackOffice/Trees/MediaTreeController.cs # src/Umbraco.Web.Common/Extensions/FormCollectionExtensions.cs # src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js # src/Umbraco.Web.UI.Client/src/views/content/overlays/publish.html # src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/media.controller.js # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/da.xml # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en.xml # src/Umbraco.Web.UI.NetCore/umbraco/config/lang/en_us.xml # src/Umbraco.Web.UI/config/umbracoSettings.Release.config # src/Umbraco.Web/Cache/MemberCacheRefresher.cs # src/Umbraco.Web/Composing/ModuleInjector.cs # src/Umbraco.Web/Editors/BackOfficeController.cs # src/Umbraco.Web/Editors/Binders/ContentModelBinderHelper.cs # src/Umbraco.Web/Editors/ContentTypeController.cs # src/Umbraco.Web/Editors/Filters/ContentSaveValidationAttribute.cs # src/Umbraco.Web/Editors/Filters/MediaItemSaveValidationAttribute.cs # src/Umbraco.Web/Editors/Filters/UserGroupAuthorizationAttribute.cs # src/Umbraco.Web/Editors/TinyMceController.cs # src/Umbraco.Web/Editors/UserGroupsController.cs # src/Umbraco.Web/Editors/UsersController.cs # src/Umbraco.Web/ImageCropperTemplateExtensions.cs # src/Umbraco.Web/Logging/WebProfiler.cs # src/Umbraco.Web/Logging/WebProfilerProvider.cs # src/Umbraco.Web/Macros/PublishedContentHashtableConverter.cs # src/Umbraco.Web/Mvc/EnsurePublishedContentRequestAttribute.cs # src/Umbraco.Web/Mvc/JsonNetResult.cs # src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs # src/Umbraco.Web/Mvc/RenderRouteHandler.cs # src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs # src/Umbraco.Web/PropertyEditors/MultiNodeTreePickerPropertyEditor.cs # src/Umbraco.Web/PublishedCache/NuCache/DataSource/DatabaseDataSource.cs # src/Umbraco.Web/RoutableDocumentFilter.cs # src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs # src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs # src/Umbraco.Web/Routing/PublishedRouter.cs # src/Umbraco.Web/Runtime/WebInitialComposer.cs # src/Umbraco.Web/Scheduling/KeepAlive.cs # src/Umbraco.Web/Security/AppBuilderExtensions.cs # src/Umbraco.Web/Security/BackOfficeClaimsIdentityFactory.cs # src/Umbraco.Web/Security/Providers/UmbracoMembershipProvider.cs # src/Umbraco.Web/Trees/DictionaryTreeController.cs # src/Umbraco.Web/Trees/LanguageTreeController.cs # src/Umbraco.Web/Trees/LogViewerTreeController.cs # src/Umbraco.Web/Trees/PackagesTreeController.cs # src/Umbraco.Web/UmbracoApplication.cs # src/Umbraco.Web/UmbracoApplicationBase.cs # src/Umbraco.Web/UmbracoInjectedModule.cs # src/Umbraco.Web/WebApi/Filters/AdminUsersAuthorizeAttribute.cs # src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs # src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForContentAttribute.cs # src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForMediaAttribute.cs # src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs
2021-03-05 15:36:27 +01:00
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Web.BackOffice.Filters;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Extensions;
namespace Umbraco.Cms.Web.BackOffice.Controllers;
[PluginController(Constants.Web.Mvc.BackOfficeApiArea)]
[Authorize(Policy = AuthorizationPolicies.SectionAccessUsers)]
[PrefixlessBodyModelValidator]
public class UserGroupsController : BackOfficeNotificationsController
{
private readonly AppCaches _appCaches;
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly IContentService _contentService;
private readonly IEntityService _entityService;
private readonly ILocalizedTextService _localizedTextService;
private readonly IMediaService _mediaService;
private readonly IShortStringHelper _shortStringHelper;
private readonly IUmbracoMapper _umbracoMapper;
private readonly IUserService _userService;
public UserGroupsController(
IUserService userService,
IContentService contentService,
IEntityService entityService,
IMediaService mediaService,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
IUmbracoMapper umbracoMapper,
ILocalizedTextService localizedTextService,
IShortStringHelper shortStringHelper,
AppCaches appCaches)
{
_userService = userService ?? throw new ArgumentNullException(nameof(userService));
_contentService = contentService ?? throw new ArgumentNullException(nameof(contentService));
_entityService = entityService ?? throw new ArgumentNullException(nameof(entityService));
_mediaService = mediaService ?? throw new ArgumentNullException(nameof(mediaService));
_backofficeSecurityAccessor = backofficeSecurityAccessor ??
throw new ArgumentNullException(nameof(backofficeSecurityAccessor));
_umbracoMapper = umbracoMapper ?? throw new ArgumentNullException(nameof(umbracoMapper));
_localizedTextService =
localizedTextService ?? throw new ArgumentNullException(nameof(localizedTextService));
_shortStringHelper = shortStringHelper ?? throw new ArgumentNullException(nameof(shortStringHelper));
_appCaches = appCaches ?? throw new ArgumentNullException(nameof(appCaches));
}
[UserGroupValidate]
public ActionResult<UserGroupDisplay?> PostSaveUserGroup(UserGroupSave userGroupSave)
{
if (userGroupSave == null)
{
throw new ArgumentNullException(nameof(userGroupSave));
}
//authorize that the user has access to save this user group
var authHelper = new UserGroupEditorAuthorizationHelper(
_userService, _contentService, _mediaService, _entityService, _appCaches);
Attempt<string?> isAuthorized =
authHelper.AuthorizeGroupAccess(_backofficeSecurityAccessor.BackOfficeSecurity?.CurrentUser, userGroupSave.Alias);
if (isAuthorized == false)
{
return 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,
userGroupSave.PersistedUserGroup?.AllowedSections,
userGroupSave.Sections);
if (isAuthorized == false)
{
return 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,
userGroupSave.PersistedUserGroup?.StartContentId,
userGroupSave.StartContentId,
userGroupSave.PersistedUserGroup?.StartMediaId,
userGroupSave.StartMediaId);
if (isAuthorized == false)
{
return Unauthorized(isAuthorized.Result);
}
//need to ensure current user is in a group if not an admin to avoid a 401
EnsureNonAdminUserIsInSavedUserGroup(userGroupSave);
//map the model to the persisted instance
_umbracoMapper.Map(userGroupSave, userGroupSave.PersistedUserGroup);
if (userGroupSave.PersistedUserGroup is not null)
{
//save the group
_userService.Save(userGroupSave.PersistedUserGroup, userGroupSave.Users?.ToArray());
}
//deal with permissions
//remove ones that have been removed
var existing = _userService.GetPermissions(userGroupSave.PersistedUserGroup, true)
.ToDictionary(x => x.EntityId, x => x);
if (userGroupSave.AssignedPermissions is not null)
{
IEnumerable<int> toRemove = existing.Keys.Except(userGroupSave.AssignedPermissions.Select(x => x.Key));
foreach (var contentId in toRemove)
{
_userService.RemoveUserGroupPermissions(userGroupSave.PersistedUserGroup?.Id ?? default, contentId);
}
//update existing
foreach (KeyValuePair<int, IEnumerable<string>> assignedPermission in userGroupSave.AssignedPermissions)
{
_userService.ReplaceUserGroupPermissions(
userGroupSave.PersistedUserGroup?.Id ?? default,
assignedPermission.Value.Select(x => x[0]),
assignedPermission.Key);
}
}
UserGroupDisplay? display = _umbracoMapper.Map<UserGroupDisplay>(userGroupSave.PersistedUserGroup);
display?.AddSuccessNotification(
_localizedTextService.Localize("speechBubbles", "operationSavedHeader"),
_localizedTextService.Localize("speechBubbles", "editUserGroupSaved"));
return display;
}
private void EnsureNonAdminUserIsInSavedUserGroup(UserGroupSave userGroupSave)
{
if (_backofficeSecurityAccessor.BackOfficeSecurity?.CurrentUser?.IsAdmin() ?? false)
{
return;
}
var userIds = userGroupSave.Users?.ToList();
if (_backofficeSecurityAccessor.BackOfficeSecurity?.CurrentUser is null ||
userIds is null ||
userIds.Contains(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id))
{
return;
}
userIds.Add(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
userGroupSave.Users = userIds;
}
/// <summary>
/// Returns the scaffold for creating a new user group
/// </summary>
/// <returns></returns>
public UserGroupDisplay? GetEmptyUserGroup() =>
_umbracoMapper.Map<UserGroupDisplay>(new UserGroup(_shortStringHelper));
/// <summary>
/// Returns all user groups
/// </summary>
/// <returns></returns>
public IEnumerable<UserGroupBasic> GetUserGroups(bool onlyCurrentUserGroups = true)
{
var allGroups = _umbracoMapper.MapEnumerable<IUserGroup, UserGroupBasic>(_userService.GetAllUserGroups())
.ToList();
var isAdmin = _backofficeSecurityAccessor.BackOfficeSecurity?.CurrentUser?.IsAdmin() ?? false;
if (isAdmin)
{
return allGroups;
}
if (onlyCurrentUserGroups == false)
{
//this user is not an admin so in that case we need to exclude all admin users
allGroups.RemoveAt(
allGroups.IndexOf(allGroups.Find(basic => basic.Alias == Constants.Security.AdminGroupAlias)!));
return allGroups;
}
//we cannot return user groups that this user does not have access to
var currentUserGroups = _backofficeSecurityAccessor.BackOfficeSecurity?.CurrentUser?.Groups.Select(x => x.Alias)
.ToArray();
return allGroups.WhereNotNull().Where(x => currentUserGroups?.Contains(x.Alias) ?? false).ToArray();
}
/// <summary>
/// Return a user group
/// </summary>
/// <returns></returns>
[Authorize(Policy = AuthorizationPolicies.UserBelongsToUserGroupInRequest)]
public ActionResult<UserGroupDisplay?> GetUserGroup(int id)
{
IUserGroup? found = _userService.GetUserGroupById(id);
if (found == null)
{
return NotFound();
}
UserGroupDisplay? display = _umbracoMapper.Map<UserGroupDisplay>(found);
return display;
}
[HttpPost]
[HttpDelete]
[Authorize(Policy = AuthorizationPolicies.UserBelongsToUserGroupInRequest)]
public IActionResult PostDeleteUserGroups([FromQuery] int[] userGroupIds)
{
IUserGroup[] userGroups = _userService.GetAllUserGroups(userGroupIds)
//never delete the admin group, sensitive data or translators group
.Where(x => !x.IsSystemUserGroup())
.ToArray();
foreach (IUserGroup userGroup in userGroups)
{
_userService.DeleteUserGroup(userGroup);
}
if (userGroups.Length > 1)
{
return Ok(_localizedTextService.Localize("speechBubbles", "deleteUserGroupsSuccess", new[] { userGroups.Length.ToString() }));
}
return Ok(_localizedTextService.Localize("speechBubbles", "deleteUserGroupSuccess", new[] { userGroups[0].Name }));
}
}