| | | 1 | | using System.Reflection; |
| | | 2 | | using Microsoft.AspNetCore.Authorization; |
| | | 3 | | using Microsoft.AspNetCore.Hosting; |
| | | 4 | | using Microsoft.AspNetCore.Mvc; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | using Microsoft.Extensions.Caching.Memory; |
| | | 7 | | using OzonDomains.Models.Authorization; |
| | | 8 | | using OzonRepositories.Context; |
| | | 9 | | |
| | | 10 | | namespace OzonOrdersWeb.Authorization.Discovery; |
| | | 11 | | |
| | | 12 | | public sealed class PageDiscoveryService : IPageDiscoveryService |
| | | 13 | | { |
| | | 14 | | private readonly ApplicationDbContext _db; |
| | | 15 | | private readonly IMemoryCache _cache; |
| | | 16 | | private readonly IWebHostEnvironment _env; |
| | | 17 | | |
| | 0 | 18 | | public PageDiscoveryService(ApplicationDbContext db, IMemoryCache cache, IWebHostEnvironment env) |
| | | 19 | | { |
| | 0 | 20 | | _db = db; |
| | 0 | 21 | | _cache = cache; |
| | 0 | 22 | | _env = env; |
| | 0 | 23 | | } |
| | | 24 | | |
| | | 25 | | public async Task<List<DiscoveredPage>> DiscoverAsync(CancellationToken ct = default) |
| | | 26 | | { |
| | 0 | 27 | | var existingCodes = (await _db.AppPages.AsNoTracking().Select(p => p.Code).ToListAsync(ct)) |
| | 0 | 28 | | .ToHashSet(StringComparer.OrdinalIgnoreCase); |
| | | 29 | | |
| | | 30 | | // Дедупликация по Code (перегрузки Create(GET)/Create(POST) и наследуемые экшены дают одинаковый код). |
| | 0 | 31 | | var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | 0 | 32 | | var result = new List<DiscoveredPage>(); |
| | | 33 | | |
| | 0 | 34 | | foreach (var type in GetControllerTypes()) |
| | | 35 | | { |
| | 0 | 36 | | if (type.GetCustomAttribute<AllowAnonymousAttribute>() is not null) continue; |
| | 0 | 37 | | if (type.GetCustomAttribute<ServiceEndpointAttribute>() is not null) continue; |
| | 0 | 38 | | var area = type.GetCustomAttribute<AreaAttribute>()?.RouteValue; |
| | 0 | 39 | | var controller = StripControllerSuffix(type.Name); |
| | | 40 | | |
| | 0 | 41 | | foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOn |
| | | 42 | | { |
| | 0 | 43 | | if (method.IsSpecialName) continue; |
| | 0 | 44 | | if (method.GetCustomAttribute<NonActionAttribute>() is not null) continue; |
| | 0 | 45 | | if (method.GetCustomAttribute<AllowAnonymousAttribute>() is not null) continue; |
| | | 46 | | // Служебные лукапы страницами не считаем — иначе на них требуются права, которых нет ни у одной роли. |
| | 0 | 47 | | if (method.GetCustomAttribute<ServiceEndpointAttribute>() is not null) continue; |
| | 0 | 48 | | if (!typeof(IActionResult).IsAssignableFrom(method.ReturnType) && |
| | 0 | 49 | | !typeof(Task<IActionResult>).IsAssignableFrom(method.ReturnType) && |
| | 0 | 50 | | !method.ReturnType.Name.Contains("Action") && |
| | 0 | 51 | | !method.ReturnType.Name.Contains("Task")) |
| | | 52 | | continue; |
| | | 53 | | |
| | 0 | 54 | | var action = GetActionName(method); |
| | 0 | 55 | | var code = BuildCode(area, controller, action); |
| | 0 | 56 | | if (!seen.Add(code)) continue; |
| | | 57 | | |
| | 0 | 58 | | var fromView = RazorViewTitleExtractor.TryGetTitleFromConventionalView( |
| | 0 | 59 | | _env.ContentRootPath, area, controller, action); |
| | 0 | 60 | | var displayName = !string.IsNullOrEmpty(fromView) |
| | 0 | 61 | | ? fromView! |
| | 0 | 62 | | : $"{controller} / {action}"; |
| | | 63 | | |
| | 0 | 64 | | result.Add(new DiscoveredPage |
| | 0 | 65 | | { |
| | 0 | 66 | | Code = code, |
| | 0 | 67 | | DisplayName = displayName, |
| | 0 | 68 | | Area = area, |
| | 0 | 69 | | Controller = controller, |
| | 0 | 70 | | Action = action, |
| | 0 | 71 | | ExistsInDb = existingCodes.Contains(code), |
| | 0 | 72 | | }); |
| | | 73 | | } |
| | | 74 | | } |
| | | 75 | | return result.OrderBy(r => r.ExistsInDb).ThenBy(r => r.Code).ToList(); |
| | 0 | 76 | | } |
| | | 77 | | |
| | | 78 | | public async Task<int> SyncAllAsync(CancellationToken ct = default) |
| | | 79 | | { |
| | 0 | 80 | | var found = await DiscoverAsync(ct); |
| | 0 | 81 | | var added = 0; |
| | | 82 | | |
| | | 83 | | // Коды страниц, которые должны отображаться в меню |
| | 0 | 84 | | var pimNavCodes = new HashSet<string>(Studio2PimNavMenuCatalog.AllPimNavPageCodes, StringComparer.OrdinalIgnoreC |
| | | 85 | | |
| | | 86 | | // Добавляем новые страницы и обновляем IsMenuItem для существующих |
| | 0 | 87 | | var existingPages = await _db.AppPages.ToListAsync(ct); |
| | | 88 | | var existingByCode = existingPages.ToDictionary(p => p.Code, StringComparer.OrdinalIgnoreCase); |
| | | 89 | | |
| | 0 | 90 | | foreach (var d in found) |
| | | 91 | | { |
| | 0 | 92 | | if (!d.ExistsInDb) |
| | | 93 | | { |
| | | 94 | | // Добавляем новую страницу |
| | 0 | 95 | | var isMenuItem = pimNavCodes.Contains(d.Code); |
| | 0 | 96 | | _db.AppPages.Add(new AppPage |
| | 0 | 97 | | { |
| | 0 | 98 | | Code = d.Code, |
| | 0 | 99 | | DisplayName = d.DisplayName, |
| | 0 | 100 | | Area = d.Area, |
| | 0 | 101 | | Controller = d.Controller, |
| | 0 | 102 | | Action = d.Action, |
| | 0 | 103 | | IsActive = true, |
| | 0 | 104 | | IsMenuItem = isMenuItem |
| | 0 | 105 | | }); |
| | 0 | 106 | | added++; |
| | | 107 | | } |
| | 0 | 108 | | else if (existingByCode.TryGetValue(d.Code, out var existing)) |
| | | 109 | | { |
| | | 110 | | // Обновляем IsMenuItem для существующей страницы если она в каталоге |
| | 0 | 111 | | var shouldBeMenuItem = pimNavCodes.Contains(d.Code); |
| | 0 | 112 | | if (existing.IsMenuItem != shouldBeMenuItem) |
| | | 113 | | { |
| | 0 | 114 | | existing.IsMenuItem = shouldBeMenuItem; |
| | 0 | 115 | | existing.UpdatedAt = DateTime.UtcNow; |
| | | 116 | | } |
| | | 117 | | } |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | if (added > 0 || existingPages.Any(p => p.UpdatedAt > DateTime.UtcNow.AddSeconds(-1))) |
| | | 121 | | { |
| | 0 | 122 | | await _db.SaveChangesAsync(ct); |
| | 0 | 123 | | AutoPageAuthorizationFilter.InvalidatePageRegistry(_cache); |
| | | 124 | | } |
| | 0 | 125 | | return added; |
| | 0 | 126 | | } |
| | | 127 | | |
| | | 128 | | public async Task<int> RefreshDisplayNamesFromViewsAsync(CancellationToken ct = default) |
| | | 129 | | { |
| | 0 | 130 | | var root = _env.ContentRootPath; |
| | 0 | 131 | | if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) return 0; |
| | | 132 | | |
| | 0 | 133 | | var pages = await _db.AppPages.ToListAsync(ct); |
| | 0 | 134 | | var updated = 0; |
| | 0 | 135 | | foreach (var p in pages) |
| | | 136 | | { |
| | 0 | 137 | | if (!RazorViewTitleExtractor.IsLegacyControllerActionLabel(p.Controller, p.Action, p.DisplayName)) continue; |
| | 0 | 138 | | var title = RazorViewTitleExtractor.TryGetTitleFromConventionalView(root, p.Area, p.Controller, p.Action); |
| | 0 | 139 | | if (string.IsNullOrEmpty(title)) continue; |
| | 0 | 140 | | p.DisplayName = title; |
| | 0 | 141 | | p.UpdatedAt = DateTime.UtcNow; |
| | 0 | 142 | | updated++; |
| | | 143 | | } |
| | 0 | 144 | | if (updated > 0) |
| | | 145 | | { |
| | 0 | 146 | | await _db.SaveChangesAsync(ct); |
| | 0 | 147 | | AutoPageAuthorizationFilter.InvalidatePageRegistry(_cache); |
| | | 148 | | } |
| | 0 | 149 | | return updated; |
| | 0 | 150 | | } |
| | | 151 | | |
| | | 152 | | private static IEnumerable<Type> GetControllerTypes() |
| | | 153 | | { |
| | 0 | 154 | | return AppDomain.CurrentDomain.GetAssemblies() |
| | 0 | 155 | | .Where(a => !a.IsDynamic) |
| | 0 | 156 | | .SelectMany(a => |
| | 0 | 157 | | { |
| | 0 | 158 | | try { return a.GetTypes(); } |
| | 0 | 159 | | catch { return Array.Empty<Type>(); } |
| | 0 | 160 | | }) |
| | 0 | 161 | | .Where(t => typeof(ControllerBase).IsAssignableFrom(t) && !t.IsAbstract); |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | private static string StripControllerSuffix(string name) |
| | 0 | 165 | | => name.EndsWith("Controller", StringComparison.Ordinal) ? name[..^"Controller".Length] : name; |
| | | 166 | | |
| | | 167 | | private static string GetActionName(MethodInfo method) |
| | | 168 | | { |
| | 0 | 169 | | var attr = method.GetCustomAttribute<ActionNameAttribute>(); |
| | 0 | 170 | | return attr?.Name ?? method.Name; |
| | | 171 | | } |
| | | 172 | | |
| | | 173 | | private static string BuildCode(string? area, string controller, string action) |
| | | 174 | | { |
| | 0 | 175 | | var a = string.IsNullOrWhiteSpace(area) ? string.Empty : area + "."; |
| | 0 | 176 | | return $"{a}{controller}.{action}"; |
| | | 177 | | } |
| | | 178 | | |
| | | 179 | | private static string Key(string? area, string controller, string action) |
| | 0 | 180 | | => $"{(area ?? string.Empty).ToLowerInvariant()}|{controller.ToLowerInvariant()}|{action.ToLowerInvariant()}"; |
| | | 181 | | } |