| | | 1 | | using System.Security.Claims; |
| | | 2 | | using Microsoft.AspNetCore.Http; |
| | | 3 | | using Microsoft.AspNetCore.Mvc.Rendering; |
| | | 4 | | using Microsoft.AspNetCore.Mvc.ViewFeatures; |
| | | 5 | | using Microsoft.AspNetCore.Razor.TagHelpers; |
| | | 6 | | using OzonDomains.Models.Authorization.Enums; |
| | | 7 | | using Services.Authorization.Services; |
| | | 8 | | |
| | | 9 | | namespace OzonOrdersWeb.TagHelpers; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// <field-access entity="Order" field="Price" access="read|write">...</field-access> |
| | | 13 | | /// Скрывает содержимое если у текущего пользователя нет указанного доступа к полю. |
| | | 14 | | /// </summary> |
| | | 15 | | [HtmlTargetElement("field-access", Attributes = "entity,field,access")] |
| | | 16 | | public sealed class FieldAccessTagHelper : TagHelper |
| | | 17 | | { |
| | | 18 | | private readonly IPermissionService _permissions; |
| | | 19 | | private readonly IHttpContextAccessor _http; |
| | | 20 | | |
| | 0 | 21 | | public FieldAccessTagHelper(IPermissionService permissions, IHttpContextAccessor http) |
| | | 22 | | { |
| | 0 | 23 | | _permissions = permissions; |
| | 0 | 24 | | _http = http; |
| | 0 | 25 | | } |
| | | 26 | | |
| | 0 | 27 | | [HtmlAttributeName("entity")] public string Entity { get; set; } = string.Empty; |
| | 0 | 28 | | [HtmlAttributeName("field")] public string Field { get; set; } = string.Empty; |
| | | 29 | | |
| | | 30 | | /// <summary>"read" (default) или "write".</summary> |
| | 0 | 31 | | [HtmlAttributeName("access")] public string Access { get; set; } = "read"; |
| | | 32 | | |
| | | 33 | | /// <summary>Если true — при отсутствии прав рендерится обёртка без контента (false — убирается целиком).</summary> |
| | 0 | 34 | | [HtmlAttributeName("keep-tag")] public bool KeepTag { get; set; } |
| | | 35 | | |
| | | 36 | | public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) |
| | | 37 | | { |
| | 0 | 38 | | output.TagName = KeepTag ? "span" : null; |
| | | 39 | | |
| | 0 | 40 | | var userId = _http.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; |
| | 0 | 41 | | if (string.IsNullOrWhiteSpace(userId)) |
| | | 42 | | { |
| | 0 | 43 | | output.SuppressOutput(); |
| | 0 | 44 | | return; |
| | | 45 | | } |
| | | 46 | | |
| | 0 | 47 | | var accessType = string.Equals(Access, "write", StringComparison.OrdinalIgnoreCase) |
| | 0 | 48 | | ? AccessType.Write |
| | 0 | 49 | | : AccessType.Read; |
| | | 50 | | |
| | 0 | 51 | | var allowed = await _permissions.HasFieldAccessAsync(userId, Entity, Field, accessType); |
| | 0 | 52 | | if (!allowed) |
| | | 53 | | { |
| | 0 | 54 | | output.SuppressOutput(); |
| | | 55 | | } |
| | 0 | 56 | | } |
| | | 57 | | } |