From 1200318326527c968d68913dea05a78cd8fb1da5 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 26 Sep 2023 12:46:18 +0100 Subject: [PATCH] feat: add password protection to blog posts (WEB-3) --- OliverBooth/OliverBooth.csproj | 1 + OliverBooth/Pages/Blog/Article.cshtml | 16 +++++++++ OliverBooth/Pages/Blog/Article.cshtml.cs | 43 ++++++++++++++++++++++++ 3 files changed, 60 insertions(+) diff --git a/OliverBooth/OliverBooth.csproj b/OliverBooth/OliverBooth.csproj index 7e43e5b..6e7d24e 100644 --- a/OliverBooth/OliverBooth.csproj +++ b/OliverBooth/OliverBooth.csproj @@ -9,6 +9,7 @@ + diff --git a/OliverBooth/Pages/Blog/Article.cshtml b/OliverBooth/Pages/Blog/Article.cshtml index 6907dd7..dbed135 100644 --- a/OliverBooth/Pages/Blog/Article.cshtml +++ b/OliverBooth/Pages/Blog/Article.cshtml @@ -5,6 +5,22 @@ @inject IBlogPostService BlogPostService @model Article +@if (Model.ShowPasswordPrompt) +{ + + +
+
+ + +
+ +
+ return; +} + @if (Model.Post is not { } post) { return; diff --git a/OliverBooth/Pages/Blog/Article.cshtml.cs b/OliverBooth/Pages/Blog/Article.cshtml.cs index caded85..17a9337 100644 --- a/OliverBooth/Pages/Blog/Article.cshtml.cs +++ b/OliverBooth/Pages/Blog/Article.cshtml.cs @@ -1,7 +1,9 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.Extensions.Primitives; using OliverBooth.Data.Blog; using OliverBooth.Services; +using BC = BCrypt.Net.BCrypt; namespace OliverBooth.Pages.Blog; @@ -38,6 +40,14 @@ public class Article : PageModel /// The requested blog post. public IBlogPost Post { get; private set; } = null!; + /// + /// Gets a value indicating whether to show the password prompt. + /// + /// + /// if the password prompt should be shown; otherwise, . + /// + public bool ShowPasswordPrompt { get; private set; } + public IActionResult OnGet(int year, int month, int day, string slug) { var date = new DateOnly(year, month, day); @@ -47,6 +57,39 @@ public class Article : PageModel return NotFound(); } + if (!string.IsNullOrWhiteSpace(post.Password)) + { + ShowPasswordPrompt = true; + } + + if (post.IsRedirect) + { + return Redirect(post.RedirectUrl!.ToString()); + } + + Post = post; + return Page(); + } + + public IActionResult OnPost([FromRoute] int year, + [FromRoute] int month, + [FromRoute] int day, + [FromRoute] string slug) + { + var date = new DateOnly(year, month, day); + if (!_blogPostService.TryGetPost(date, slug, out IBlogPost? post)) + { + Response.StatusCode = 404; + return NotFound(); + } + + ShowPasswordPrompt = true; + + if (Request.Form.TryGetValue("password", out StringValues password) && BC.Verify(password, post.Password)) + { + ShowPasswordPrompt = false; + } + if (post.IsRedirect) { return Redirect(post.RedirectUrl!.ToString());