Skip to content

Commit

Permalink
Merge pull request #457 from thousandtyone/main
Browse files Browse the repository at this point in the history
Adding Ability For DasBlog To Support Google Recaptcha.

closes #363
  • Loading branch information
poppastring authored Sep 1, 2020
2 parents 1aff31d + 48c2a95 commit a8884e1
Show file tree
Hide file tree
Showing 12 changed files with 129 additions and 11 deletions.
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ steps:
inputs:
command: build
projects: '**/*.sln'
arguments: '--no-restore --configuration $(BuildConfiguration) -p:VersionPrefix=2.0.$(Build.BuildId) -p:FileVersion=2.0.$(Build.BuildId).0'
arguments: '--no-restore --configuration $(BuildConfiguration) -p:VersionPrefix=2.11.$(Build.BuildId) -p:FileVersion=2.11.$(Build.BuildId).0'

- script: dotnet test source/DasBlog.Tests/UnitTests/ --logger trx;LogfileName=test_results.xml --results-directory $(System.DefaultWorkingDirectory)/test_results --filter Category=UnitTest
displayName: Run Unit Tests on Windows
Expand Down
6 changes: 6 additions & 0 deletions source/DasBlog.Services/ConfigFile/Interfaces/ISiteConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,12 @@ public interface ISiteConfig

bool EnableCaptcha { get; set; }

string RecaptchaSiteKey { get; set; }

string RecaptchaSecretKey { get; set; }

double RecaptchaMinimumScore { get; set; }

bool EnableReferralUrlBlackList404s { get; set; }

