V2 #1

Merged
danieljsummers merged 102 commits from v2 into main 2022-06-23 00:35:12 +00:00
22 changed files with 573 additions and 32 deletions
Showing only changes of commit 39e0d5ec8b - Show all commits

View File

@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
namespace MyWebLog.Data;
public static class WebLogUserExtensions
{
/// <summary>
/// Find a user by their log on information (non-tracked)
/// </summary>
/// <param name="email">The user's e-mail address</param>
/// <param name="pwHash">The hash of the password provided by the user</param>
/// <returns>The user, if the credentials match; null if they do not</returns>
public static async Task<WebLogUser?> FindByEmail(this DbSet<WebLogUser> db, string email) =>
await db.SingleOrDefaultAsync(wlu => wlu.UserName == email).ConfigureAwait(false);
}

View File

@ -56,6 +56,12 @@ public sealed class WebLogDbContext : DbContext
/// <param name="options">Configuration options</param>
public WebLogDbContext(DbContextOptions<WebLogDbContext> options) : base(options) { }
/// <inheritdoc />
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
}
/// <inheritdoc />
protected override void OnModelCreating(ModelBuilder modelBuilder)
{

View File

@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Mvc;
namespace MyWebLog.Features.Admin;
/// <summary>
/// Controller for admin-specific displays and routes
/// </summary>
[Route("/admin")]
public class AdminController : MyWebLogController
{
/// <inheritdoc />
public AdminController(WebLogDbContext db) : base(db) { }
[HttpGet("")]
public IActionResult Index()
{
return View();
}
}

View File

@ -0,0 +1,5 @@
@{
Layout = "_AdminLayout";
ViewBag.Title = Resources.Dashboard;
}
<p>You're logged on!</p>

View File

@ -0,0 +1,48 @@
@inject IHttpContextAccessor ctxAcc
@{
var details = WebLogCache.Get(ctxAcc.HttpContext!);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title &laquo; @Resources.Admin &laquo; @details.Name</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="~/css/admin.css">
</head>
<body>
<header>
<nav class="navbar navbar-dark bg-dark navbar-expand-md justify-content-start px-2">
<div class="container-fluid">
<a class="navbar-brand" href="~/">@details.Name</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText"
aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<span class="navbar-text">@ViewBag.Title</span>
@await Html.PartialAsync("_LogOnOffPartial")
</div>
</div>
</nav>
</header>
<main>
<h2 class="pb-3">@ViewBag.Title</h2>
@* Each.Messages
@Current.ToDisplay
@EndEach *@
@RenderBody()
</main>
<footer>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12 text-end"><img src="~/img/logo-light.png" alt="myWebLog"></div>
</div>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
</body>
</html>

View File

@ -0,0 +1,11 @@
<ul class="navbar-nav flex-grow-1 justify-content-end">
@if (User is not null && (User.Identity?.IsAuthenticated ?? false))
{
<li class="nav-item"><a class="nav-link" asp-action="Index" asp-controller="Admin">@Resources.Dashboard</a></li>
<li class="nav-item"><a class="nav-link" asp-action="LogOff" asp-controller="User">@Resources.LogOff</a></li>
}
else
{
<li class="nav-item"><a class="nav-link" asp-action="LogOn" asp-controller="User">@Resources.LogOn</a></li>
}
</ul>

View File

@ -0,0 +1,30 @@
@model LogOnModel
@{
Layout = "_AdminLayout";
ViewBag.Title = @Resources.LogOn;
}
<article>
<form asp-action="DoLogOn" asp-controller="User" method="post">
<div class="container">
<div class="row pb-3">
<div class="col col-md-6 col-lg-4 offset-lg-2">
<div class="form-floating">
<input type="email" asp-for="EmailAddress" class="form-control" autofocus>
<label asp-for="EmailAddress"></label>
</div>
</div>
<div class="col col-md-6 col-lg-4">
<div class="form-floating">
<input type="password" asp-for="Password" class="form-control">
<label asp-for="Password"></label>
</div>
</div>
</div>
<div class="row pb-3">
<div class="col text-center">
<button type="submit" class="btn btn-primary">@Resources.LogOn</button>
</div>
</div>
</div>
</form>
</article>

View File

@ -0,0 +1,24 @@
using System.ComponentModel.DataAnnotations;
namespace MyWebLog.Features.Users;
/// <summary>
/// The model to use to allow a user to log on
/// </summary>
public class LogOnModel
{
/// <summary>
/// The user's e-mail address
/// </summary>
[Required(AllowEmptyStrings = false)]
[EmailAddress]
[Display(ResourceType = typeof(Resources), Name = "EmailAddress")]
public string EmailAddress { get; set; } = "";
/// <summary>
/// The user's password
/// </summary>
[Required(AllowEmptyStrings = false)]
[Display(ResourceType = typeof(Resources), Name = "Password")]
public string Password { get; set; } = "";
}

View File

@ -1,4 +1,8 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
@ -7,6 +11,7 @@ namespace MyWebLog.Features.Users;
/// <summary>
/// Controller for the users feature
/// </summary>
[Route("/user")]
public class UserController : MyWebLogController
{
/// <summary>
@ -19,15 +24,53 @@ public class UserController : MyWebLogController
internal static string HashedPassword(string plainText, string email, Guid salt)
{
var allSalt = salt.ToByteArray().Concat(Encoding.UTF8.GetBytes(email)).ToArray();
using var alg = new Rfc2898DeriveBytes(plainText, allSalt, 2_048);
using Rfc2898DeriveBytes alg = new(plainText, allSalt, 2_048);
return Convert.ToBase64String(alg.GetBytes(64));
}
/// <inheritdoc />
public UserController(WebLogDbContext db) : base(db) { }
public IActionResult Index()
[HttpGet("log-on")]
public IActionResult LogOn() =>
View(new LogOnModel());
[HttpPost("log-on")]
public async Task<IActionResult> DoLogOn(LogOnModel model)
{
return View();
var user = await Db.Users.FindByEmail(model.EmailAddress);
if (user == null || user.PasswordHash != HashedPassword(model.Password, user.UserName, user.Salt))
{
// TODO: make error, not 404
return NotFound();
}
List<Claim> claims = new()
{
new(ClaimTypes.NameIdentifier, user.Id),
new(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
new(ClaimTypes.GivenName, user.PreferredName),
new(ClaimTypes.Role, user.AuthorizationLevel.ToString())
};
ClaimsIdentity identity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(identity.AuthenticationType, new(identity),
new() { IssuedUtc = DateTime.UtcNow });
// TODO: confirmation message
return RedirectToAction("Index", "Admin");
}
[HttpGet("log-off")]
[Authorize]
public async Task<IActionResult> LogOff()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// TODO: confirmation message
return LocalRedirect("~/");
}
}

View File

@ -0,0 +1,6 @@
@namespace MyWebLog.Features
@using MyWebLog
@using MyWebLog.Properties
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -1,2 +1,3 @@
global using MyWebLog.Data;
global using MyWebLog.Features.Shared;
global using MyWebLog.Properties;

View File

@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<Folder Include="Features\Admin\" />
<Folder Include="wwwroot\img\" />
</ItemGroup>
<ItemGroup>
@ -21,4 +21,19 @@
<ProjectReference Include="..\MyWebLog.Data\MyWebLog.Data.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyWebLog;
using MyWebLog.Features;
@ -12,8 +13,11 @@ if (args.Length > 0 && args[0] == "init")
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMvc(opts => opts.Conventions.Add(new FeatureControllerModelConvention()))
.AddRazorOptions(opts =>
builder.Services.AddMvc(opts =>
{
opts.Conventions.Add(new FeatureControllerModelConvention());
opts.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
}).AddRazorOptions(opts =>
{
opts.ViewLocationFormats.Clear();
opts.ViewLocationFormats.Add("/Themes/{3}/{0}.cshtml");

View File

@ -0,0 +1,117 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MyWebLog.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MyWebLog.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Admin.
/// </summary>
public static string Admin {
get {
return ResourceManager.GetString("Admin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dashboard.
/// </summary>
public static string Dashboard {
get {
return ResourceManager.GetString("Dashboard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to E-mail Address.
/// </summary>
public static string EmailAddress {
get {
return ResourceManager.GetString("EmailAddress", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Log Off.
/// </summary>
public static string LogOff {
get {
return ResourceManager.GetString("LogOff", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Log On.
/// </summary>
public static string LogOn {
get {
return ResourceManager.GetString("LogOn", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Password.
/// </summary>
public static string Password {
get {
return ResourceManager.GetString("Password", resourceCulture);
}
}
}
}

View File

@ -0,0 +1,138 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Admin" xml:space="preserve">
<value>Admin</value>
</data>
<data name="Dashboard" xml:space="preserve">
<value>Dashboard</value>
</data>
<data name="EmailAddress" xml:space="preserve">
<value>E-mail Address</value>
</data>
<data name="LogOff" xml:space="preserve">
<value>Log Off</value>
</data>
<data name="LogOn" xml:space="preserve">
<value>Log On</value>
</data>
<data name="Password" xml:space="preserve">
<value>Password</value>
</data>
</root>

View File

@ -0,0 +1,6 @@
<footer>
<hr>
<div class="container-fluid text-end">
<img src="img/logo-dark.png" alt="myWebLog">
</div>
</footer>

View File

@ -0,0 +1,23 @@
@inject IHttpContextAccessor ctxAcc
@{
var details = WebLogCache.Get(ctxAcc.HttpContext!);
}
<header>
<nav class="navbar navbar-light bg-light navbar-expand-md justify-content-start px-2">
<div class="container-fluid">
<a class="navbar-brand" href="~/">@details.Name</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText"
aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
@if (details.Subtitle is not null)
{
<span class="navbar-text">@details.Subtitle</span>
}
@* TODO: list pages for current web log *@
@await Html.PartialAsync("_LogOnOffPartial")
</div>
</div>
</nav>
</header>

View File

@ -1,14 +1,37 @@
@inject IHttpContextAccessor ctxAcc
@{
var details = WebLogCache.Get(ctxAcc.HttpContext!);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width">
<title>@ViewBag.Title &laquo; @WebLogCache.Get(ctxAcc.HttpContext!).Name</title>
<meta name="generator" content="myWebLog 2">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="~/css/@details.ThemePath/style.css">
@await RenderSectionAsync("Style", false)
<title>@ViewBag.Title &laquo; @details.Name</title>
</head>
<body>
<div>
@if (IsSectionDefined("Header"))
{
@await RenderSectionAsync("Header")
}
else
{
@await Html.PartialAsync("_DefaultHeader")
}
<main>
@RenderBody()
</div>
</main>
@if (IsSectionDefined("Footer"))
{
@await RenderSectionAsync("Footer")
} else
{
@await Html.PartialAsync("_DefaultFooter")
}
@await RenderSectionAsync("Script", false)
</body>
</html>

View File

@ -73,8 +73,8 @@ public class WebLogMiddleware
{
var host = WebLogCache.HostToDb(context);
if (WebLogCache.Exists(host)) return;
if (!WebLogCache.Exists(host))
{
var db = context.RequestServices.GetRequiredService<WebLogDbContext>();
var details = await db.WebLogDetails.FindByHost(context.Request.Host.ToUriComponent());
if (details == null)
@ -84,6 +84,7 @@ public class WebLogMiddleware
}
WebLogCache.Set(host, details);
}
await _next.Invoke(context);
}

View File

@ -0,0 +1,5 @@
footer {
background-color: #808080;
border-top: solid 1px black;
color: white;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB