Made admin pages dependency injectable
This commit is contained in:
10
src/HopFrame.Web.Admin/Attributes/AdminPageUrlAttribute.cs
Normal file
10
src/HopFrame.Web.Admin/Attributes/AdminPageUrlAttribute.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace HopFrame.Web.Admin.Attributes;
|
||||
|
||||
/// <summary>
|
||||
/// This attribute specifies the url of the admin page and needs to be applied on the AdminPage property in the AdminContext directly
|
||||
/// </summary>
|
||||
/// <param name="url">The page url: '/administration/{url}'</param>
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
public sealed class AdminPageUrlAttribute(string url) : Attribute {
|
||||
public string Url { get; set; } = url;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace HopFrame.Web.Admin.Attributes;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
|
||||
[AttributeUsage(AttributeTargets.Class)]
|
||||
public sealed class AdminDescriptionAttribute(string description) : Attribute {
|
||||
public string Description { get; set; } = description;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace HopFrame.Web.Admin.Attributes.Classes;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class)]
|
||||
public class AdminUrlAttribute(string url) : Attribute {
|
||||
public string Url { get; set; } = url;
|
||||
}
|
||||
@@ -18,13 +18,6 @@ public interface IAdminPageGenerator<TModel> {
|
||||
/// <param name="description">the specified description</param>
|
||||
/// <returns></returns>
|
||||
IAdminPageGenerator<TModel> Description(string description);
|
||||
|
||||
/// <summary>
|
||||
/// Sets the url for the Admin Page
|
||||
/// </summary>
|
||||
/// <param name="url">the specified url (administration/{url})</param>
|
||||
/// <returns></returns>
|
||||
IAdminPageGenerator<TModel> Url(string url);
|
||||
|
||||
/// <summary>
|
||||
/// Sets the permission needed to view the Admin Page
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using HopFrame.Web.Admin.Attributes;
|
||||
using HopFrame.Web.Admin.Models;
|
||||
using HopFrame.Web.Admin.Providers;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace HopFrame.Web.Admin.Generators.Implementation;
|
||||
|
||||
@@ -27,13 +26,14 @@ internal class AdminContextGenerator : IAdminContextGenerator {
|
||||
return (generator as AdminPageGenerator<TModel>)?.Compile();
|
||||
}
|
||||
|
||||
public TContext CompileContext<TContext>() where TContext : AdminPagesContext {
|
||||
public TContext CompileContext<TContext>(IServiceProvider provider) where TContext : AdminPagesContext {
|
||||
var type = typeof(TContext);
|
||||
var compileMethod = typeof(AdminContextGenerator).GetMethod(nameof(CompilePage));
|
||||
|
||||
var properties = type.GetProperties();
|
||||
|
||||
var context = Activator.CreateInstance<TContext>();
|
||||
var dependencies = ResolveDependencies<TContext>(provider);
|
||||
var context = Activator.CreateInstance(type, dependencies) as TContext;
|
||||
|
||||
foreach (var property in properties) {
|
||||
var propertyType = property.PropertyType.GenericTypeArguments[0];
|
||||
@@ -49,31 +49,48 @@ internal class AdminContextGenerator : IAdminContextGenerator {
|
||||
_adminPages.Add(propertyType, generatorInstance);
|
||||
}
|
||||
|
||||
context.OnModelCreating(this);
|
||||
context?.OnModelCreating(this);
|
||||
|
||||
foreach (var property in properties) {
|
||||
var modelType = property.PropertyType.GenericTypeArguments[0];
|
||||
var method = compileMethod?.MakeGenericMethod(modelType);
|
||||
property.SetValue(context, method?.Invoke(this, []));
|
||||
var compiledPage = method?.Invoke(this, []) as AdminPage;
|
||||
|
||||
var url = property.Name;
|
||||
if (property.GetCustomAttributes(false).Any(a => a is AdminPageUrlAttribute)) {
|
||||
var attribute = property.GetCustomAttributes(false)
|
||||
.Single(a => a is AdminPageUrlAttribute) as AdminPageUrlAttribute;
|
||||
|
||||
url = attribute?.Url;
|
||||
}
|
||||
compiledPage!.Url = url;
|
||||
|
||||
property.SetValue(context, compiledPage);
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
private object[] ResolveDependencies<TContext>(IServiceProvider provider) {
|
||||
return ResolveDependencies(typeof(TContext), provider);
|
||||
}
|
||||
|
||||
public static object[] ResolveDependencies(Type type, IServiceProvider provider) {
|
||||
var ctors = type.GetConstructors();
|
||||
|
||||
if (ctors.Length == 0) return [];
|
||||
if (ctors.Length > 1)
|
||||
throw new ArgumentException($"Dependencies of {type.Name} could not be resolved (multiple constructors)!");
|
||||
|
||||
public static void RegisterPages(AdminPagesContext context, IAdminPagesProvider provider, IServiceCollection services) {
|
||||
var properties = context.GetType().GetProperties();
|
||||
|
||||
foreach (var property in properties) {
|
||||
var page = property.GetValue(context) as AdminPage;
|
||||
if (page is null) continue;
|
||||
|
||||
provider.RegisterAdminPage(page.Title.ToLower(), page);
|
||||
|
||||
if (page.RepositoryProvider is not null)
|
||||
services.AddScoped(page.RepositoryProvider);
|
||||
var ctor = ctors[0];
|
||||
var depTypes = ctor.GetParameters();
|
||||
var dependencies = new object[depTypes.Length];
|
||||
|
||||
for (var i = 0; i < depTypes.Length; i++) {
|
||||
dependencies[i] = provider.GetService(depTypes[i].ParameterType);
|
||||
}
|
||||
|
||||
return dependencies;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -40,7 +40,6 @@ internal sealed class AdminPageGenerator<TModel> : IAdminPageGenerator<TModel>,
|
||||
|
||||
public IAdminPageGenerator<TModel> Title(string title) {
|
||||
Page.Title = title;
|
||||
Page.Url ??= title.ToLower();
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -49,11 +48,6 @@ internal sealed class AdminPageGenerator<TModel> : IAdminPageGenerator<TModel>,
|
||||
return this;
|
||||
}
|
||||
|
||||
public IAdminPageGenerator<TModel> Url(string url) {
|
||||
Page.Url = url;
|
||||
return this;
|
||||
}
|
||||
|
||||
public IAdminPageGenerator<TModel> ViewPermission(string permission) {
|
||||
Page.Permissions.View = permission;
|
||||
return this;
|
||||
@@ -167,11 +161,6 @@ internal sealed class AdminPageGenerator<TModel> : IAdminPageGenerator<TModel>,
|
||||
Description(attribute?.Description);
|
||||
}
|
||||
|
||||
if (attributes.Any(a => a is AdminUrlAttribute)) {
|
||||
var attribute = attributes.Single(a => a is AdminUrlAttribute) as AdminUrlAttribute;
|
||||
Url(attribute?.Url);
|
||||
}
|
||||
|
||||
if (attributes.Any(a => a is AdminPermissionsAttribute)) {
|
||||
var attribute = attributes.Single(a => a is AdminPermissionsAttribute) as AdminPermissionsAttribute;
|
||||
CreatePermission(attribute?.Permissions.Create);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json.Serialization;
|
||||
using HopFrame.Web.Admin.Generators.Implementation;
|
||||
|
||||
namespace HopFrame.Web.Admin.Models;
|
||||
|
||||
@@ -23,4 +23,11 @@ public class AdminPage {
|
||||
public bool ShowCreateButton { get; set; } = true;
|
||||
public bool ShowDeleteButton { get; set; } = true;
|
||||
public bool ShowUpdateButton { get; set; } = true;
|
||||
|
||||
public IModelRepository LoadModelRepository(IServiceProvider provider) {
|
||||
if (RepositoryProvider is null) return null;
|
||||
|
||||
var dependencies = AdminContextGenerator.ResolveDependencies(RepositoryProvider, provider);
|
||||
return Activator.CreateInstance(RepositoryProvider, dependencies) as IModelRepository;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ namespace HopFrame.Web.Admin.Providers;
|
||||
|
||||
public interface IAdminPagesProvider {
|
||||
|
||||
internal void RegisterAdminPage(string url, AdminPage page);
|
||||
AdminPage LoadAdminPage(string url);
|
||||
IList<AdminPage> LoadRegisteredAdminPages();
|
||||
AdminPage HasPageFor(Type type);
|
||||
|
||||
@@ -2,25 +2,44 @@ using HopFrame.Web.Admin.Models;
|
||||
|
||||
namespace HopFrame.Web.Admin.Providers.Implementation;
|
||||
|
||||
public class AdminPagesProvider : IAdminPagesProvider {
|
||||
private readonly IDictionary<string, AdminPage> _pages = new Dictionary<string, AdminPage>();
|
||||
|
||||
public void RegisterAdminPage(string url, AdminPage page) {
|
||||
_pages.Add(url, page);
|
||||
public class AdminPagesProvider(IServiceProvider provider) : IAdminPagesProvider {
|
||||
private static readonly IDictionary<string, PageDataStore> Pages = new Dictionary<string, PageDataStore>();
|
||||
|
||||
public static void RegisterAdminPage<TContext>(string url, Type pageType) where TContext : AdminPagesContext {
|
||||
Pages.Add(url, new PageDataStore {
|
||||
ContextType = typeof(TContext),
|
||||
PageType = pageType
|
||||
});
|
||||
}
|
||||
|
||||
public AdminPage LoadAdminPage(string url) {
|
||||
return _pages.TryGetValue(url, out var page) ? page : null;
|
||||
if (!Pages.TryGetValue(url, out var data)) return null;
|
||||
|
||||
var context = provider.GetService(data.ContextType);
|
||||
var property = data.ContextType.GetProperties()
|
||||
.SingleOrDefault(prop => prop.PropertyType == data.PageType);
|
||||
|
||||
return property?.GetValue(context) as AdminPage;
|
||||
}
|
||||
|
||||
public IList<AdminPage> LoadRegisteredAdminPages() {
|
||||
return _pages.Values.ToList();
|
||||
return Pages
|
||||
.Select(pair => LoadAdminPage(pair.Key))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public AdminPage HasPageFor(Type type) {
|
||||
return _pages
|
||||
.Where(p => p.Value.ModelType == type)
|
||||
.Select(p => p.Value)
|
||||
.SingleOrDefault();
|
||||
foreach (var (url, data) in Pages) {
|
||||
var innerType = data.PageType.GenericTypeArguments[0];
|
||||
if (innerType != type) continue;
|
||||
return LoadAdminPage(url);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal struct PageDataStore {
|
||||
public Type PageType { get; set; }
|
||||
public Type ContextType { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using HopFrame.Web.Admin.Attributes;
|
||||
using HopFrame.Web.Admin.Generators.Implementation;
|
||||
using HopFrame.Web.Admin.Providers;
|
||||
using HopFrame.Web.Admin.Providers.Implementation;
|
||||
@@ -8,22 +9,36 @@ namespace HopFrame.Web.Admin;
|
||||
|
||||
public static class ServiceCollectionExtensions {
|
||||
|
||||
private static IAdminPagesProvider _provider;
|
||||
|
||||
public static IServiceCollection AddAdminContext<TContext>(this IServiceCollection services) where TContext : AdminPagesContext {
|
||||
var provider = GetProvider();
|
||||
services.TryAddSingleton(provider);
|
||||
services.TryAddSingleton<IAdminPagesProvider, AdminPagesProvider>();
|
||||
|
||||
var generator = new AdminContextGenerator();
|
||||
var context = generator.CompileContext<TContext>();
|
||||
AdminContextGenerator.RegisterPages(context, provider, services);
|
||||
services.AddSingleton(context);
|
||||
services.AddSingleton(provider => {
|
||||
var generator = new AdminContextGenerator();
|
||||
var context = generator.CompileContext<TContext>(provider);
|
||||
return context;
|
||||
});
|
||||
|
||||
PreregisterPages<TContext>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
private static IAdminPagesProvider GetProvider() {
|
||||
return _provider ??= new AdminPagesProvider();
|
||||
private static void PreregisterPages<TContext>() where TContext : AdminPagesContext {
|
||||
var contextType = typeof(TContext);
|
||||
var props = contextType.GetProperties();
|
||||
|
||||
foreach (var property in props) {
|
||||
var url = property.Name;
|
||||
|
||||
if (property.GetCustomAttributes(false).Any(a => a is AdminPageUrlAttribute)) {
|
||||
var attribute = property.GetCustomAttributes(false)
|
||||
.Single(a => a is AdminPageUrlAttribute) as AdminPageUrlAttribute;
|
||||
|
||||
url = attribute?.Url;
|
||||
}
|
||||
|
||||
AdminPagesProvider.RegisterAdminPage<TContext>(url, property.PropertyType);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
@rendermode InteractiveServer
|
||||
|
||||
@using System.Collections
|
||||
@using System.Globalization
|
||||
@using BlazorStrap
|
||||
@using BlazorStrap.Shared.Components.Modal
|
||||
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
||||
@@ -144,7 +143,7 @@
|
||||
_currentPage = page;
|
||||
_entry = entryToEdit;
|
||||
_isEdit = entryToEdit is not null;
|
||||
_repository = Provider.GetService(_currentPage.RepositoryProvider) as IModelRepository;
|
||||
_repository = _currentPage.LoadModelRepository(Provider);
|
||||
|
||||
_entry ??= Activator.CreateInstance(_currentPage.ModelType);
|
||||
_context = new EditContext(_entry);
|
||||
@@ -247,8 +246,7 @@
|
||||
foreach (var value in _values) {
|
||||
if (value.Key.Unique) {
|
||||
if (value.Value == value.Key.GetValue(_entry)) continue;
|
||||
var repo = Provider.GetService(_currentPage.RepositoryProvider) as IModelRepository;
|
||||
var data = repo!.ReadAllO().GetAwaiter().GetResult();
|
||||
var data = _repository!.ReadAllO().GetAwaiter().GetResult();
|
||||
foreach (var entry in data) {
|
||||
var other = value.Key.GetValue(entry);
|
||||
if (!other.Equals(value.Value)) continue;
|
||||
@@ -295,7 +293,7 @@
|
||||
throw new ArgumentException($"'{property.Name}' cannot be a selector because a admin page for '{type.Name}' does not exist!");
|
||||
}
|
||||
|
||||
var repo = Provider.GetService(page.RepositoryProvider) as IModelRepository;
|
||||
var repo = page.LoadModelRepository(Provider);
|
||||
var objects = (await repo!.ReadAllO()).ToArray();
|
||||
_selectorValues[property] = objects;
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Text.RegularExpressions;
|
||||
using HopFrame.Database.Models;
|
||||
using HopFrame.Security;
|
||||
using HopFrame.Web.Admin;
|
||||
using HopFrame.Web.Admin.Attributes;
|
||||
using HopFrame.Web.Admin.Generators;
|
||||
using HopFrame.Web.Admin.Models;
|
||||
using HopFrame.Web.Repositories;
|
||||
@@ -10,7 +11,10 @@ namespace HopFrame.Web;
|
||||
|
||||
internal class HopAdminContext : AdminPagesContext {
|
||||
|
||||
[AdminPageUrl("users")]
|
||||
public AdminPage<User> Users { get; set; }
|
||||
|
||||
[AdminPageUrl("groups")]
|
||||
public AdminPage<PermissionGroup> Groups { get; set; }
|
||||
|
||||
public override void OnModelCreating(IAdminContextGenerator generator) {
|
||||
|
||||
@@ -106,6 +106,7 @@
|
||||
@inject ITokenContext Auth
|
||||
@inject IPermissionRepository Permissions
|
||||
@inject SweetAlertService Alerts
|
||||
@inject NavigationManager Navigator
|
||||
|
||||
@code {
|
||||
[Parameter]
|
||||
@@ -127,12 +128,17 @@
|
||||
protected override async Task OnInitializedAsync() {
|
||||
_pageData = Pages.LoadAdminPage(Url);
|
||||
|
||||
if (_pageData is null) {
|
||||
Navigator.NavigateTo("/administration", true);
|
||||
return;
|
||||
}
|
||||
|
||||
_currentSortProperty = _pageData.DefaultSortPropertyName;
|
||||
_currentSortDirection = _pageData.DefaultSortDirection;
|
||||
|
||||
if (_pageData.RepositoryProvider is null)
|
||||
throw new ArgumentException($"AdminPage '{_pageData.Title}' does not specify a model repository!'");
|
||||
_modelRepository = Provider.GetService(_pageData.RepositoryProvider) as IModelRepository;
|
||||
_modelRepository = _pageData.LoadModelRepository(Provider);
|
||||
|
||||
_hasEditPermission = _pageData.Permissions.Update is null || await Permissions.HasPermission(Auth.User, _pageData.Permissions.Update);
|
||||
_hasDeletePermission = _pageData.Permissions.Delete is null || await Permissions.HasPermission(Auth.User, _pageData.Permissions.Delete);
|
||||
|
||||
Reference in New Issue
Block a user