| | | 1 | | using System.Security.Claims; |
| | | 2 | | using Microsoft.AspNetCore.Http; |
| | | 3 | | using Microsoft.AspNetCore.Razor.TagHelpers; |
| | | 4 | | using OzonDomains.Models.Authorization.Enums; |
| | | 5 | | using Services.Authorization.Services; |
| | | 6 | | |
| | | 7 | | namespace OzonOrdersWeb.TagHelpers; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// <page-access page="Orders.Create" access="view|create|edit|delete|export">...</page-access> |
| | | 11 | | /// Скрывает элемент, если нет указанного доступа к странице. |
| | | 12 | | /// </summary> |
| | | 13 | | [HtmlTargetElement("page-access", Attributes = "page")] |
| | | 14 | | public sealed class PageAccessTagHelper : TagHelper |
| | | 15 | | { |
| | | 16 | | private readonly IPermissionService _permissions; |
| | | 17 | | private readonly IHttpContextAccessor _http; |
| | | 18 | | |
| | 0 | 19 | | public PageAccessTagHelper(IPermissionService permissions, IHttpContextAccessor http) |
| | | 20 | | { |
| | 0 | 21 | | _permissions = permissions; |
| | 0 | 22 | | _http = http; |
| | 0 | 23 | | } |
| | | 24 | | |
| | 0 | 25 | | [HtmlAttributeName("page")] public string Page { get; set; } = string.Empty; |
| | 0 | 26 | | [HtmlAttributeName("access")] public string Access { get; set; } = "view"; |
| | 0 | 27 | | [HtmlAttributeName("keep-tag")] public bool KeepTag { get; set; } |
| | | 28 | | |
| | | 29 | | public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) |
| | | 30 | | { |
| | 0 | 31 | | output.TagName = KeepTag ? "span" : null; |
| | | 32 | | |
| | 0 | 33 | | var userId = _http.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; |
| | 0 | 34 | | if (string.IsNullOrWhiteSpace(userId)) |
| | | 35 | | { |
| | 0 | 36 | | output.SuppressOutput(); |
| | 0 | 37 | | return; |
| | | 38 | | } |
| | | 39 | | |
| | 0 | 40 | | var accessType = Access.ToLowerInvariant() switch |
| | 0 | 41 | | { |
| | 0 | 42 | | "create" => AccessType.Create, |
| | 0 | 43 | | "edit" => AccessType.Edit, |
| | 0 | 44 | | "delete" => AccessType.Delete, |
| | 0 | 45 | | "export" => AccessType.Export, |
| | 0 | 46 | | _ => AccessType.View |
| | 0 | 47 | | }; |
| | | 48 | | |
| | 0 | 49 | | var allowed = await _permissions.HasPageAccessAsync(userId, Page, accessType); |
| | 0 | 50 | | if (!allowed) |
| | | 51 | | { |
| | 0 | 52 | | output.SuppressOutput(); |
| | | 53 | | } |
| | 0 | 54 | | } |
| | | 55 | | } |