Files
Umbraco-CMS/src/Umbraco.Web.Common/Extensions/ApplicationBuilderExtensions.cs
Shannon Deminick 39aeec0f1f Implement password config storage for members (#10170)
* Getting new netcore PublicAccessChecker in place

* Adds full test coverage for PublicAccessChecker

* remove PublicAccessComposer

* adjust namespaces, ensure RoleManager works, separate public access controller, reduce content controller

* Implements the required methods on IMemberManager, removes old migrated code

* Updates routing to be able to re-route, Fixes middleware ordering ensuring endpoints are last, refactors pipeline options, adds public access middleware, ensures public access follows all hops

* adds note

* adds note

* Cleans up ext methods, ensures that members identity is added on both front-end and back ends. updates how UmbracoApplicationBuilder works in that it explicitly starts endpoints at the time of calling.

* Changes name to IUmbracoEndpointBuilder

* adds note

* Fixing tests, fixing error describers so there's 2x one for back office, one for members, fixes TryConvertTo, fixes login redirect

* fixing build

* Updates user manager to correctly validate password hashing and injects the IBackOfficeUserPasswordChecker

* Merges PR

* Fixes up build and notes

* Implements security stamp and email confirmed for members, cleans up a bunch of repo/service level member groups stuff, shares user store code between members and users and fixes the user identity object so we arent' tracking both groups and roles.

* Security stamp for members is now working

* Fixes keepalive, fixes PublicAccessMiddleware to not throw, updates startup code to be more clear and removes magic that registers middleware.

* adds note

* removes unused filter, fixes build

* fixes WebPath and tests

* Looks up entities in one query

* remove usings

* Fix test, remove stylesheet

* Set status code before we write to response to avoid error

* Ensures that users and members are validated when logging in. Shares more code between users and members.

* merge changes

* oops

* Reducing and removing published member cache

* Fixes RepositoryCacheKeys to ensure the keys are normalized

* oops didn't mean to commit this

* Fix casing issues with caching, stop boxing value types for all cache operations, stop re-creating string keys in DefaultRepositoryCachePolicy

* oops didn't mean to comit this

* bah, far out this keeps getting recommitted. sorry

* cannot inject IPublishedMemberCache and cannot have IPublishedMember

* splits out files, fixes build

* fix tests

* removes membership provider classes

* removes membership provider classes

* updates the identity map definition

* reverts commented out lines

* reverts commented out lines

* Implements members Password config in db, fixes members cookie auth to not interfere with the back office cookie auth, fixes Startup sequence, fixes startup pipeline

* commits change to Startup

* Rename migration from `MemberTableColumns2` to `AddPasswordConfigToMemberTable`

* Fix test

* Fix tests, but adding default passwordConfig to members

Co-authored-by: Bjarke Berg <mail@bergmania.dk>
2021-04-22 15:59:13 +02:00

187 lines
7.3 KiB
C#

using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Serilog.Context;
using SixLabors.ImageSharp.Web.DependencyInjection;
using StackExchange.Profiling;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Logging.Serilog.Enrichers;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Web.Common.ApplicationBuilder;
using Umbraco.Cms.Web.Common.Middleware;
using Umbraco.Cms.Web.Common.Plugins;
namespace Umbraco.Extensions
{
/// <summary>
/// <see cref="IApplicationBuilder"/> extensions for Umbraco
/// </summary>
public static class ApplicationBuilderExtensions
{
/// <summary>
/// Configures and use services required for using Umbraco
/// </summary>
public static IUmbracoApplicationBuilder UseUmbraco(this IApplicationBuilder app)
{
IOptions<UmbracoPipelineOptions> startupOptions = app.ApplicationServices.GetRequiredService<IOptions<UmbracoPipelineOptions>>();
app.RunPrePipeline(startupOptions.Value);
// TODO: Should we do some checks like this to verify that the corresponding "Add" methods have been called for the
// corresponding "Use" methods?
// https://github.com/dotnet/aspnetcore/blob/b795ac3546eb3e2f47a01a64feb3020794ca33bb/src/Mvc/Mvc.Core/src/Builder/MvcApplicationBuilderExtensions.cs#L132
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
app.UseUmbracoCore();
app.UseUmbracoRequestLogging();
// We need to add this before UseRouting so that the UmbracoContext and other middlewares are executed
// before endpoint routing middleware.
app.UseUmbracoRouting();
app.UseStatusCodePages();
// Important we handle image manipulations before the static files, otherwise the querystring is just ignored.
// TODO: Since we are dependent on these we need to register them but what happens when we call this multiple times since we are dependent on this for UseUmbracoBackOffice too?
app.UseImageSharp();
app.UseStaticFiles();
app.UseUmbracoPlugins();
// UseRouting adds endpoint routing middleware, this means that middlewares registered after this one
// will execute after endpoint routing. The ordering of everything is quite important here, see
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0
// where we need to have UseAuthentication and UseAuthorization proceeding this call but before
// endpoints are defined.
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
// This must come after auth because the culture is based on the auth'd user
app.UseRequestLocalization();
// Must be called after UseRouting and before UseEndpoints
app.UseSession();
// DO NOT PUT ANY UseEndpoints declarations here!! Those must all come very last in the pipeline,
// endpoints are terminating middleware. All of our endpoints are declared in ext of IUmbracoApplicationBuilder
return ActivatorUtilities.CreateInstance<UmbracoApplicationBuilder>(
app.ApplicationServices,
new object[] { app });
}
private static void RunPrePipeline(this IApplicationBuilder app, UmbracoPipelineOptions startupOptions)
{
foreach (IUmbracoPipelineFilter filter in startupOptions.PipelineFilters)
{
filter.OnPrePipeline(app);
}
}
/// <summary>
/// Returns true if Umbraco <see cref="IRuntimeState"/> is greater than <see cref="RuntimeLevel.BootFailed"/>
/// </summary>
public static bool UmbracoCanBoot(this IApplicationBuilder app)
=> app.ApplicationServices.GetRequiredService<IRuntimeState>().UmbracoCanBoot();
/// <summary>
/// Enables core Umbraco functionality
/// </summary>
public static IApplicationBuilder UseUmbracoCore(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (!app.UmbracoCanBoot())
{
return app;
}
// Register our global threadabort enricher for logging
ThreadAbortExceptionEnricher threadAbortEnricher = app.ApplicationServices.GetRequiredService<ThreadAbortExceptionEnricher>();
LogContext.Push(threadAbortEnricher); // NOTE: We are not in a using clause because we are not removing it, it is on the global context
return app;
}
/// <summary>
/// Enables middlewares required to run Umbraco
/// </summary>
/// <remarks>
/// Must occur before UseRouting
/// </remarks>
public static IApplicationBuilder UseUmbracoRouting(this IApplicationBuilder app)
{
// TODO: This method could be internal or part of another call - this is a required system so should't be 'opt-in'
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (!app.UmbracoCanBoot())
{
app.UseStaticFiles(); // We need static files to show the nice error page.
app.UseMiddleware<BootFailedMiddleware>();
}
else
{
app.UseMiddleware<PreviewAuthenticationMiddleware>();
app.UseMiddleware<UmbracoRequestMiddleware>();
app.UseMiddleware<MiniProfilerMiddleware>();
}
return app;
}
/// <summary>
/// Adds request based serilog enrichers to the LogContext for each request
/// </summary>
public static IApplicationBuilder UseUmbracoRequestLogging(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (!app.UmbracoCanBoot()) return app;
app.UseMiddleware<UmbracoRequestLoggingMiddleware>();
return app;
}
public static IApplicationBuilder UseUmbracoPlugins(this IApplicationBuilder app)
{
var hostingEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();
var umbracoPluginSettings = app.ApplicationServices.GetRequiredService<IOptions<UmbracoPluginSettings>>();
var pluginFolder = hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.AppPlugins);
// Ensure the plugin folder exists
Directory.CreateDirectory(pluginFolder);
var fileProvider = new UmbracoPluginPhysicalFileProvider(
pluginFolder,
umbracoPluginSettings);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = fileProvider,
RequestPath = Constants.SystemDirectories.AppPlugins
});
return app;
}
}
}