Repository navigation
Expand file tree
/
Copy pathBaseProductController.cs
More file actions
698 lines (607 loc) · 32.8 KB
/
Copy pathBaseProductController.cs
File metadata and controls
698 lines (607 loc) · 32.8 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
using Grand.Business.Core.Dto;
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Business.Core.Interfaces.Storage;
using Grand.Business.Core.Utilities.Catalog;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Permissions;
using Grand.SharedKernel.Extensions;
using Grand.Web.AdminShared.Extensions.Mapping;
using Grand.Web.AdminShared.Interfaces;
using Grand.Web.AdminShared.Models.Catalog;
using Grand.Web.AdminShared.Models.Orders;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Extensions;
using Grand.Web.Common.Filters;
using Grand.Web.Common.Localization;
using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.AdminShared.Controllers;
[PermissionAuthorize(PermissionSystemName.Products)]
[AutoValidateAntiforgeryToken]
public abstract class BaseProductController(
IProductViewModelService productViewModelService,
IProductAddPopupViewModelService productAddPopupViewModelService,
IProductService productService,
ILanguageService languageService,
IRequestTranslationService translationService,
IDateTimeService dateTimeService,
IRequestPermissionService permissionService,
IAdminDataScope<Product> scope)
: BaseController
{
protected virtual void EditWarningCheck(Product product) { }
protected IRequestTranslationService TranslationService => translationService;
protected IAdminDataScope<Product> Scope => scope;
#region Product list / create / edit / delete
public IActionResult Index() => RedirectToAction("List");
public async Task<IActionResult> List()
{
var model = await productViewModelService.PrepareProductListModel();
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.List)]
[HttpPost]
public async Task<IActionResult> ProductList(DataSourceRequest command, ProductListModel model)
{
if (scope.DefaultStoreId is not null) model.SearchStoreId = scope.DefaultStoreId;
var (productModels, totalCount) =
await productViewModelService.PrepareProductsModel(model, command.Page, command.PageSize);
return Json(new DataSourceResult { Data = productModels.ToList(), Total = totalCount });
}
[PermissionAuthorizeAction(PermissionActionName.Preview)]
[HttpPost]
public async Task<IActionResult> GoToSku(ProductListModel model)
{
var product = await productService.GetProductBySku(model.GoDirectlyToSku);
if (product != null)
{
if (!await scope.HasAccess(product))
return RedirectToAction("List", "Product");
return RedirectToAction("Edit", "Product", new { id = product.Id });
}
Warning(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.List.SkuNotFound"));
return RedirectToAction("List", "Product");
}
[PermissionAuthorizeAction(PermissionActionName.Create)]
public async Task<IActionResult> Create()
{
var model = new ProductModel { StoreId = scope.DefaultStoreId };
await productViewModelService.PrepareProductModel(model, null, true, true);
await AddLocales(languageService, model.Locales);
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Create)]
[HttpPost]
[ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
public async Task<IActionResult> Create(ProductModel model, bool continueEditing)
{
if (await productViewModelService.StockChangeRefused(model) is { } stockRefused)
ModelState.AddModelError("", stockRefused);
if (await productViewModelService.TrackingChangeRefused(null, model) is { } trackingRefused)
ModelState.AddModelError("", trackingRefused);
if (ModelState.IsValid)
{
if (scope.DefaultStoreId is not null)
{
model.Stores = [scope.DefaultStoreId];
model.StoreId = scope.DefaultStoreId;
}
var product = await productViewModelService.InsertProductModel(model);
Success(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Added"));
return continueEditing ? RedirectToAction("Edit", new { id = product.Id }) : RedirectToAction("List");
}
if (scope.DefaultStoreId is not null) model.StoreId = scope.DefaultStoreId;
await productViewModelService.PrepareProductModel(model, null, false, true);
return View(model);
}
/// <param name="popup">
/// true: the screen opened inside a popup of the bulk-edit grid (EditPopup) - no panel chrome,
/// only the quick-edit tabs shown, and every save stays in the popup.
/// </param>
[PermissionAuthorizeAction(PermissionActionName.Preview)]
public async Task<IActionResult> Edit(string id, bool popup = false)
{
var product = await productService.GetProductById(id, true);
if (product == null) return RedirectToAction("List");
EditWarningCheck(product);
// CanView, not HasAccess: viewing a shared/global product is allowed on Store (with a warning
// from EditWarningCheck above); only mutating one is restricted to the exclusive single-store
// owner. See IAdminDataScope<TEntity>.CanView's doc comment and StoreAdminDataScope.CanView.
if (!await scope.CanView(product)) return RedirectToAction("List");
var model = product.ToModel(dateTimeService);
//seen but not owned (Store: a product shared with other stores): the tabs render without the
//buttons that write; every write action still checks HasAccess itself
model.IsReadOnly = !await scope.HasAccess(product);
if (scope.DefaultStoreId is not null) model.StoreId = scope.DefaultStoreId;
await productViewModelService.PrepareProductModel(model, product, false, false);
await AddLocales(languageService, model.Locales, (locale, languageId) =>
{
locale.Name = product.GetTranslation(x => x.Name, languageId, false);
locale.ShortDescription = product.GetTranslation(x => x.ShortDescription, languageId, false);
locale.FullDescription = product.GetTranslation(x => x.FullDescription, languageId, false);
locale.MetaKeywords = product.GetTranslation(x => x.MetaKeywords, languageId, false);
locale.MetaDescription = product.GetTranslation(x => x.MetaDescription, languageId, false);
locale.MetaTitle = product.GetTranslation(x => x.MetaTitle, languageId, false);
locale.Flag = product.GetTranslation(x => x.Flag, languageId, false);
locale.SeName = product.GetSeName(languageId, false);
});
return popup ? View("EditPopup", model) : View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
[ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
public async Task<IActionResult> Edit(ProductModel model, bool continueEditing, bool popup = false)
{
var product = await productService.GetProductById(model.Id, true);
if (product == null) return RedirectToAction("List");
if (!await scope.HasAccess(product)) return RedirectToAction("Edit", new { id = product.Id, popup });
if (model.Ticks != product.Ticks)
{
Error(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Fields.ChangedWarning"));
return RedirectToAction("Edit", new { id = product.Id, popup });
}
//the server is the guard, not the read-only fields
if (await productViewModelService.StockChangeRefused(model) is { } stockRefused)
ModelState.AddModelError("", stockRefused);
//batches or serial numbers assigned stay where they are
if (await productViewModelService.TrackingChangeRefused(product, model) is { } trackingRefused)
ModelState.AddModelError("", trackingRefused);
if (ModelState.IsValid)
{
if (scope.DefaultStoreId is not null)
{
model.Stores = [scope.DefaultStoreId];
model.StoreId = scope.DefaultStoreId;
}
product = await productViewModelService.UpdateProductModel(product, model);
Success(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Updated"));
//a popup has no list to go back to: it stays on the tab that was saved
if (continueEditing || popup)
{
await SaveSelectedTabIndex();
return RedirectToAction("Edit", new { id = product.Id, popup });
}
return RedirectToAction("List");
}
if (scope.DefaultStoreId is not null) model.StoreId = scope.DefaultStoreId;
await productViewModelService.PrepareProductModel(model, product, false, true);
return popup ? View("EditPopup", model) : View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Delete)]
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
var product = await productService.GetProductById(id, true);
if (product == null) return RedirectToAction("List");
if (!await scope.HasAccess(product)) return RedirectToAction("Edit", new { id });
if (ModelState.IsValid)
{
await productViewModelService.DeleteProduct(product);
Success(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Deleted"));
return RedirectToAction("List");
}
Error(ModelState);
return RedirectToAction("Edit", new { id });
}
[PermissionAuthorizeAction(PermissionActionName.Delete)]
[HttpPost]
public async Task<IActionResult> DeleteSelected(ICollection<string> selectedIds)
{
if (selectedIds == null || selectedIds.Count == 0) return Json(new { Result = true });
// This is a mutation (bulk delete), so it uses the strict HasAccess, matching Edit(POST)/Delete
// above — not a no-op pass-through to the service. Without this filter, Store gains an
// unscoped bulk-delete endpoint (any store staff could delete any product id in the system,
// bypassing AccessToEntityByStore entirely) purely because MVC routes actions regardless of
// whether a host's views ever link to them.
var products = await productService.GetProductsByIds(selectedIds.ToArray(),
access: CatalogAccess.IncludingHidden());
var allowedIds = new List<string>();
foreach (var product in products)
if (await scope.HasAccess(product))
allowedIds.Add(product.Id);
if (allowedIds.Count > 0) await productViewModelService.DeleteSelected(allowedIds);
return Json(new { Result = true });
}
[PermissionAuthorizeAction(PermissionActionName.Create)]
[HttpPost]
public async Task<IActionResult> CopyProduct(ProductModel model,
[FromServices] ICopyProductService copyProductService, [FromServices] IPictureService pictureService)
{
var copyModel = model.CopyProductModel;
try
{
var originalProduct = await productService.GetProductById(copyModel.Id, true);
// CanView, not HasAccess: Store's original CopyProduct denies only when LimitedToStores is
// true AND the staff member's store isn't among them — the same looser rule as Edit(GET)
// above, not the strict mutation rule. See IAdminDataScope<TEntity>.CanView.
if (!await scope.CanView(originalProduct)) return RedirectToAction("List");
if (scope.DefaultStoreId is not null)
{
originalProduct.LimitedToStores = true;
originalProduct.Stores.Clear();
originalProduct.Stores.Add(scope.DefaultStoreId);
}
var newProduct = await copyProductService.CopyProduct(originalProduct, copyModel.Name, copyModel.Published);
if (copyModel.CopyImages) await CopyImages(originalProduct, newProduct, pictureService);
Success("The product has been copied successfully");
return RedirectToAction("Edit", new { id = newProduct.Id });
}
catch (Exception exc)
{
Error(exc.Message);
return RedirectToAction("Edit", new { id = copyModel.Id });
}
}
private async Task CopyImages(Product originalProduct, Product newProduct, IPictureService pictureService)
{
foreach (var productPicture in originalProduct.ProductPictures)
{
var picture = await pictureService.GetPictureById(productPicture.PictureId);
var pictureCopy = await pictureService.InsertPicture(
await pictureService.LoadPictureBinary(picture),
picture.MimeType,
pictureService.GetPictureSeName(newProduct.Name),
picture.AltAttribute,
picture.TitleAttribute,
false,
Reference.Product,
newProduct.Id);
await productService.InsertProductPicture(new ProductPicture {
PictureId = pictureCopy.Id,
DisplayOrder = productPicture.DisplayOrder,
IsDefault = productPicture.IsDefault
}, newProduct.Id);
}
}
#endregion
#region Required products
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> LoadProductFriendlyNames(string productIds)
{
var result = "";
if (!string.IsNullOrWhiteSpace(productIds))
{
var ids = productIds
.Split([','], StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.ToList();
var products = await productService.GetProductsByIds(ids.ToArray(),
access: CatalogAccess.IncludingHidden());
var names = new List<string>();
foreach (var product in products)
{
// Filters the friendly-name list, not a hard deny of the whole action: matches Store's
// CanAccessProduct loop and Vendor's HasAccessToProduct loop, both of which skip
// inaccessible products silently rather than erroring the whole request. Both are the
// strict rule (AccessToEntityByStore / VendorId equality), so HasAccess (not CanView) is
// correct here - this is filtering a display list, not opening/copying a single entity.
if (!await scope.HasAccess(product)) continue;
names.Add(product.Name);
}
result = string.Join(", ", names);
}
return Json(new { Text = result });
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> RequiredProductAddPopup()
{
// PrepareAddRequiredProductModel() now reads scope internally (Task 9) - the injected
// IAdminDataScope<Product> already encodes the per-host default exactly: null for Admin
// (global) and Vendor (not store-scoped), StaffStoreId for Store.
var model = await productAddPopupViewModelService.PrepareAddRequiredProductModel();
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> RequiredProductAddPopupList(DataSourceRequest command,
ProductModel.AddRequiredProductModel model)
{
if (scope.DefaultStoreId is not null) model.SearchStoreId = scope.DefaultStoreId;
var (products, totalCount) =
await productAddPopupViewModelService.PrepareProductModel(model, command.Page, command.PageSize);
var gridModel = new DataSourceResult {
Data = products.ToList(),
Total = totalCount
};
return Json(gridModel);
}
#endregion
#region Purchased with order
// Type note: this method covers Admin and Store only. Both already share
// Grand.Web.AdminShared's IOrderViewModelService and Models.Orders.OrderListModel (see the usings
// at the top of this file). Vendor defines its own, structurally different
// Grand.Web.Vendor.Interfaces.IOrderViewModelService and Grand.Web.Vendor.Models.Orders.OrderListModel
// (no StoreId property at all - Vendor's PrepareOrderModel scopes by
// _contextAccessor.WorkContext.CurrentVendor.Id internally, not via any model field), so it cannot
// bind to this signature. That vendor-id scoping lives entirely inside Vendor's own
// OrderViewModelService, outside anything IAdminDataScope<Product> expresses - flagging as a concern
// per the task brief rather than inventing a shared model/service pair. Not virtual: C#'s override
// rules require an exact parameter-type match, so a Vendor override using
// Grand.Web.Vendor.Interfaces.IOrderViewModelService/Models.Orders.OrderListModel could never compile
// as an override of this signature anyway. When Vendor is wired onto this base controller (Task 11),
// its subclass will declare its own PurchasedWithOrders action with `new` to shadow this one (a
// standard, valid ASP.NET Core MVC pattern for a derived controller needing an incompatible signature
// under the same action name), not override it.
[PermissionAuthorizeAction(PermissionActionName.Preview)]
[HttpPost]
public async Task<IActionResult> PurchasedWithOrders(DataSourceRequest command, string productId,
[FromServices] IOrderViewModelService orderViewModelService)
{
if (!await permissionService.Authorize(StandardPermission.ManageOrders))
return Json(new DataSourceResult {
Data = null,
Total = 0
});
var product = await productService.GetProductById(productId);
// CanView on this read: a product shared with other stores opens read-only on Store, so its
// tabs must load; the mutating actions below keep the strict HasAccess. History:
// HasAccess (strict): mirrors Store's CanAccessProduct check on this action. Admin's original had
// no check at all - GlobalAdminDataScope.HasAccess is a no-op there, so this closes that gap the
// same way as every other row in this task.
if (!await scope.CanView(product))
return ErrorForKendoGridJson(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions"));
var model = new OrderListModel {
ProductId = productId,
// DefaultStoreId is the staff member's store for Store (matches its original
// model.StoreId = StaffStoreId) and null for Admin (matches its original, which never set
// StoreId at all).
StoreId = scope.DefaultStoreId
};
var (orderModels, totalCount) =
await orderViewModelService.PrepareOrderModel(model, command.Page, command.PageSize);
var gridModel = new DataSourceResult {
Data = orderModels.ToList(),
Total = totalCount
};
return Json(gridModel);
}
#endregion
#region Reviews
[PermissionAuthorizeAction(PermissionActionName.Preview)]
[HttpPost]
public async Task<IActionResult> Reviews(DataSourceRequest command, string productId,
[FromServices] IProductReviewService productReviewService)
{
var product = await productService.GetProductById(productId);
// CanView on this read: a product shared with other stores opens read-only on Store, so its
// tabs must load; the mutating actions below keep the strict HasAccess. History:
// HasAccess (strict): mirrors Store's CanAccessProduct and Vendor's CheckAccessToProduct gating
// this action on both hosts. Admin's original had no check at all - GlobalAdminDataScope.HasAccess
// is a no-op there, so this closes that gap the same way as every other row in this task.
if (!await scope.CanView(product))
return ErrorForKendoGridJson(translationService.GetResource($"{scope.ResourceKeyPrefix}.Catalog.Products.Permissions"));
// DefaultStoreId is the staff member's store for Store (matches its original storeId argument,
// which filtered reviews to the staff member's store) and null - normalized to "" here, matching
// GetAllProductReviews's expected "no filter" value - for both Admin and Vendor (matches their
// originals, which both passed "" literally; Vendor scopes by VendorId via the HasAccess check
// above, not by store, since VendorProductDataScope.DefaultStoreId is null).
var storeId = scope.DefaultStoreId ?? "";
var productReviews = await productReviewService.GetAllProductReviews("", null,
null, null, "", storeId, productId);
var items = new List<ProductReviewModel>();
foreach (var item in productReviews.PagedForCommand(command))
{
var m = new ProductReviewModel();
await productViewModelService.PrepareProductReviewModel(m, item, false, true);
items.Add(m);
}
var gridModel = new DataSourceResult {
Data = items,
Total = productReviews.Count
};
return Json(gridModel);
}
#endregion
#region Export / Import
[PermissionAuthorizeAction(PermissionActionName.Export)]
[HttpPost]
[AuditExport("Product")]
public async Task<IActionResult> ExportExcelAll(ProductListModel model,
[FromServices] IExportManager<Product> exportManager)
{
// vendorId is forced inside PrepareProducts itself (scope.DefaultVendorId ?? model.SearchVendorId),
// but storeId is not - every other caller of PrepareProductsModel/PrepareProducts in this file
// forces it here, at the call site, the same way ProductList does above. This one was missing it:
// a Store-scoped user could POST an arbitrary (or blank) SearchStoreId and export every store's
// products, not just their own. Found during a post-Phase-2 tenant-isolation audit.
if (scope.DefaultStoreId is not null) model.SearchStoreId = scope.DefaultStoreId;
var products = await productViewModelService.PrepareProducts(model);
try
{
var bytes = await exportManager.Export(products, HttpContext.RequestAborted);
return File(bytes, "text/xls", "products.xlsx");
}
catch (Exception exc) when (!IsRequestAborted(exc))
{
Error(exc);
return RedirectToAction("List");
}
}
[PermissionAuthorizeAction(PermissionActionName.Export)]
[HttpPost]
[AuditExport("Product")]
public async Task<IActionResult> ExportExcelSelected(string selectedIds,
[FromServices] IExportManager<Product> exportManager)
{
var products = new List<Product>();
if (selectedIds != null)
{
var ids = selectedIds
.Split([','], StringSplitOptions.RemoveEmptyEntries)
.Select(x => x)
.ToArray();
products.AddRange(await productService.GetProductsByIds(ids, access: CatalogAccess.IncludingHidden()));
}
// Unlike ExportExcelAll, selectedIds is caller-supplied and not derived from a scoped search -
// Vendor's original explicitly re-checked HasAccessToProduct per id for exactly this reason
// (a vendor could otherwise pass another vendor's product id and export it). Admin's original had
// no check at all (GlobalAdminDataScope.HasAccess is a no-op there), so applying the filter
// unconditionally closes that gap the same way as every other row in this task, without changing
// Admin's or Store's observable behavior.
var scoped = new List<Product>();
foreach (var product in products)
if (await scope.HasAccess(product))
scoped.Add(product);
var bytes = await exportManager.Export(scoped, HttpContext.RequestAborted);
return File(bytes, "text/xls", "products.xlsx");
}
// Global scope only, as for brands, categories and collections: the importer is not store- or
// vendor-aware.
//
// Concern (flagged, not fixed - out of scope for this row): ImportExcel only checks
// `importexcelfile.Length > 0` before handing the raw stream to IImportManager<ProductDto>.Import.
// There is no file-extension allowlist and no upper bound on Length before the stream is read into
// memory by the importer. Commit a153496a6 hardened exactly this shape of gap (memory DoS + extension
// bypass) for attribute file uploads; this action has the same shape and was not touched by that fix.
// This is pre-existing behavior being ported verbatim, not something introduced by this migration -
// worth a follow-up ticket, not a silent fix here.
[PermissionAuthorizeAction(PermissionActionName.Import)]
[HttpPost]
public async Task<IActionResult> ImportExcel(IFormFile importexcelfile,
[FromServices] IImportManager<ProductDto> importManager)
{
try
{
if (Scope.DefaultStoreId is not null || Scope.DefaultVendorId is not null)
{
Error(translationService.GetResource("Admin.AccessDenied.Title"));
return RedirectToAction("List");
}
if (importexcelfile is { Length: > 0 })
{
await importManager.Import(importexcelfile.OpenReadStream(), HttpContext.RequestAborted);
}
else
{
Error(translationService.GetResource("Admin.Common.UploadFile"));
return RedirectToAction("List");
}
Success(translationService.GetResource("Admin.Catalog.Products.Imported"));
return RedirectToAction("List");
}
catch (Exception exc) when (!IsRequestAborted(exc))
{
Error(exc);
return RedirectToAction("List");
}
}
#endregion
#region Bulk editing
[PermissionAuthorizeAction(PermissionActionName.Preview)]
public async Task<IActionResult> BulkEdit()
{
// PrepareBulkEditListModel() now reads scope internally (Task 9): null for Admin/Vendor
// (not store-scoped), StaffStoreId for Store.
var model = await productViewModelService.PrepareBulkEditListModel();
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> BulkEditSelect(DataSourceRequest command, BulkEditListModel model)
{
if (scope.DefaultStoreId is not null) model.SearchStoreId = scope.DefaultStoreId;
// BLOCKING PREREQUISITE for Task 11 (see plan's Task 10 PrepareBulkEditProductModel row and
// Task 11's blocking-prerequisite note, added in commit a8def835a after this gap was flagged and
// verified during review): Vendor's original bulk-edit grid was vendor-scoped -
// PrepareBulkEditProductModel passed vendorId: CurrentVendor.Id into productService.SearchProducts,
// so the grid only ever listed the vendor's own products. AdminShared's version isn't -
// IProductViewModelService.PrepareBulkEditProductModel used here has no vendorId parameter (unlike
// PrepareProductModel(AddProductModel), which supports SearchVendorId - see
// AssociatedProductVendorId above) - and BulkEditListModel carries no SearchVendorId field either.
// Closing this requires a ProductViewModelService/BulkEditListModel change, which this task's
// per-row scope (BaseProductController.cs + tests only) does not permit. Not a security gap by
// itself (a wider listing, not a mutation) - the mutate endpoints below (BulkEditUpdate/
// BulkEditDelete) are scope-checked per item regardless and never leak another party's product -
// but Task 11 must NOT subclass Vendor onto this base controller until Task 10 adds vendor-scoped
// filtering here, or a vendor would see every vendor's products in this grid.
var (bulkEditProductModels, totalCount) =
await productViewModelService.PrepareBulkEditProductModel(model, command.Page, command.PageSize);
var gridModel = new DataSourceResult {
Data = bulkEditProductModels.ToList(),
Total = totalCount
};
return Json(gridModel);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> BulkEditUpdate(IEnumerable<BulkEditProductModel> products)
{
var validProducts = await FilterBulkEditProductsByAccess(products);
if (validProducts.Count > 0) await productViewModelService.UpdateBulkEdit(validProducts);
return new JsonResult("");
}
/// <summary>
/// Rows added in the bulk-edit grid: a simple product each, with the fields of the row. The ids
/// are the grid's empty ones, so there is nothing to scope-check; ownership of the new product
/// is set by the service (store for Store, vendor for Vendor) the way the Create screen sets it.
/// </summary>
[PermissionAuthorizeAction(PermissionActionName.Create)]
[HttpPost]
public async Task<IActionResult> BulkEditCreate(IEnumerable<BulkEditProductModel> products)
{
var newProducts = products?.Where(x => !string.IsNullOrWhiteSpace(x.Name)).ToList() ?? [];
if (newProducts.Count > 0) await productViewModelService.InsertBulkEdit(newProducts);
return new JsonResult("");
}
[PermissionAuthorizeAction(PermissionActionName.Delete)]
[HttpPost]
public async Task<IActionResult> BulkEditDelete(IEnumerable<BulkEditProductModel> products)
{
var validProducts = await FilterBulkEditProductsByAccess(products);
if (validProducts.Count > 0) await productViewModelService.DeleteBulkEdit(validProducts);
return new JsonResult("");
}
/// <summary>
/// Filters a caller-supplied bulk-edit product list (BulkEditUpdate/BulkEditDelete) down to the ones
/// the current user may mutate. Same shape as the DeleteSelected gap above: this is a caller-supplied
/// list of ids being mutated in one request, and each id must be scope-checked individually before
/// mutation, not just implicitly trusted because it appeared in a grid the user was shown.
///
/// Admin's original had NO check at all here - both BulkEditUpdate and BulkEditDelete accepted a
/// client-supplied list of ids and mutated/deleted every one of them unconditionally, a real unscoped
/// bulk-mutate/bulk-delete IDOR (any authenticated admin user hitting these actions directly - not
/// through the grid - could update or delete any product in the system by id).
///
/// Store's original had this exact check (FilterValidProductsForStore, via CanAccessProduct /
/// AccessToEntityByStore) - HasAccess (strict), matching CanAccessProduct's strict rule, not CanView.
///
/// Vendor's original enforced the equivalent strict check (HasAccessToProduct / VendorId equality)
/// inside its own separate service (Grand.Web.Vendor's ProductViewModelService.UpdateBulkEdit/
/// DeleteBulkEdit), not in the controller - functionally the same per-item gate, just placed one layer
/// down. Routing it through scope.HasAccess here reproduces that gate at the controller layer, where
/// the shared IProductViewModelService.UpdateBulkEdit/DeleteBulkEdit used by this class does not
/// filter internally (verified: both loop and mutate/delete every product they're given, no ownership
/// check).
///
/// No-op for Admin (GlobalAdminDataScope.HasAccess is always true, so validProducts == products).
/// Silently drops missing/inaccessible ids rather than throwing (matches Admin's/Vendor's
/// null-then-skip behavior, not Store's original throw-on-missing-id - the majority behavior, and a
/// single bad id in a bulk request shouldn't fail the whole batch).
/// </summary>
private async Task<List<BulkEditProductModel>> FilterBulkEditProductsByAccess(
IEnumerable<BulkEditProductModel> products)
{
if (products == null) return [];
var byId = products
.Where(x => !string.IsNullOrEmpty(x.Id))
.GroupBy(x => x.Id)
.ToDictionary(g => g.Key, g => g.First());
if (byId.Count == 0) return [];
var loadedProducts = await productService.GetProductsByIds(byId.Keys.ToArray(),
access: CatalogAccess.IncludingHidden());
var validProducts = new List<BulkEditProductModel>();
foreach (var product in loadedProducts)
if (await scope.HasAccess(product))
validProducts.Add(byId[product.Id]);
return validProducts;
}
#endregion
}