Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Blog - move validator logic from BlogController to Validator
support3d7fe47cf5c8
diff --git a/src/Web/Grand.Web/Controllers/BlogController.cs b/src/Web/Grand.Web/Controllers/BlogController.csindex 83d9eb777..f2a435681 100644--- a/src/Web/Grand.Web/Controllers/BlogController.cs+++ b/src/Web/Grand.Web/Controllers/BlogController.cs@@ -55,6 +55,7 @@ namespace Grand.Web.Controllers#region Methods+ [HttpGet]public virtual async Task<IActionResult> List(BlogPagingFilteringModel command){if (!_blogSettings.Enabled)@@ -63,6 +64,7 @@ namespace Grand.Web.Controllersvar model = await _mediator.Send(new GetBlogPostList { Command = command });return View("List", model);}+ [HttpGet]public virtual async Task<IActionResult> BlogByTag(BlogPagingFilteringModel command){if (!_blogSettings.Enabled)@@ -71,6 +73,7 @@ namespace Grand.Web.Controllersvar model = await _mediator.Send(new GetBlogPostList { Command = command });return View("List", model);}+ [HttpGet]public virtual async Task<IActionResult> BlogByMonth(BlogPagingFilteringModel command){if (!_blogSettings.Enabled)@@ -79,6 +82,7 @@ namespace Grand.Web.Controllersvar model = await _mediator.Send(new GetBlogPostList { Command = command });return View("List", model);}+ [HttpGet]public virtual async Task<IActionResult> BlogByCategory(BlogPagingFilteringModel command){if (!_blogSettings.Enabled)@@ -87,6 +91,7 @@ namespace Grand.Web.Controllersvar model = await _mediator.Send(new GetBlogPostList { Command = command });return View("List", model);}+ [HttpGet]public virtual async Task<IActionResult> BlogByKeyword(BlogPagingFilteringModel command){if (!_blogSettings.Enabled)@@ -95,6 +100,7 @@ namespace Grand.Web.Controllersvar model = await _mediator.Send(new GetBlogPostList { Command = command });return View("List", model);}+ [HttpGet]public virtual async Task<IActionResult> BlogPost(string blogPostId,[FromServices] IAclService aclService,[FromServices] IPermissionService permissionService)@@ -123,27 +129,18 @@ namespace Grand.Web.Controllers[HttpPost][AutoValidateAntiforgeryToken]- [ValidateCaptcha][DenySystemAccount]- public virtual async Task<IActionResult> BlogCommentAdd(string blogPostId, BlogPostModel model, bool captchaValid)+ public virtual async Task<IActionResult> BlogPost(BlogPostModel model,+ [FromServices] IAclService aclService){- if (!_blogSettings.Enabled)- return RedirectToRoute("HomePage");-- var blogPost = await _blogService.GetBlogPostById(blogPostId);- if (blogPost is not { AllowComments: true })+ var blogPost = await _blogService.GetBlogPostById(model.BlogPostId);+ if (blogPost == null ||+ (blogPost.StartDateUtc.HasValue && blogPost.StartDateUtc.Value >= DateTime.UtcNow) ||+ (blogPost.EndDateUtc.HasValue && blogPost.EndDateUtc.Value <= DateTime.UtcNow))return RedirectToRoute("HomePage");-- if (await _groupService.IsGuest(_workContext.CurrentCustomer) && !_blogSettings.AllowNotRegisteredUsersToLeaveComments)- {- ModelState.AddModelError("", _translationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments"));- }-- //validate CAPTCHA- if (_captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage && !captchaValid)- {- ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_translationService));- }++ if (!aclService.Authorize(blogPost, _workContext.CurrentStore.Id))+ return InvokeHttp404();if (ModelState.IsValid){@@ -156,10 +153,10 @@ namespace Grand.Web.ControllersTempData["Grand.blog.addcomment.result"] = _translationService.GetResource("Blog.Comments.SuccessfullyAdded");return RedirectToRoute("BlogPost", new { SeName = blogPost.GetSeName(_workContext.WorkingLanguage.Id) });}-+//If we got this far, something failed, redisplay formmodel = await _mediator.Send(new GetBlogPost { BlogPost = blogPost });- return View("BlogPost", model);+ return View(model);}#endregion}diff --git a/src/Web/Grand.Web/Models/Blogs/BlogPostModel.cs b/src/Web/Grand.Web/Models/Blogs/BlogPostModel.csindex 3a5311dcf..4e7f55f1b 100644--- a/src/Web/Grand.Web/Models/Blogs/BlogPostModel.cs+++ b/src/Web/Grand.Web/Models/Blogs/BlogPostModel.cs@@ -1,10 +1,12 @@using Grand.Infrastructure.Models;+using Grand.Web.Models.Common;using Grand.Web.Models.Media;namespace Grand.Web.Models.Blogs{public class BlogPostModel : BaseEntityModel{+public BlogPostModel(){Tags = new List<string>();@@ -12,7 +14,8 @@ namespace Grand.Web.Models.BlogsAddNewComment = new AddBlogCommentModel();PictureModel = new PictureModel();}-++ public string BlogPostId { get; set; }public string MetaKeywords { get; set; }public string MetaDescription { get; set; }public string MetaTitle { get; set; }@@ -30,5 +33,8 @@ namespace Grand.Web.Models.Blogspublic IList<BlogCommentModel> Comments { get; set; }public AddBlogCommentModel AddNewComment { get; set; }++ public ICaptchaValidModel Captcha { get; set; } = new CaptchaModel();+}}\ No newline at end of filediff --git a/src/Web/Grand.Web/Validators/Blogs/AddBlogCommentValidator.cs b/src/Web/Grand.Web/Validators/Blogs/AddBlogCommentValidator.csnew file mode 100644index 000000000..fda110a63--- /dev/null+++ b/src/Web/Grand.Web/Validators/Blogs/AddBlogCommentValidator.cs@@ -0,0 +1,18 @@+using FluentValidation;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Infrastructure.Validators;+using Grand.Web.Models.Blogs;++namespace Grand.Web.Validators.Blogs;++public class AddBlogCommentValidator : BaseGrandValidator<AddBlogCommentModel>+{+ public AddBlogCommentValidator(+ IEnumerable<IValidatorConsumer<AddBlogCommentModel>> validators,+ ITranslationService translationService)+ : base(validators)+ {+ RuleFor(x => x.CommentText).NotEmpty()+ .WithMessage(translationService.GetResource("Blog.Comments.CommentText.Required"));+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web/Validators/Blogs/BlogPostValidator.cs b/src/Web/Grand.Web/Validators/Blogs/BlogPostValidator.csindex fd5c4d8fe..d89c562ca 100644--- a/src/Web/Grand.Web/Validators/Blogs/BlogPostValidator.cs+++ b/src/Web/Grand.Web/Validators/Blogs/BlogPostValidator.cs@@ -1,17 +1,64 @@using FluentValidation;+using Grand.Business.Core.Interfaces.Cms;+using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Common.Security;+using Grand.Domain.Blogs;+using Grand.Infrastructure;+using Grand.Infrastructure.Models;using Grand.Infrastructure.Validators;+using Grand.Web.Common.Security.Captcha;+using Grand.Web.Common.Validators;using Grand.Web.Models.Blogs;+using Microsoft.AspNetCore.Http;-namespace Grand.Web.Validators.Blogs+namespace Grand.Web.Validators.Blogs;++public class BlogPostValidator : BaseGrandValidator<BlogPostModel>{- public class BlogPostValidator : BaseGrandValidator<AddBlogCommentModel>+ public BlogPostValidator(+ IEnumerable<IValidatorConsumer<BlogPostModel>> validators,+ IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,+ CaptchaSettings captchaSettings, BlogSettings blogSettings,+ IGroupService groupService, IWorkContext workContext, IBlogService blogService, IAclService aclService,+ IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,+ ITranslationService translationService)+ : base(validators){- public BlogPostValidator(- IEnumerable<IValidatorConsumer<AddBlogCommentModel>> validators,- ITranslationService translationService)- : base(validators)+ RuleFor(x => x.AddNewComment.CommentText).NotEmpty()+ .WithMessage(translationService.GetResource("Blog.Comments.CommentText.Required"));++ RuleFor(x => x).CustomAsync(async (x, context, _) =>+ {+ if (await groupService.IsGuest(workContext.CurrentCustomer) &&+ !blogSettings.AllowNotRegisteredUsersToLeaveComments)+ {+ context.AddFailure(+ translationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments"));+ }++ if (!blogSettings.Enabled)+ context.AddFailure(+ translationService.GetResource("Blog.Disabled"));++ var blogPost = await blogService.GetBlogPostById(x.BlogPostId);+ if (blogPost is not { AllowComments: true })+ context.AddFailure(translationService.GetResource("Blog.Comments.NotAllowed"));++ if (!aclService.Authorize(blogPost, workContext.CurrentStore.Id))+ context.AddFailure(translationService.GetResource("Blog.Comments.NotAllowed"));++ if (blogPost == null ||+ (blogPost.StartDateUtc.HasValue && blogPost.StartDateUtc.Value >= DateTime.UtcNow) ||+ (blogPost.EndDateUtc.HasValue && blogPost.EndDateUtc.Value <= DateTime.UtcNow))+ context.AddFailure(translationService.GetResource("Blog.Comments.NotAllowed"));+ });++ if (captchaSettings.Enabled && captchaSettings.ShowOnBlogCommentPage){- RuleFor(x => x.CommentText).NotEmpty().WithMessage(translationService.GetResource("Blog.Comments.CommentText.Required"));- }}+ RuleFor(x => x.Captcha).NotNull().WithMessage(translationService.GetResource("Account.Captcha.Required"));+ RuleFor(x => x.Captcha)+ .SetValidator(new CaptchaValidator(validatorsCaptcha, contextAccessor, googleReCaptchaValidator));+ }+ }}\ No newline at end of filediff --git a/src/Web/Grand.Web/Views/Blog/BlogPost.cshtml b/src/Web/Grand.Web/Views/Blog/BlogPost.cshtmlindex 798fad99c..d3fcc7a4b 100644--- a/src/Web/Grand.Web/Views/Blog/BlogPost.cshtml+++ b/src/Web/Grand.Web/Views/Blog/BlogPost.cshtml@@ -60,7 +60,7 @@<div class="fieldset new-comment generalMarginSupporter" id="comments"><h4 class="generalTitle generalMarginSupporter">@Loc["Blog.Comments.LeaveYourComment"]</h4><div class="notifications">- <div asp-validation-summary="ModelOnly" class="message-error"></div>+ <div asp-validation-summary="All" class="message-error"></div>@{var result = TempData["Grand.blog.addcomment.result"] as string;}@@ -70,11 +70,11 @@}</div><validation-observer v-slot="{ handleSubmit }">- <form asp-controller="Blog" asp-action="BlogCommentAdd" asp-route-id="@Model.Id" method="post" ref="form" v-on:submit.prevent="handleSubmit(formSubmit)">+ <form asp-controller="Blog" asp-action="BlogPost" asp-route-id="@Model.Id" method="post" ref="form" v-on:submit.prevent="handleSubmit(formSubmit)"><input type="hidden" name="blogPostId" value="@Model.Id" /><div class="form-fields"><div class="form-group">- <validation-provider tag="div" rules="required" name="AddNewComment.CommentText" v-slot="{ errors, classes }">+ <validation-provider tag="div" rules="required" v-slot="{ errors, classes }"><label asp-for="AddNewComment.CommentText" class="col-form-label">@Loc["Blog.Comments.CommentText"]:</label><span class="required">*</span><textarea asp-for="AddNewComment.CommentText" v-model="blog.CommentText" v-bind:class="[classes , 'form-control']" autofocus="autofocus" rows="4"></textarea>@@ -133,6 +133,5 @@</div>}}- @await Component.InvokeAsync("Widget", new { widgetZone = "blogpost_page_after_comments", additionalData = Model.Id })@await Component.InvokeAsync("Widget", new { widgetZone = "blogpost_page_bottom", additionalData = Model.Id })</div>\ No newline at end of file