-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Performance: Add create-and-publish and update-and-publish endpoints #21284
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
779260a
Introduce create/update and publish management API controllers.
AndyButland 4ae686d
Optimise by not retrieving the content that we have just created/upda…
AndyButland 31fc0a1
Merge branch 'main' into v17/improvement/save-and-publish
AndyButland 246eb4a
Apply code-reuse suggestions from review.
AndyButland fdc61f6
Add controller integration tests for authorization.
AndyButland e02776d
Update OpenApi.json.
AndyButland 9271e1c
Merge branch 'refs/heads/main' into v17/improvement/save-and-publish
kjac e8f62cc
Merge branch 'main' into v17/improvement/save-and-publish
kjac File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
105 changes: 105 additions & 0 deletions
105
src/Umbraco.Cms.Api.Management/Controllers/Document/CreateAndPublishDocumentController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| using Asp.Versioning; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Umbraco.Cms.Api.Management.Factories; | ||
| using Umbraco.Cms.Api.Management.ViewModels.Document; | ||
| using Umbraco.Cms.Core; | ||
| using Umbraco.Cms.Core.Actions; | ||
| using Umbraco.Cms.Core.Models.ContentEditing; | ||
| using Umbraco.Cms.Core.Models.ContentPublishing; | ||
| using Umbraco.Cms.Core.Security; | ||
| using Umbraco.Cms.Core.Security.Authorization; | ||
| using Umbraco.Cms.Core.Services; | ||
| using Umbraco.Cms.Core.Services.OperationStatus; | ||
| using Umbraco.Cms.Web.Common.Authorization; | ||
| using Umbraco.Extensions; | ||
|
|
||
| namespace Umbraco.Cms.Api.Management.Controllers.Document; | ||
|
|
||
| [ApiVersion("1.0")] | ||
| public class CreateAndPublishDocumentController : DocumentControllerBase | ||
| { | ||
| private readonly IAuthorizationService _authorizationService; | ||
| private readonly IDocumentEditingPresentationFactory _documentEditingPresentationFactory; | ||
| private readonly IContentEditingService _contentEditingService; | ||
| private readonly IContentPublishingService _contentPublishingService; | ||
| private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor; | ||
|
|
||
| public CreateAndPublishDocumentController( | ||
| IAuthorizationService authorizationService, | ||
| IDocumentEditingPresentationFactory documentEditingPresentationFactory, | ||
| IContentEditingService contentEditingService, | ||
| IContentPublishingService contentPublishingService, | ||
| IBackOfficeSecurityAccessor backOfficeSecurityAccessor) | ||
| { | ||
| _authorizationService = authorizationService; | ||
| _documentEditingPresentationFactory = documentEditingPresentationFactory; | ||
| _contentEditingService = contentEditingService; | ||
| _contentPublishingService = contentPublishingService; | ||
| _backOfficeSecurityAccessor = backOfficeSecurityAccessor; | ||
| } | ||
|
|
||
| [HttpPost("create-and-publish")] | ||
| [MapToApiVersion("1.0")] | ||
| [ProducesResponseType(StatusCodes.Status201Created)] | ||
| [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] | ||
| [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] | ||
| public async Task<IActionResult> CreateAndPublish( | ||
| CancellationToken cancellationToken, | ||
| CreateAndPublishDocumentRequestModel requestModel) | ||
| { | ||
| // Authorize both create and publish permissions upfront. | ||
| AuthorizationResult createAuthorizationResult = await _authorizationService.AuthorizeResourceAsync( | ||
| User, | ||
| ContentPermissionResource.WithKeys(ActionNew.ActionLetter, requestModel.Parent?.Id), | ||
| AuthorizationPolicies.ContentPermissionByResource); | ||
|
|
||
| AuthorizationResult publishAuthorizationResult = await _authorizationService.AuthorizeResourceAsync( | ||
| User, | ||
| ContentPermissionResource.WithKeys(ActionPublish.ActionLetter, requestModel.Parent?.Id, requestModel.Cultures.OfType<string>()), | ||
| AuthorizationPolicies.ContentPermissionByResource); | ||
|
|
||
| if (createAuthorizationResult.Succeeded is false || publishAuthorizationResult.Succeeded is false) | ||
| { | ||
| return Forbidden(); | ||
| } | ||
|
|
||
| // Create the document. | ||
| ContentCreateModel createModel = _documentEditingPresentationFactory.MapCreateModel(requestModel); | ||
| Attempt<ContentCreateResult, ContentEditingOperationStatus> createResult = | ||
| await _contentEditingService.CreateAsync(createModel, CurrentUserKey(_backOfficeSecurityAccessor)); | ||
|
|
||
| if (createResult.Success is false) | ||
| { | ||
| return ContentEditingOperationStatusResult(createResult.Status); | ||
| } | ||
|
|
||
| // If create had validation errors, don't attempt to publish - it will fail. | ||
| if (createResult.Status == ContentEditingOperationStatus.PropertyValidationError) | ||
| { | ||
| return DocumentPublishingOperationStatusResult( | ||
| ContentPublishingOperationStatus.ContentInvalid, | ||
| invalidPropertyAliases: createResult.Result.ValidationResult.ValidationErrors.Select(e => e.Alias)); | ||
| } | ||
|
|
||
| // Build immediate publish model (no schedule). | ||
| IList<CulturePublishScheduleModel> culturePublishSchedules = GetImmediateCulturePublishSchedule(requestModel.Cultures); | ||
|
|
||
| // Publish the document immediately using the already-loaded content. | ||
| // Skip validation since create succeeded with no validation errors. | ||
| Attempt<ContentPublishingResult, ContentPublishingOperationStatus> publishResult = | ||
| await _contentPublishingService.PublishAsync( | ||
| createResult.Result.Content!, | ||
| culturePublishSchedules, | ||
| CurrentUserKey(_backOfficeSecurityAccessor), | ||
| skipValidation: true); | ||
|
|
||
| if (publishResult.Success is false) | ||
| { | ||
| return DocumentPublishingOperationStatusResult(publishResult.Status, invalidPropertyAliases: publishResult.Result.InvalidPropertyAliases); | ||
| } | ||
|
|
||
| return CreatedAtId<ByKeyDocumentController>(controller => nameof(controller.ByKey), createResult.Result.Content!.Key); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 106 additions & 0 deletions
106
src/Umbraco.Cms.Api.Management/Controllers/Document/UpdateAndPublishDocumentController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| using Asp.Versioning; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Umbraco.Cms.Api.Management.Factories; | ||
| using Umbraco.Cms.Api.Management.ViewModels.Document; | ||
| using Umbraco.Cms.Core; | ||
| using Umbraco.Cms.Core.Actions; | ||
| using Umbraco.Cms.Core.Models.ContentEditing; | ||
| using Umbraco.Cms.Core.Models.ContentPublishing; | ||
| using Umbraco.Cms.Core.Security; | ||
| using Umbraco.Cms.Core.Security.Authorization; | ||
| using Umbraco.Cms.Core.Services; | ||
| using Umbraco.Cms.Core.Services.OperationStatus; | ||
| using Umbraco.Cms.Web.Common.Authorization; | ||
| using Umbraco.Extensions; | ||
|
|
||
| namespace Umbraco.Cms.Api.Management.Controllers.Document; | ||
|
|
||
| [ApiVersion("1.0")] | ||
| public class UpdateAndPublishDocumentController : DocumentControllerBase | ||
| { | ||
| private readonly IAuthorizationService _authorizationService; | ||
| private readonly IDocumentEditingPresentationFactory _documentEditingPresentationFactory; | ||
| private readonly IContentEditingService _contentEditingService; | ||
| private readonly IContentPublishingService _contentPublishingService; | ||
| private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor; | ||
|
|
||
| public UpdateAndPublishDocumentController( | ||
| IAuthorizationService authorizationService, | ||
| IDocumentEditingPresentationFactory documentEditingPresentationFactory, | ||
| IContentEditingService contentEditingService, | ||
| IContentPublishingService contentPublishingService, | ||
| IBackOfficeSecurityAccessor backOfficeSecurityAccessor) | ||
| { | ||
| _authorizationService = authorizationService; | ||
| _documentEditingPresentationFactory = documentEditingPresentationFactory; | ||
| _contentEditingService = contentEditingService; | ||
| _contentPublishingService = contentPublishingService; | ||
| _backOfficeSecurityAccessor = backOfficeSecurityAccessor; | ||
| } | ||
|
|
||
| [HttpPut("{id:guid}/update-and-publish")] | ||
| [MapToApiVersion("1.0")] | ||
| [ProducesResponseType(StatusCodes.Status200OK)] | ||
| [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] | ||
| [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] | ||
| public async Task<IActionResult> UpdateAndPublish( | ||
| CancellationToken cancellationToken, | ||
| Guid id, | ||
| UpdateAndPublishDocumentRequestModel requestModel) | ||
| { | ||
| // Authorize both update and publish permissions upfront. | ||
| AuthorizationResult updateAuthorizationResult = await _authorizationService.AuthorizeResourceAsync( | ||
| User, | ||
| ContentPermissionResource.WithKeys(ActionUpdate.ActionLetter, id), | ||
| AuthorizationPolicies.ContentPermissionByResource); | ||
|
|
||
| AuthorizationResult publishAuthorizationResult = await _authorizationService.AuthorizeResourceAsync( | ||
| User, | ||
| ContentPermissionResource.WithKeys(ActionPublish.ActionLetter, id, requestModel.Cultures.OfType<string>()), | ||
| AuthorizationPolicies.ContentPermissionByResource); | ||
|
|
||
| if (updateAuthorizationResult.Succeeded is false || publishAuthorizationResult.Succeeded is false) | ||
| { | ||
| return Forbidden(); | ||
| } | ||
|
|
||
| // Update the document. | ||
| ContentUpdateModel updateModel = _documentEditingPresentationFactory.MapUpdateModel(requestModel); | ||
| Attempt<ContentUpdateResult, ContentEditingOperationStatus> updateResult = | ||
| await _contentEditingService.UpdateAsync(id, updateModel, CurrentUserKey(_backOfficeSecurityAccessor)); | ||
|
|
||
| if (updateResult.Success is false) | ||
| { | ||
| return ContentEditingOperationStatusResult(updateResult.Status); | ||
| } | ||
|
|
||
| // If update had validation errors, don't attempt to publish - it will fail. | ||
| if (updateResult.Status == ContentEditingOperationStatus.PropertyValidationError) | ||
| { | ||
| return DocumentPublishingOperationStatusResult( | ||
| ContentPublishingOperationStatus.ContentInvalid, | ||
| invalidPropertyAliases: updateResult.Result.ValidationResult.ValidationErrors.Select(e => e.Alias)); | ||
| } | ||
|
|
||
| // Build immediate publish model (no schedule). | ||
| IList<CulturePublishScheduleModel> culturePublishSchedules = GetImmediateCulturePublishSchedule(requestModel.Cultures); | ||
|
|
||
| // Publish the document immediately using the already-loaded content. | ||
| // Skip validation since update succeeded with no validation errors. | ||
| Attempt<ContentPublishingResult, ContentPublishingOperationStatus> publishResult = | ||
| await _contentPublishingService.PublishAsync( | ||
| updateResult.Result.Content!, | ||
| culturePublishSchedules, | ||
| CurrentUserKey(_backOfficeSecurityAccessor), | ||
| skipValidation: true); | ||
|
|
||
| if (publishResult.Success is false) | ||
| { | ||
| return DocumentPublishingOperationStatusResult(publishResult.Status, invalidPropertyAliases: publishResult.Result.InvalidPropertyAliases); | ||
| } | ||
|
|
||
| return Ok(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Missing cross-site request forgery token validation High
Copilot Autofix
AI 6 months ago
In general, the fix is to ensure that any state-changing POST action that can be called from a browser with cookie-based authentication validates an anti-forgery token. In ASP.NET Core MVC/Web API controllers using
[ApiController]-style patterns, the common approach is to add[ValidateAntiForgeryToken](or the ASP.NET Core equivalent[AutoValidateAntiforgeryToken]at a broader scope) on POST actions, and ensure clients send the token with their requests.For this specific controller, the minimal, non-breaking change is to decorate the
CreateAndPublishPOST action with the anti-forgery validation attribute while leaving the rest of the logic untouched. The project already usesMicrosoft.AspNetCore.Mvc, which definesValidateAntiForgeryTokenAttribute, so no new imports are needed. Concretely, insrc/Umbraco.Cms.Api.Management/Controllers/Document/CreateAndPublishDocumentController.cs, just above theCreateAndPublishmethod (around line 48), add[ValidateAntiForgeryToken]alongside the existing attributes ([HttpPost("create-and-publish")],[MapToApiVersion("1.0")], etc.). This will cause ASP.NET Core’s anti-forgery system to validate the token whenever this method is invoked via an HTTP POST, reusing the existing infrastructure without changing the method body or signatures.