chore: applied code style

This commit is contained in:
Mia Rose Winter 2024-01-11 15:15:30 +01:00
parent 760203083a
commit 3ce25305a9
Signed by: miawinter
GPG key ID: 4B6F6A83178F595E
6 changed files with 152 additions and 172 deletions

View file

@ -10,13 +10,11 @@
using Wave.Components.Account.Pages.Manage; using Wave.Components.Account.Pages.Manage;
using Wave.Data; using Wave.Data;
namespace Microsoft.AspNetCore.Routing namespace Microsoft.AspNetCore.Routing;
{
internal static class IdentityComponentsEndpointRouteBuilderExtensions internal static class IdentityComponentsEndpointRouteBuilderExtensions {
{
// These endpoints are required by the Identity Razor components defined in the /Components/Account/Pages directory of this project. // These endpoints are required by the Identity Razor components defined in the /Components/Account/Pages directory of this project.
public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEndpointRouteBuilder endpoints) public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEndpointRouteBuilder endpoints) {
{
ArgumentNullException.ThrowIfNull(endpoints); ArgumentNullException.ThrowIfNull(endpoints);
var accountGroup = endpoints.MapGroup("/Account"); var accountGroup = endpoints.MapGroup("/Account");
@ -25,11 +23,11 @@ public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEn
HttpContext context, HttpContext context,
[FromServices] SignInManager<ApplicationUser> signInManager, [FromServices] SignInManager<ApplicationUser> signInManager,
[FromForm] string provider, [FromForm] string provider,
[FromForm] string returnUrl) => [FromForm] string returnUrl) => {
{
IEnumerable<KeyValuePair<string, StringValues>> query = [ IEnumerable<KeyValuePair<string, StringValues>> query = [
new("ReturnUrl", returnUrl), new("ReturnUrl", returnUrl),
new("Action", ExternalLogin.LoginCallbackAction)]; new("Action", ExternalLogin.LoginCallbackAction)
];
var redirectUrl = UriHelper.BuildRelative( var redirectUrl = UriHelper.BuildRelative(
context.Request.PathBase, context.Request.PathBase,
@ -43,8 +41,7 @@ public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEn
accountGroup.MapPost("/Logout", async ( accountGroup.MapPost("/Logout", async (
ClaimsPrincipal user, ClaimsPrincipal user,
SignInManager<ApplicationUser> signInManager, SignInManager<ApplicationUser> signInManager,
[FromForm] string returnUrl) => [FromForm] string returnUrl) => {
{
await signInManager.SignOutAsync(); await signInManager.SignOutAsync();
return TypedResults.LocalRedirect($"~/{returnUrl}"); return TypedResults.LocalRedirect($"~/{returnUrl}");
}); });
@ -54,8 +51,7 @@ public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEn
manageGroup.MapPost("/LinkExternalLogin", async ( manageGroup.MapPost("/LinkExternalLogin", async (
HttpContext context, HttpContext context,
[FromServices] SignInManager<ApplicationUser> signInManager, [FromServices] SignInManager<ApplicationUser> signInManager,
[FromForm] string provider) => [FromForm] string provider) => {
{
// Clear the existing external cookie to ensure a clean login process // Clear the existing external cookie to ensure a clean login process
await context.SignOutAsync(IdentityConstants.ExternalScheme); await context.SignOutAsync(IdentityConstants.ExternalScheme);
@ -64,7 +60,8 @@ public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEn
"/Account/Manage/ExternalLogins", "/Account/Manage/ExternalLogins",
QueryString.Create("Action", ExternalLogins.LinkLoginCallbackAction)); QueryString.Create("Action", ExternalLogins.LinkLoginCallbackAction));
var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, signInManager.UserManager.GetUserId(context.User)); var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl,
signInManager.UserManager.GetUserId(context.User));
return TypedResults.Challenge(properties, [provider]); return TypedResults.Challenge(properties, [provider]);
}); });
@ -74,11 +71,9 @@ public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEn
manageGroup.MapPost("/DownloadPersonalData", async ( manageGroup.MapPost("/DownloadPersonalData", async (
HttpContext context, HttpContext context,
[FromServices] UserManager<ApplicationUser> userManager, [FromServices] UserManager<ApplicationUser> userManager,
[FromServices] AuthenticationStateProvider authenticationStateProvider) => [FromServices] AuthenticationStateProvider authenticationStateProvider) => {
{
var user = await userManager.GetUserAsync(context.User); var user = await userManager.GetUserAsync(context.User);
if (user is null) if (user is null) {
{
return Results.NotFound($"Unable to load user with ID '{userManager.GetUserId(context.User)}'."); return Results.NotFound($"Unable to load user with ID '{userManager.GetUserId(context.User)}'.");
} }
@ -89,14 +84,12 @@ public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEn
var personalData = new Dictionary<string, string>(); var personalData = new Dictionary<string, string>();
var personalDataProps = typeof(ApplicationUser).GetProperties().Where( var personalDataProps = typeof(ApplicationUser).GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute))); prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
foreach (var p in personalDataProps) foreach (var p in personalDataProps) {
{
personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null"); personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null");
} }
var logins = await userManager.GetLoginsAsync(user); var logins = await userManager.GetLoginsAsync(user);
foreach (var l in logins) foreach (var l in logins) {
{
personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey); personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey);
} }
@ -109,5 +102,4 @@ public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEn
return accountGroup; return accountGroup;
} }
}
} }

