Skip to content

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.

2.4 KB
Raw Blame
using FluentValidation;
using Grand.Business.Core.Interfaces.Cms;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Domain.Common;
using Grand.Domain.Knowledgebase;
using Grand.Infrastructure;
using Grand.Infrastructure.Models;
using Grand.Infrastructure.Validators;
using Grand.SharedKernel.Captcha;
using Grand.Web.Common.Validators;
using Grand.Web.Models.Knowledgebase;

namespace Grand.Web.Validators.Knowledgebase;

public class KnowledgebaseArticleValidator : BaseGrandValidator<KnowledgebaseArticleModel>
{
    public KnowledgebaseArticleValidator(
        IEnumerable<IValidatorConsumer<KnowledgebaseArticleModel>> validators,
        IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
        IContextAccessor contextAccessor, IGroupService groupService,
        IKnowledgebaseService knowledgebaseService, KnowledgebaseSettings knowledgebaseSettings,
        CaptchaSettings captchaSettings,
        IHttpContextAccessor httpcontextAccessor, IGoogleReCaptchaValidator googleReCaptchaValidator,
        ITranslationService translationService)
        : base(validators)
    {
        RuleFor(x => x.AddNewComment.CommentText).NotEmpty()
            .WithMessage(translationService.GetResource("Grand.knowledgebase.addarticlecomment.result"))
            .When(x => x.AddNewComment != null);

        RuleFor(x => x).CustomAsync(async (x, context, _) =>
        {
            if (await groupService.IsGuest(contextAccessor.WorkContext.CurrentCustomer) &&
                !knowledgebaseSettings.AllowNotRegisteredUsersToLeaveComments)
                context.AddFailure(
                    translationService.GetResource("Knowledgebase.Article.Comments.OnlyRegisteredUsersLeaveComments"));
            var article = await knowledgebaseService.GetPublicKnowledgebaseArticle(x.ArticleId);
            if (article is not { AllowComments: true })
                context.AddFailure(translationService.GetResource("Knowledgebase.Article.Comments.NotAllowed"));
        });

        if (captchaSettings.Enabled && captchaSettings.ShowOnArticleCommentPage)
        {
            RuleFor(x => x.Captcha).NotNull()
                .WithMessage(translationService.GetResource("Account.Captcha.Required"));
            RuleFor(x => x.Captcha)
                .SetValidator(new CaptchaValidator(validatorsCaptcha, httpcontextAccessor, googleReCaptchaValidator));
        }
    }
}