Style: C# 12 Primary constructor
This commit is contained in:
@@ -7,10 +7,10 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Hutopy.Infrastructure.Data;
|
||||
|
||||
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
|
||||
public class ApplicationDbContext(
|
||||
DbContextOptions<ApplicationDbContext> options)
|
||||
: IdentityDbContext<ApplicationUser>(options), IApplicationDbContext
|
||||
{
|
||||
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
|
||||
|
||||
public DbSet<TodoList> TodoLists => Set<TodoList>();
|
||||
|
||||
public DbSet<TodoItem> TodoItems => Set<TodoItem>();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Hutopy.Domain.Constants;
|
||||
using Hutopy.Domain.Constants;
|
||||
using Hutopy.Domain.Entities;
|
||||
using Hutopy.Infrastructure.Identity;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
@@ -10,44 +9,35 @@ using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Hutopy.Infrastructure.Data;
|
||||
|
||||
public static class InitialiserExtensions
|
||||
public static class InitializerExtensions
|
||||
{
|
||||
public static async Task InitialiseDatabaseAsync(this WebApplication app)
|
||||
{
|
||||
using var scope = app.Services.CreateScope();
|
||||
|
||||
var initialiser = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitialiser>();
|
||||
var initializer = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitializer>();
|
||||
|
||||
await initialiser.InitialiseAsync();
|
||||
await initializer.InitialiseAsync();
|
||||
|
||||
await initialiser.SeedAsync();
|
||||
await initializer.SeedAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public class ApplicationDbContextInitialiser
|
||||
public class ApplicationDbContextInitializer(
|
||||
ILogger<ApplicationDbContextInitializer> logger,
|
||||
ApplicationDbContext context,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
RoleManager<IdentityRole> roleManager)
|
||||
{
|
||||
private readonly ILogger<ApplicationDbContextInitialiser> _logger;
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly RoleManager<IdentityRole> _roleManager;
|
||||
|
||||
public ApplicationDbContextInitialiser(ILogger<ApplicationDbContextInitialiser> logger, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
_userManager = userManager;
|
||||
_roleManager = roleManager;
|
||||
}
|
||||
|
||||
public async Task InitialiseAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _context.Database.MigrateAsync();
|
||||
await context.Database.MigrateAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "An error occurred while initialising the database.");
|
||||
logger.LogError(ex, "An error occurred while initialising the database.");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -60,38 +50,38 @@ public class ApplicationDbContextInitialiser
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "An error occurred while seeding the database.");
|
||||
logger.LogError(ex, "An error occurred while seeding the database.");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task TrySeedAsync()
|
||||
private async Task TrySeedAsync()
|
||||
{
|
||||
// Default roles
|
||||
var administratorRole = new IdentityRole(Roles.Administrator);
|
||||
|
||||
if (_roleManager.Roles.All(r => r.Name != administratorRole.Name))
|
||||
if (roleManager.Roles.All(r => r.Name != administratorRole.Name))
|
||||
{
|
||||
await _roleManager.CreateAsync(administratorRole);
|
||||
await roleManager.CreateAsync(administratorRole);
|
||||
}
|
||||
|
||||
// Default users
|
||||
var administrator = new ApplicationUser { UserName = "administrator@localhost", Email = "administrator@localhost" };
|
||||
|
||||
if (_userManager.Users.All(u => u.UserName != administrator.UserName))
|
||||
if (userManager.Users.All(u => u.UserName != administrator.UserName))
|
||||
{
|
||||
await _userManager.CreateAsync(administrator, "Administrator1!");
|
||||
await userManager.CreateAsync(administrator, "Administrator1!");
|
||||
if (!string.IsNullOrWhiteSpace(administratorRole.Name))
|
||||
{
|
||||
await _userManager.AddToRolesAsync(administrator, new [] { administratorRole.Name });
|
||||
await userManager.AddToRolesAsync(administrator, new [] { administratorRole.Name });
|
||||
}
|
||||
}
|
||||
|
||||
// Default data
|
||||
// Seed, if necessary
|
||||
if (!_context.TodoLists.Any())
|
||||
if (!context.TodoLists.Any())
|
||||
{
|
||||
_context.TodoLists.Add(new TodoList
|
||||
context.TodoLists.Add(new TodoList
|
||||
{
|
||||
Title = "Todo List",
|
||||
Items =
|
||||
@@ -103,7 +93,7 @@ public class ApplicationDbContextInitialiser
|
||||
}
|
||||
});
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,19 +6,10 @@ using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
|
||||
namespace Hutopy.Infrastructure.Data.Interceptors;
|
||||
|
||||
public class AuditableEntityInterceptor : SaveChangesInterceptor
|
||||
public class AuditableEntityInterceptor(
|
||||
IUser user,
|
||||
TimeProvider dateTime) : SaveChangesInterceptor
|
||||
{
|
||||
private readonly IUser _user;
|
||||
private readonly TimeProvider _dateTime;
|
||||
|
||||
public AuditableEntityInterceptor(
|
||||
IUser user,
|
||||
TimeProvider dateTime)
|
||||
{
|
||||
_user = user;
|
||||
_dateTime = dateTime;
|
||||
}
|
||||
|
||||
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
UpdateEntities(eventData.Context);
|
||||
@@ -41,13 +32,13 @@ public class AuditableEntityInterceptor : SaveChangesInterceptor
|
||||
{
|
||||
if (entry.State is EntityState.Added or EntityState.Modified || entry.HasChangedOwnedEntities())
|
||||
{
|
||||
var utcNow = _dateTime.GetUtcNow();
|
||||
var utcNow = dateTime.GetUtcNow();
|
||||
if (entry.State == EntityState.Added)
|
||||
{
|
||||
entry.Entity.CreatedBy = _user.Id;
|
||||
entry.Entity.CreatedBy = user.Id;
|
||||
entry.Entity.Created = utcNow;
|
||||
}
|
||||
entry.Entity.LastModifiedBy = _user.Id;
|
||||
entry.Entity.LastModifiedBy = user.Id;
|
||||
entry.Entity.LastModified = utcNow;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,15 +5,10 @@ using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
|
||||
namespace Hutopy.Infrastructure.Data.Interceptors;
|
||||
|
||||
public class DispatchDomainEventsInterceptor : SaveChangesInterceptor
|
||||
public class DispatchDomainEventsInterceptor(
|
||||
IPublisher mediator)
|
||||
: SaveChangesInterceptor
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public DispatchDomainEventsInterceptor(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
DispatchDomainEvents(eventData.Context).GetAwaiter().GetResult();
|
||||
@@ -45,6 +40,6 @@ public class DispatchDomainEventsInterceptor : SaveChangesInterceptor
|
||||
entities.ToList().ForEach(e => e.ClearDomainEvents());
|
||||
|
||||
foreach (var domainEvent in domainEvents)
|
||||
await _mediator.Publish(domainEvent);
|
||||
await mediator.Publish(domainEvent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@ using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Microsoft.Extensions.DependencyInjection;
|
||||
namespace Hutopy.Infrastructure;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
@@ -34,7 +35,7 @@ public static class DependencyInjection
|
||||
|
||||
services.AddScoped<IApplicationDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());
|
||||
|
||||
services.AddScoped<ApplicationDbContextInitialiser>();
|
||||
services.AddScoped<ApplicationDbContextInitializer>();
|
||||
|
||||
services.AddAuthentication()
|
||||
.AddBearerToken(IdentityConstants.BearerScheme);
|
||||
|
||||
@@ -5,25 +5,15 @@ using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace Hutopy.Infrastructure.Identity;
|
||||
|
||||
public class IdentityService : IIdentityService
|
||||
public class IdentityService(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IUserClaimsPrincipalFactory<ApplicationUser> userClaimsPrincipalFactory,
|
||||
IAuthorizationService authorizationService)
|
||||
: IIdentityService
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly IUserClaimsPrincipalFactory<ApplicationUser> _userClaimsPrincipalFactory;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
|
||||
public IdentityService(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IUserClaimsPrincipalFactory<ApplicationUser> userClaimsPrincipalFactory,
|
||||
IAuthorizationService authorizationService)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_userClaimsPrincipalFactory = userClaimsPrincipalFactory;
|
||||
_authorizationService = authorizationService;
|
||||
}
|
||||
|
||||
public async Task<string?> GetUserNameAsync(string userId)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
var user = await userManager.FindByIdAsync(userId);
|
||||
|
||||
return user?.UserName;
|
||||
}
|
||||
@@ -36,44 +26,44 @@ public class IdentityService : IIdentityService
|
||||
Email = userName,
|
||||
};
|
||||
|
||||
var result = await _userManager.CreateAsync(user, password);
|
||||
var result = await userManager.CreateAsync(user, password);
|
||||
|
||||
return (result.ToApplicationResult(), user.Id);
|
||||
}
|
||||
|
||||
public async Task<bool> IsInRoleAsync(string userId, string role)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
var user = await userManager.FindByIdAsync(userId);
|
||||
|
||||
return user != null && await _userManager.IsInRoleAsync(user, role);
|
||||
return user != null && await userManager.IsInRoleAsync(user, role);
|
||||
}
|
||||
|
||||
public async Task<bool> AuthorizeAsync(string userId, string policyName)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
var user = await userManager.FindByIdAsync(userId);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var principal = await _userClaimsPrincipalFactory.CreateAsync(user);
|
||||
var principal = await userClaimsPrincipalFactory.CreateAsync(user);
|
||||
|
||||
var result = await _authorizationService.AuthorizeAsync(principal, policyName);
|
||||
var result = await authorizationService.AuthorizeAsync(principal, policyName);
|
||||
|
||||
return result.Succeeded;
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteUserAsync(string userId)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
var user = await userManager.FindByIdAsync(userId);
|
||||
|
||||
return user != null ? await DeleteUserAsync(user) : Result.Success();
|
||||
}
|
||||
|
||||
public async Task<Result> DeleteUserAsync(ApplicationUser user)
|
||||
{
|
||||
var result = await _userManager.DeleteAsync(user);
|
||||
var result = await userManager.DeleteAsync(user);
|
||||
|
||||
return result.ToApplicationResult();
|
||||
}
|
||||
|
||||
@@ -16,22 +16,20 @@ public class StripeService : IStripeService
|
||||
{
|
||||
var options = new SessionCreateOptions
|
||||
{
|
||||
LineItems = new List<SessionLineItemOptions>
|
||||
{
|
||||
LineItems =
|
||||
[
|
||||
new SessionLineItemOptions
|
||||
{
|
||||
PriceData = new SessionLineItemPriceDataOptions
|
||||
{
|
||||
UnitAmount = price,
|
||||
Currency = currency,
|
||||
ProductData = new SessionLineItemPriceDataProductDataOptions
|
||||
PriceData = new SessionLineItemPriceDataOptions
|
||||
{
|
||||
Name = "Tip",
|
||||
UnitAmount = price,
|
||||
Currency = currency,
|
||||
ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Tip", },
|
||||
},
|
||||
},
|
||||
Quantity = 1,
|
||||
},
|
||||
},
|
||||
Quantity = 1,
|
||||
}
|
||||
|
||||
],
|
||||
Mode = "payment",
|
||||
UiMode = "embedded",
|
||||
ReturnUrl = $"http://localhost:5173/creatorfolio",
|
||||
|
||||
Reference in New Issue
Block a user