View file

@ -2,20 +2,21 @@
using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Identity.UI.Services;
using Wave.Data; using Wave.Data;
namespace Wave.Components.Account namespace Wave.Components.Account;
{
// Remove the "else if (EmailSender is IdentityNoOpEmailSender)" block from RegisterConfirmation.razor after updating with a real implementation. // Remove the "else if (EmailSender is IdentityNoOpEmailSender)" block from RegisterConfirmation.razor after updating with a real implementation.
internal sealed class IdentityNoOpEmailSender : IEmailSender<ApplicationUser> internal sealed class IdentityNoOpEmailSender : IEmailSender<ApplicationUser> {
{
private readonly IEmailSender emailSender = new NoOpEmailSender(); private readonly IEmailSender emailSender = new NoOpEmailSender();
public Task SendConfirmationLinkAsync(ApplicationUser user, string email, string confirmationLink) => public Task SendConfirmationLinkAsync(ApplicationUser user, string email, string confirmationLink) =>
emailSender.SendEmailAsync(email, "Confirm your email", $"Please confirm your account by <a href='{confirmationLink}'>clicking here</a>."); emailSender.SendEmailAsync(email, "Confirm your email",
$"Please confirm your account by <a href='{confirmationLink}'>clicking here</a>.");
public Task SendPasswordResetLinkAsync(ApplicationUser user, string email, string resetLink) => public Task SendPasswordResetLinkAsync(ApplicationUser user, string email, string resetLink) =>
emailSender.SendEmailAsync(email, "Reset your password", $"Please reset your password by <a href='{resetLink}'>clicking here</a>."); emailSender.SendEmailAsync(email, "Reset your password",
$"Please reset your password by <a href='{resetLink}'>clicking here</a>.");
public Task SendPasswordResetCodeAsync(ApplicationUser user, string email, string resetCode) => public Task SendPasswordResetCodeAsync(ApplicationUser user, string email, string resetCode) =>
emailSender.SendEmailAsync(email, "Reset your password", $"Please reset your password using the following code: {resetCode}"); emailSender.SendEmailAsync(email, "Reset your password",
} $"Please reset your password using the following code: {resetCode}");
} }

View file

