| | | 1 | | using System.Text.RegularExpressions; |
| | | 2 | | using Services.Authorization.Dtos; |
| | | 3 | | |
| | | 4 | | namespace Services.Authorization.Services; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Парсит Dynamic LINQ выражения DataScope-ов и достаёт допустимые значения FK-полей. |
| | | 8 | | /// Поддерживает шаблонный формат «(Field == val)» / «(Field == val || Field == val2)» |
| | | 9 | | /// (то, что генерирует мастер создания набора из шаблона). |
| | | 10 | | /// </summary> |
| | | 11 | | public sealed class ScopeFilterValuesService : IScopeFilterValuesService |
| | | 12 | | { |
| | | 13 | | private readonly IPermissionService _permissions; |
| | | 14 | | |
| | 1 | 15 | | private static readonly Regex FieldEqRegex = new( |
| | 1 | 16 | | @"(?<field>[A-Za-z_][A-Za-z0-9_]*)\s*==\s*(?:""(?<sv>[^""]*)""|(?<nv>-?\d+))", |
| | 1 | 17 | | RegexOptions.Compiled); |
| | | 18 | | |
| | 29 | 19 | | public ScopeFilterValuesService(IPermissionService permissions) |
| | | 20 | | { |
| | 29 | 21 | | _permissions = permissions; |
| | 29 | 22 | | } |
| | | 23 | | |
| | | 24 | | public async Task<IReadOnlyDictionary<string, HashSet<string>>> GetAllowedValuesAsync( |
| | | 25 | | string userId, string entityName, CancellationToken ct = default) |
| | | 26 | | { |
| | 23 | 27 | | if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(entityName)) |
| | 6 | 28 | | return new Dictionary<string, HashSet<string>>(); |
| | | 29 | | |
| | 17 | 30 | | var bundle = await _permissions.GetUserPermissionsAsync(userId, ct); |
| | 18 | 31 | | if (bundle.IsSuperAdmin) return new Dictionary<string, HashSet<string>>(); |
| | | 32 | | |
| | 16 | 33 | | var exprs = bundle.DataScopes |
| | 16 | 34 | | .Where(s => string.Equals(s.EntityName, entityName, StringComparison.OrdinalIgnoreCase)) |
| | 15 | 35 | | .Select(s => s.FilterExpression) |
| | 15 | 36 | | .Where(s => !string.IsNullOrWhiteSpace(s)) |
| | 16 | 37 | | .ToList(); |
| | | 38 | | |
| | 20 | 39 | | if (exprs.Count == 0) return new Dictionary<string, HashSet<string>>(); |
| | | 40 | | |
| | 12 | 41 | | var result = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase); |
| | 50 | 42 | | foreach (var expr in exprs) |
| | | 43 | | { |
| | | 44 | | // ВАЖНО: разные scope-ы объединяются по OR. Но ограничения ПО ПОЛЮ — пересечение множеств |
| | | 45 | | // допустимых значений невозможно трактовать однозначно (ибо OR делается на уровне всей строки). |
| | | 46 | | // Поэтому считаем, что разные scope'ы перечисляют разрешённые значения одного поля аддитивно. |
| | 62 | 47 | | foreach (Match m in FieldEqRegex.Matches(expr)) |
| | | 48 | | { |
| | 18 | 49 | | var field = m.Groups["field"].Value; |
| | 18 | 50 | | var value = m.Groups["sv"].Success ? m.Groups["sv"].Value : m.Groups["nv"].Value; |
| | 18 | 51 | | if (!result.TryGetValue(field, out var set)) |
| | | 52 | | { |
| | 14 | 53 | | set = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | 14 | 54 | | result[field] = set; |
| | | 55 | | } |
| | 18 | 56 | | set.Add(value); |
| | | 57 | | } |
| | | 58 | | } |
| | | 59 | | |
| | 12 | 60 | | return result; |
| | 23 | 61 | | } |
| | | 62 | | |
| | | 63 | | public async Task<UserPermissionsBundle?> GetBundleIfRestrictedAsync(string userId, CancellationToken ct = default) |
| | | 64 | | { |
| | 10 | 65 | | if (string.IsNullOrWhiteSpace(userId)) return null; |
| | 4 | 66 | | var bundle = await _permissions.GetUserPermissionsAsync(userId, ct); |
| | 5 | 67 | | if (bundle.IsSuperAdmin) return null; |
| | 5 | 68 | | if (bundle.DataScopes.Count == 0) return null; |
| | 1 | 69 | | return bundle; |
| | 7 | 70 | | } |
| | | 71 | | } |