bool EnableMovableTypeBlackList { get; set; }
Expand Down
3 changes: 3 additions & 0 deletions source/DasBlog.Services/ConfigFile/SiteConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ public SiteConfig() { }
public string ReferralUrlBlackList { get; set; }
public string[] ReferralUrlBlackListArray { get; set; }
public bool EnableCaptcha { get; set; }
public string RecaptchaSiteKey { get; set; }
public string RecaptchaSecretKey { get; set; }
public double RecaptchaMinimumScore {get; set; }
public bool EnableReferralUrlBlackList404s { get; set; }
public bool EnableMovableTypeBlackList { get; set; }
public string ChannelImageUrl { get; set; }
Expand Down
3 changes: 3 additions & 0 deletions source/DasBlog.Tests/UnitTests/SiteConfigTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ public class SiteConfigTest : ISiteConfig
public string ReferralUrlBlackList { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string[] ReferralUrlBlackListArray { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public bool EnableCaptcha { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string RecaptchaSiteKey { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string RecaptchaSecretKey { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public double RecaptchaMinimumScore { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public bool EnableReferralUrlBlackList404s { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public bool EnableMovableTypeBlackList { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string ChannelImageUrl { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
Expand Down
3 changes: 3 additions & 0 deletions source/DasBlog.Web.UI/Config/site.Development.config
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@
<EnableReferralUrlBlackList>false</EnableReferralUrlBlackList>
<ReferralUrlBlackList>poker;casino;pharmacy;sex;piss;cock;fuck;shit;pussy;gay;boys;girls;cheap;drugs;shipping;pussy;shemale;nude;slots;gambling;poker;uncut;taboo;pervert;fanta;hotbod;hotg;drunk;megavideo;femdom;incest;e-finance;holdem;deal;loan;consolidation;top-deals;hold-em;4-you;cell-phone;24x7;cute;spank;bott;girl;glamor;glamour;ortho;mortgage;models;cunt;cock;virgin;prussia;megavideo;debt;porn;4u;nude;naked;assh;hole;drug;bargin;insurance;xxx;teen;fatties;flower;leading;pill;diet;weight;gain;loss;viag;levit;best;online-dat;file://;scat;incest;credit;mortgage;calculator;esite;golf;gokura;oldie;fuzz;strap;ein.be;texasproptax;alphacarolinas;ourtownhelps;acrs;fortisenterprises;kardtoons;hermosa.us;monavaletoys;australia-;travel;berwick;sedona;handmade;digitaltwist;normytexas;xopy;superdolphins;instant;popwow;sportsparent;condo;flaf;mediavisor;gables;stmary;whichis;oiline;crepe;tmsa;easymoney;loddes;rimp;milf;halloween;bdsm;paris;hentai;britney;4free;ownsthis;fidelity;uae;cash;labels;hotel;spood;newtruths;krant;twinky;nehru;ansar;tclighting;reservedining;parkviewsoc;hometeaminspect;stories-on;marshally;suttonjames;hdic;pagetwo;ingy;psyche;seedfarm;azian;sportingcolor;atlanta2000;rifp;mor-lit;catcha;sysrem;exitq;rethy;lemon;zone-b51;jfcadvocacy;weighweb;mp-forum;darkangel;gargz;grot;yonet;middlecay;merchant;lvcpa;hassler;taklar;simonr;pisoc;alumni;applyonline;clonaze;rulo;tecrep;learnhow;arsc;69-review;exotic;adult;18dvd;nett;cialis;yelucie;dildo;ikill;saluk;doobu;cream;blonde;oncam;basket;her-first;lutsch;nicht;fundel;rausg;omni;cum;cxa.de;tits;sami;alters;krank;it2u;sperm;fick;kred;studiomoney;ca-america;vrajitor;pkv.net;buy-2005;gaming;uncovered;corpor;firsthori;win-2005;vinhas;forex;conjur;bellen;personalsites;geert;learningphp;ms-inc;slots;ejac;blackjack;wins;wslp;zindagi;ladysroom;nerosang;wadoo;owned;dvdwizard;scout;op-clan;three.us;vegas;hosting;texas;whvc;ua-;bodyshop;stumble;slot;findmore;bardak;hernya;adult-;texas;craps;porno;codone;azer</ReferralUrlBlackList>
<EnableCaptcha>false</EnableCaptcha>
<RecaptchaSiteKey>your_google_recaptcha_site_key_here</RecaptchaSiteKey>
<RecaptchaSecretKey>your_google_recaptcha_secret_key_here</RecaptchaSecretKey>
<RecaptchaMinimumScore>0.7</RecaptchaMinimumScore>
<EnableReferralUrlBlackList404s>false</EnableReferralUrlBlackList404s>
<EnableMovableTypeBlackList>false</EnableMovableTypeBlackList>
<EnableCrossPostFooter>false</EnableCrossPostFooter>
Expand Down
3 changes: 3 additions & 0 deletions source/DasBlog.Web.UI/Config/site.config
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@
<EnableReferralUrlBlackList>false</EnableReferralUrlBlackList>
<ReferralUrlBlackList>poker;casino;pharmacy;sex;piss;cock;fuck;shit;pussy;gay;boys;girls;cheap;drugs;shipping;pussy;shemale;nude;slots;gambling;poker;uncut;taboo;pervert;fanta;hotbod;hotg;drunk;megavideo;femdom;incest;e-finance;holdem;deal;loan;consolidation;top-deals;hold-em;4-you;cell-phone;24x7;cute;spank;bott;girl;glamor;glamour;ortho;mortgage;models;cunt;cock;virgin;prussia;megavideo;debt;porn;4u;nude;naked;assh;hole;drug;bargin;insurance;xxx;teen;fatties;flower;leading;pill;diet;weight;gain;loss;viag;levit;best;online-dat;file://;scat;incest;credit;mortgage;calculator;esite;golf;gokura;oldie;fuzz;strap;ein.be;texasproptax;alphacarolinas;ourtownhelps;acrs;fortisenterprises;kardtoons;hermosa.us;monavaletoys;australia-;travel;berwick;sedona;handmade;digitaltwist;normytexas;xopy;superdolphins;instant;popwow;sportsparent;condo;flaf;mediavisor;gables;stmary;whichis;oiline;crepe;tmsa;easymoney;loddes;rimp;milf;halloween;bdsm;paris;hentai;britney;4free;ownsthis;fidelity;uae;cash;labels;hotel;spood;newtruths;krant;twinky;nehru;ansar;tclighting;reservedining;parkviewsoc;hometeaminspect;stories-on;marshally;suttonjames;hdic;pagetwo;ingy;psyche;seedfarm;azian;sportingcolor;atlanta2000;rifp;mor-lit;catcha;sysrem;exitq;rethy;lemon;zone-b51;jfcadvocacy;weighweb;mp-forum;darkangel;gargz;grot;yonet;middlecay;merchant;lvcpa;hassler;taklar;simonr;pisoc;alumni;applyonline;clonaze;rulo;tecrep;learnhow;arsc;69-review;exotic;adult;18dvd;nett;cialis;yelucie;dildo;ikill;saluk;doobu;cream;blonde;oncam;basket;her-first;lutsch;nicht;fundel;rausg;omni;cum;cxa.de;tits;sami;alters;krank;it2u;sperm;fick;kred;studiomoney;ca-america;vrajitor;pkv.net;buy-2005;gaming;uncovered;corpor;firsthori;win-2005;vinhas;forex;conjur;bellen;personalsites;geert;learningphp;ms-inc;slots;ejac;blackjack;wins;wslp;zindagi;ladysroom;nerosang;wadoo;owned;dvdwizard;scout;op-clan;three.us;vegas;hosting;texas;whvc;ua-;bodyshop;stumble;slot;findmore;bardak;hernya;adult-;texas;craps;porno;codone;azer</ReferralUrlBlackList>
<EnableCaptcha>false</EnableCaptcha>
<RecaptchaSiteKey>your_google_recaptcha_site_key_here</RecaptchaSiteKey>
<RecaptchaSecretKey>your_google_recaptcha_secret_key_here</RecaptchaSecretKey>
<RecaptchaMinimumScore>0.7</RecaptchaMinimumScore>
<EnableReferralUrlBlackList404s>false</EnableReferralUrlBlackList404s>
<EnableMovableTypeBlackList>false</EnableMovableTypeBlackList>
<EnableCrossPostFooter>false</EnableCrossPostFooter>
Expand Down
29 changes: 27 additions & 2 deletions source/DasBlog.Web.UI/Controllers/BlogPostController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
using System.Linq;
using System.Net;
using DasBlog.Web.Services;
using reCAPTCHA.AspNetCore.Attributes;
using reCAPTCHA.AspNetCore;

namespace DasBlog.Web.Controllers
{
Expand All @@ -34,11 +36,12 @@ public class BlogPostController : DasBlogBaseController
private readonly ILogger<BlogPostController> logger;
private readonly IBlogPostViewModelCreator modelViewCreator;
private readonly IMemoryCache memoryCache;
private readonly IRecaptchaService recaptcha;


public BlogPostController(IBlogManager blogManager, IHttpContextAccessor httpContextAccessor, IDasBlogSettings dasBlogSettings,
IMapper mapper, ICategoryManager categoryManager, IFileSystemBinaryManager binaryManager, ILogger<BlogPostController> logger,
IBlogPostViewModelCreator modelViewCreator, IMemoryCache memoryCache)
IBlogPostViewModelCreator modelViewCreator, IMemoryCache memoryCache,IRecaptchaService recaptcha)
: base(dasBlogSettings)
{
this.blogManager = blogManager;
Expand All @@ -50,6 +53,7 @@ public BlogPostController(IBlogManager blogManager, IHttpContextAccessor httpCon
this.logger = logger;
this.modelViewCreator = modelViewCreator;
this.memoryCache = memoryCache;
this.recaptcha = recaptcha;
}

[AllowAnonymous]
Expand Down Expand Up @@ -346,7 +350,11 @@ public IActionResult AddComment(AddCommentViewModel addcomment)
return Comment(addcomment.TargetEntryId);
}

if (dasBlogSettings.SiteConfiguration.CheesySpamQ.Trim().Length > 0 &&
// Optional in case of Captcha. Commenting the settings in the config file
// Will disable this check. People will typically disable this when using captcha.
if (!String.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamQ) &&
!String.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamA) &&
dasBlogSettings.SiteConfiguration.CheesySpamQ.Trim().Length > 0 &&
dasBlogSettings.SiteConfiguration.CheesySpamA.Trim().Length > 0)
{
if (string.Compare(addcomment.CheesyQuestionAnswered, dasBlogSettings.SiteConfiguration.CheesySpamA,
Expand All @@ -356,6 +364,23 @@ public IActionResult AddComment(AddCommentViewModel addcomment)
}
}

if(dasBlogSettings.SiteConfiguration.EnableCaptcha)
{
var recaptchaTask = recaptcha.Validate(Request);
recaptchaTask.Wait();
var recaptchaResult = recaptchaTask.Result;
if ((!recaptchaResult.success || recaptchaResult.score != 0) &&
recaptchaResult.score < dasBlogSettings.SiteConfiguration.RecaptchaMinimumScore )
{
// Todo: Rajiv Popat: This just redirects to the comment page. Ideally user should be informed that
// the captch is invalid and he should be shown an error page with ability to fix the issue.
// We need to have the ability to show errors and let the user fix typos in Captcha or Cheesy
// Question. For now we are following the sample implementation as Cheesy Spam Question above
// for the sake of consistency but this should be fixed everywhere.
return Comment(addcomment.TargetEntryId);
}
}

addcomment.Content = dasBlogSettings.FilterHtml(addcomment.Content);

var commt = mapper.Map<NBR.Comment>(addcomment);
Expand Down
1 change: 1 addition & 0 deletions source/DasBlog.Web.UI/DasBlog.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.9.10" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
<PackageReference Include="NetEscapades.Extensions.Logging.RollingFile" Version="2.2.0" />
<PackageReference Include="reCAPTCHA.AspNetCore" Version="3.0.10" />
<PackageReference Include="Quartz.AspNetCore" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
Expand Down
22 changes: 19 additions & 3 deletions source/DasBlog.Web.UI/Models/AdminViewModels/SiteViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,26 @@ public class SiteViewModel
[DisplayName("Spam prevention answer")]
[Description("Cheesy Spam Answer - Defines an answer that the commenters need to respond with in order to submit a comment (only enabled when CheesySpamQ has a val")]
[StringLength(300, MinimumLength = 1, ErrorMessage = "{0} should be between 1 to 300 characters")]

public string CheesySpamA { get; set; }

[DisplayName("Enable Captcha")]
[Description("Let's You Decide if you want to use Google's Recaptcha to Prevents Bots from spamming the comments on your posts.")]
public bool EnableCaptcha { get; set; }

[DisplayName("Recapcha Minimum Score")]
[Description("Minimum Score for the Recaptcha to be considered pass. For example if you are asked to identify an image at least 50% of the images must be identified if score if 0.5")]
[Range(0.0, 1.0, ErrorMessage = "Values should be between 0 and 1")]
public double RecaptchaMinimumScore { get; set; }

[DisplayName("Google Recaptha Site Key")]
[Description("Recaptcha Site Key Based on Recaptha Configured On Google Recaptcha Admin Site.")]
[StringLength(300, MinimumLength = 1, ErrorMessage = "{0} should be between 1 to 300 characters")]
public string RecaptchaSiteKey { get; set; }

[DisplayName("Google Recaptcha Secret Key")]
[Description("Recaptcha Secret Key based on Recaptcha configured on Google Recaptha Admin Site.")]
[StringLength(300, MinimumLength = 1, ErrorMessage = "{0} should be between 1 to 300 characters")]
public string RecaptchaSecretKey { get; set; }

[DisplayName("Enable unique URls")]
[Description(@"Enable Title PermaLink Unique - Ensures all urls are unique by adding a date to the URL '\somepost' becomes '20191112\some - post'")]
Expand Down Expand Up @@ -292,8 +309,7 @@ public class SiteViewModel
public bool EnableReferralUrlBlackList { get; set; }
public string ReferralUrlBlackList { get; set; }
public string[] ReferralUrlBlackListArray { get; set; }
public bool EnableCaptcha { get; set; }
public bool EnableReferralUrlBlackList404s { get; set; }
public bool EnableReferralUrlBlackList404s { get; set; }
public bool EnableMovableTypeBlackList { get; set; }
public bool EnableCrossPostFooter { get; set; }
public string CrossPostFooter { get; set; }
Expand Down
11 changes: 11 additions & 0 deletions source/DasBlog.Web.UI/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using reCAPTCHA.AspNetCore;

namespace DasBlog.Web
{
Expand All @@ -50,6 +51,8 @@ public class Startup
private readonly string LogFolderPath;
private readonly string BinariesPath;
private readonly string BinariesUrlRelativePath;
private readonly string RecaptchaSiteKey;
private readonly string RecaptchaSecretKey;

private readonly IWebHostEnvironment hostingEnvironment;

Expand All @@ -73,6 +76,8 @@ public Startup(IWebHostEnvironment env)
BinariesPath = new DirectoryInfo(Path.Combine(env.ContentRootPath, Configuration.GetValue<string>("BinariesDir"))).FullName;
ThemeFolderPath = new DirectoryInfo(Path.Combine(hostingEnvironment.ContentRootPath, "Themes", Configuration.GetSection("Theme").Value)).FullName;
LogFolderPath = new DirectoryInfo(Path.Combine(hostingEnvironment.ContentRootPath, Configuration.GetSection("LogDir").Value)).FullName;
RecaptchaSiteKey = Configuration.GetSection("RecaptchaSiteKey").Value;
RecaptchaSecretKey = Configuration.GetSection("RecaptchaSecretKey").Value;
BinariesUrlRelativePath = "content/binary";

}
Expand Down Expand Up @@ -225,6 +230,12 @@ public void ConfigureServices(IServiceCollection services)
services
.AddControllersWithViews()
.AddRazorRuntimeCompilation();

services.AddRecaptcha(options =>
{
options.SiteKey = RecaptchaSiteKey;
options.SecretKey = RecaptchaSecretKey;
});

services.Configure<CookiePolicyOptions>(options =>
{
Expand Down
37 changes: 34 additions & 3 deletions source/DasBlog.Web.UI/Views/Admin/Settings.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,39 @@

</div>

<div class="dbc-form-check row">
<div class="dbc-form-check row">

@Html.LabelFor(m => @Model.SiteConfig.EnableCaptcha, null, new { @class = "dbc-col-form-label col-3" })
@Html.CheckBoxFor(m => @Model.SiteConfig.EnableCaptcha , new { @class = "dbc-form-check-input" })

</div>

<div class="dbc-form-group row">

@Html.LabelFor(m => @Model.SiteConfig.RecaptchaMinimumScore, null, new { @class = "dbc-col-form-label col-3" })
@Html.TextBoxFor(m => @Model.SiteConfig.RecaptchaMinimumScore , null, new { @class = "form-control col-9" })
@Html.ValidationMessageFor(m => m.SiteConfig.RecaptchaMinimumScore, null, new { @class = "text-danger" })

</div>
<div class="dbc-form-group row">

@Html.LabelFor(m => @Model.SiteConfig.RecaptchaSiteKey, null, new { @class = "dbc-col-form-label col-3" })
@Html.TextBoxFor(m => @Model.SiteConfig.RecaptchaSiteKey, null, new { @class = "form-control col-9" })
@Html.ValidationMessageFor(m => m.SiteConfig.RecaptchaSiteKey, null, new { @class = "text-danger" })

</div>



<div class="dbc-form-group row">

@Html.LabelFor(m => @Model.SiteConfig.RecaptchaSecretKey, null, new { @class = "dbc-col-form-label col-3" })
@Html.TextBoxFor(m => @Model.SiteConfig.RecaptchaSecretKey, null, new { @class = "form-control col-9" })
@Html.ValidationMessageFor(m => m.SiteConfig.RecaptchaSecretKey, null, new { @class = "text-danger" })

</div>

<div class="dbc-form-check row">

@Html.LabelFor(m => @Model.SiteConfig.ShowCommentsWhenViewingEntry, null, new { @class = "dbc-col-form-label col-3" })
@Html.CheckBoxFor(m => @Model.SiteConfig.ShowCommentsWhenViewingEntry, new { @class = "dbc-form-check-input" })
Expand Down Expand Up @@ -554,7 +586,6 @@
@Html.HiddenFor(@m => m.SiteConfig.EnableReferralUrlBlackList)

@Html.HiddenFor(@m => m.SiteConfig.ReferralUrlBlackList)
@Html.HiddenFor(@m => m.SiteConfig.EnableCaptcha)
@Html.HiddenFor(@m => m.SiteConfig.EnableReferralUrlBlackList404s)

@Html.HiddenFor(@m => m.SiteConfig.EnableMovableTypeBlackList)
Expand Down Expand Up @@ -608,4 +639,4 @@
@Html.HiddenFor(@m => m.MetaConfig.FaceBookAdmins)
@Html.HiddenFor(@m => m.MetaConfig.FaceBookAppID)

</form>
</form>
Loading

0 comments on commit a8884e1

Please sign in to comment.