@ -1,14 +1,12 @@
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
namespace Wave.Components.Account namespace Wave.Components.Account;
{
internal sealed class IdentityRedirectManager(NavigationManager navigationManager) internal sealed class IdentityRedirectManager(NavigationManager navigationManager) {
{
public const string StatusCookieName = "Identity.StatusMessage"; public const string StatusCookieName = "Identity.StatusMessage";
private static readonly CookieBuilder StatusCookieBuilder = new() private static readonly CookieBuilder StatusCookieBuilder = new() {
{
SameSite = SameSiteMode.Strict, SameSite = SameSiteMode.Strict,
HttpOnly = true, HttpOnly = true,
IsEssential = true, IsEssential = true,
@ -16,33 +14,30 @@ internal sealed class IdentityRedirectManager(NavigationManager navigationManage
}; };
[DoesNotReturn] [DoesNotReturn]
public void RedirectTo(string? uri) public void RedirectTo(string? uri) {
{
uri ??= ""; uri ??= "";
// Prevent open redirects. // Prevent open redirects.
if (!Uri.IsWellFormedUriString(uri, UriKind.Relative)) if (!Uri.IsWellFormedUriString(uri, UriKind.Relative)) {
{
uri = navigationManager.ToBaseRelativePath(uri); uri = navigationManager.ToBaseRelativePath(uri);
} }
// During static rendering, NavigateTo throws a NavigationException which is handled by the framework as a redirect. // During static rendering, NavigateTo throws a NavigationException which is handled by the framework as a redirect.
// So as long as this is called from a statically rendered Identity component, the InvalidOperationException is never thrown. // So as long as this is called from a statically rendered Identity component, the InvalidOperationException is never thrown.
navigationManager.NavigateTo(uri); navigationManager.NavigateTo(uri);
throw new InvalidOperationException($"{nameof(IdentityRedirectManager)} can only be used during static rendering."); throw new InvalidOperationException(
$"{nameof(IdentityRedirectManager)} can only be used during static rendering.");
} }
[DoesNotReturn] [DoesNotReturn]
public void RedirectTo(string uri, Dictionary<string, object?> queryParameters) public void RedirectTo(string uri, Dictionary<string, object?> queryParameters) {
{
var uriWithoutQuery = navigationManager.ToAbsoluteUri(uri).GetLeftPart(UriPartial.Path); var uriWithoutQuery = navigationManager.ToAbsoluteUri(uri).GetLeftPart(UriPartial.Path);
var newUri = navigationManager.GetUriWithQueryParameters(uriWithoutQuery, queryParameters); var newUri = navigationManager.GetUriWithQueryParameters(uriWithoutQuery, queryParameters);
RedirectTo(newUri); RedirectTo(newUri);
} }
[DoesNotReturn] [DoesNotReturn]
public void RedirectToWithStatus(string uri, string message, HttpContext context) public void RedirectToWithStatus(string uri, string message, HttpContext context) {
{
context.Response.Cookies.Append(StatusCookieName, message, StatusCookieBuilder.Build(context)); context.Response.Cookies.Append(StatusCookieName, message, StatusCookieBuilder.Build(context));
RedirectTo(uri); RedirectTo(uri);
} }
@ -55,5 +50,4 @@ public void RedirectToWithStatus(string uri, string message, HttpContext context
[DoesNotReturn] [DoesNotReturn]
public void RedirectToCurrentPageWithStatus(string message, HttpContext context) public void RedirectToCurrentPageWithStatus(string message, HttpContext context)
=> RedirectToWithStatus(CurrentPath, message, context); => RedirectToWithStatus(CurrentPath, message, context);
}
} }

View file

@ -1,20 +1,19 @@
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Wave.Data; using Wave.Data;
namespace Wave.Components.Account namespace Wave.Components.Account;
{
internal sealed class IdentityUserAccessor(UserManager<ApplicationUser> userManager, IdentityRedirectManager redirectManager) internal sealed class IdentityUserAccessor(
{ UserManager<ApplicationUser> userManager,
public async Task<ApplicationUser> GetRequiredUserAsync(HttpContext context) IdentityRedirectManager redirectManager) {
{ public async Task<ApplicationUser> GetRequiredUserAsync(HttpContext context) {
var user = await userManager.GetUserAsync(context.User); var user = await userManager.GetUserAsync(context.User);
if (user is null) if (user is null) {
{ redirectManager.RedirectToWithStatus("Account/InvalidUser",
redirectManager.RedirectToWithStatus("Account/InvalidUser", $"Error: Unable to load user with ID '{userManager.GetUserId(context.User)}'.", context); $"Error: Unable to load user with ID '{userManager.GetUserId(context.User)}'.", context);
} }
return user; return user;
} }
}
} }

View file

@ -1,9 +1,7 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Wave.Data namespace Wave.Data;
{
public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext<ApplicationUser>(options) public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
{ : IdentityDbContext<ApplicationUser>(options) { }
}
}

View file

@ -1,10 +1,6 @@
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
namespace Wave.Data namespace Wave.Data;
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
}
} // Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser { }