-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathBagPartDisplayDriver.cs
More file actions
299 lines (240 loc) · 13.2 KB
/
BagPartDisplayDriver.cs
File metadata and controls
299 lines (240 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.ContentManagement.Display.Models;
using OrchardCore.ContentManagement.Handlers;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.Contents;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Flows.Models;
using OrchardCore.Flows.ViewModels;
using OrchardCore.Modules;
using OrchardCore.Security.Permissions;
namespace OrchardCore.Flows.Drivers;
public sealed class BagPartDisplayDriver : ContentPartDisplayDriver<BagPart>
{
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly IContentManager _contentManager;
private readonly IServiceProvider _serviceProvider;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger _logger;
private readonly INotifier _notifier;
private readonly IAuthorizationService _authorizationService;
private readonly IEnumerable<IContentHandler> _contentHandlers;
private readonly IEnumerable<IContentHandler> _reversedContentHandlers;
internal readonly IHtmlLocalizer H;
public BagPartDisplayDriver(
IContentManager contentManager,
IContentDefinitionManager contentDefinitionManager,
IServiceProvider serviceProvider,
IHttpContextAccessor httpContextAccessor,
ILogger<BagPartDisplayDriver> logger,
INotifier notifier,
IHtmlLocalizer<BagPartDisplayDriver> htmlLocalizer,
IEnumerable<IContentHandler> contentHandlers,
IAuthorizationService authorizationService
)
{
_contentDefinitionManager = contentDefinitionManager;
_contentManager = contentManager;
_serviceProvider = serviceProvider;
_httpContextAccessor = httpContextAccessor;
_logger = logger;
_notifier = notifier;
H = htmlLocalizer;
_contentHandlers = contentHandlers;
_reversedContentHandlers = contentHandlers.Reverse();
_authorizationService = authorizationService;
}
public override IDisplayResult Display(BagPart bagPart, BuildPartDisplayContext context)
{
var hasItems = bagPart.ContentItems.Count > 0;
return Initialize<BagPartViewModel>(hasItems ? "BagPart" : "BagPart_Empty", m =>
{
m.BagPart = bagPart;
m.BuildPartDisplayContext = context;
m.Settings = context.TypePartDefinition.GetSettings<BagPartSettings>();
})
.Location(OrchardCoreConstants.DisplayType.Detail, "Content")
.Location(OrchardCoreConstants.DisplayType.Summary, "Content");
}
public override IDisplayResult Edit(BagPart bagPart, BuildPartEditorContext context)
{
return Initialize<BagPartEditViewModel>(GetEditorShapeType(context), async m =>
{
var contentDefinitionManager = _serviceProvider.GetRequiredService<IContentDefinitionManager>();
var blocksSettings = context.TypePartDefinition.GetSettings<BagPartBlocksEditorSettings>();
m.BagPart = bagPart;
m.Updater = context.Updater;
m.ContainedContentTypeDefinitions = await GetContainedContentTypesAsync(context.TypePartDefinition);
m.AccessibleWidgets = await GetAccessibleWidgetsAsync(bagPart.ContentItems, contentDefinitionManager);
m.TypePartDefinition = context.TypePartDefinition;
m.AddButtonText = blocksSettings.AddButtonText;
m.ModalTitleText = blocksSettings.ModalTitleText;
});
}
public override async Task<IDisplayResult> UpdateAsync(BagPart part, UpdatePartEditorContext context)
{
var contentItemDisplayManager = _serviceProvider.GetRequiredService<IContentItemDisplayManager>();
var contentDefinitionManager = _serviceProvider.GetRequiredService<IContentDefinitionManager>();
var model = new BagPartEditViewModel { BagPart = part };
await context.Updater.TryUpdateModelAsync(model, Prefix);
var contentItems = new Dictionary<string, ContentItem>();
var existsingContentItems = part.ContentItems.ToDictionary(x => x.ContentItemId, StringComparer.OrdinalIgnoreCase);
// Handle the content found in the request
for (var i = 0; i < model.Prefixes.Length; i++)
{
var contentItem = await _contentManager.NewAsync(model.ContentTypes[i]);
// Try to match the requested id with an existing id
ContentItem existingContentItem = null;
existsingContentItems.TryGetValue(model.ContentItems[i], out existingContentItem);
var contentTypeDefinition = await contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType);
if (existingContentItem == null && !await AuthorizeAsync(contentTypeDefinition, CommonPermissions.EditContent, contentItem))
{
// At this point the user is somehow trying to add content with no privileges. ignore the request
continue;
}
// When the content item already exists merge its elements to preserve nested content item ids.
// All of the data for these merged items is then replaced by the model values on update, while a nested content item id is maintained.
// This prevents nested items which rely on the content item id, i.e. the media attached field, losing their reference point.
if (existingContentItem != null)
{
if (!await AuthorizeAsync(contentTypeDefinition, CommonPermissions.EditContent, existingContentItem))
{
// At this point, the user is somehow modifying existing content with no privileges.
// honor the existing data and ignore the data in the request
contentItems.Add(existingContentItem.ContentItemId, existingContentItem);
continue;
}
// At this point the user have privileges to edit, merge the data from the request
var updateContentContext = new UpdateContentContext(contentItem);
await _contentHandlers.InvokeAsync((handler, context) => handler.UpdatingAsync(context), updateContentContext, _logger);
var cloneContentContext = new CloneContentContext(existingContentItem, contentItem);
await _contentHandlers.InvokeAsync((handler, context) => handler.CloningAsync(context), cloneContentContext, _logger);
contentItem.ContentItemId = model.ContentItems[i];
contentItem.Merge(existingContentItem);
await contentItemDisplayManager.UpdateEditorAsync(contentItem, context.Updater, context.IsNew, htmlFieldPrefix: model.Prefixes[i]);
await _reversedContentHandlers.InvokeAsync((handler, context) => handler.UpdatedAsync(context), updateContentContext, _logger);
}
else
{
var createContentContext = new CreateContentContext(contentItem);
await _contentHandlers.InvokeAsync((handler, context) => handler.CreatingAsync(context), createContentContext, _logger);
await contentItemDisplayManager.UpdateEditorAsync(contentItem, context.Updater, context.IsNew, htmlFieldPrefix: model.Prefixes[i]);
await _reversedContentHandlers.InvokeAsync((handler, context) => handler.CreatedAsync(context), createContentContext, _logger);
}
contentItems.Add(contentItem.ContentItemId, contentItem);
}
// At the end, lets add existing readonly contents.
foreach (var existingContentItem in part.ContentItems)
{
if (contentItems.ContainsKey(existingContentItem.ContentItemId))
{
// Item was already added using the edit.
continue;
}
var contentTypeDefinition = await contentDefinitionManager.GetTypeDefinitionAsync(existingContentItem.ContentType);
if (await AuthorizeAsync(contentTypeDefinition, CommonPermissions.DeleteContent, existingContentItem))
{
// At this point, the user has permission to delete a securable item or the type isn't securable
// if the existing content id isn't in the requested ids, don't add the content item... meaning the user deleted it.
if (!model.ContentItems.Contains(existingContentItem.ContentItemId))
{
continue;
}
}
// Since the content item isn't editable, lets add it so it's not removed from the collection
contentItems.Add(existingContentItem.ContentItemId, existingContentItem);
}
// TODO, some how here contentItems should be sorted by a defined order
part.ContentItems = contentItems.Values.ToList();
return Edit(part, context);
}
private async Task<IEnumerable<BagPartWidgetViewModel>> GetAccessibleWidgetsAsync(IEnumerable<ContentItem> contentItems, IContentDefinitionManager contentDefinitionManager)
{
var widgets = new List<BagPartWidgetViewModel>();
foreach (var contentItem in contentItems)
{
var widget = new BagPartWidgetViewModel
{
ContentItem = contentItem,
Viewable = true,
Editable = true,
Deletable = true,
};
var contentTypeDefinition = await contentDefinitionManager.GetTypeDefinitionAsync(contentItem.ContentType);
if (contentTypeDefinition == null)
{
_logger.LogWarning("The Widget content item with id {ContentItemId} has no matching {ContentType} content type definition.", contentItem.ContentItemId, contentItem.ContentType);
await _notifier.WarningAsync(H["The Widget content item with id {0} has no matching {1} content type definition.", contentItem.ContentItemId, contentItem.ContentType]);
continue;
}
widget.Viewable = await AuthorizeAsync(contentTypeDefinition, CommonPermissions.ViewContent, contentItem);
widget.Editable = await AuthorizeAsync(contentTypeDefinition, CommonPermissions.EditContent, contentItem);
widget.Deletable = await AuthorizeAsync(contentTypeDefinition, CommonPermissions.DeleteContent, contentItem);
widget.ContentTypeDefinition = contentTypeDefinition;
if (widget.Editable || widget.Viewable)
{
widgets.Add(widget);
}
}
return widgets;
}
private async Task<bool> AuthorizeAsync(ContentTypeDefinition contentTypeDefinition, Permission permission, ContentItem contentItem)
{
if (contentTypeDefinition is not null && contentTypeDefinition.IsSecurable())
{
return await AuthorizeAsync(permission, contentItem);
}
return true;
}
private Task<bool> AuthorizeAsync(Permission permission, ContentItem contentItem)
=> _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext.User, permission, contentItem);
private async Task<IEnumerable<ContentTypeDefinition>> GetContainedContentTypesAsync(ContentTypePartDefinition typePartDefinition)
{
var settings = typePartDefinition.GetSettings<BagPartSettings>();
var contentTypes = Enumerable.Empty<ContentTypeDefinition>();
if (settings.ContainedStereotypes != null && settings.ContainedStereotypes.Length > 0)
{
contentTypes = (await _contentDefinitionManager.ListTypeDefinitionsAsync())
.Where(contentType => contentType.HasStereotype() && settings.ContainedStereotypes.Contains(contentType.GetStereotype(), StringComparer.OrdinalIgnoreCase));
}
else if (settings.ContainedContentTypes != null && settings.ContainedContentTypes.Length > 0)
{
var definitions = new List<ContentTypeDefinition>();
foreach (var contentType in settings.ContainedContentTypes)
{
var definition = await _contentDefinitionManager.GetTypeDefinitionAsync(contentType);
if (definition == null)
{
continue;
}
definitions.Add(definition);
}
contentTypes = definitions;
}
var user = _httpContextAccessor.HttpContext.User;
var accessibleContentTypes = new List<ContentTypeDefinition>();
foreach (var contentType in contentTypes)
{
if (contentType.IsSecurable() && !await _authorizationService.AuthorizeContentTypeAsync(user, CommonPermissions.EditContent, contentType, GetCurrentOwner()))
{
continue;
}
accessibleContentTypes.Add(contentType);
}
return accessibleContentTypes;
}
private string GetCurrentOwner()
{
return _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
}
}