Repository navigation
Просмотр прав пользователя и настройка отображения сервера #20
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
842ada3
819833d
a15b019
5b88001
6f3ff03
cb17d5a
7525a89
e795395
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| using Ascon.Pilot.SDK; | ||
|
|
||
| namespace PilotLookUp.Model | ||
| { | ||
| public sealed class ServerIdentity | ||
| { | ||
| private readonly IClientInfo _clientInfo; | ||
| public ServerIdentity(IClientInfo clientInfo) => _clientInfo = clientInfo; | ||
|
|
||
| public string Name | ||
| { | ||
| get | ||
| { | ||
| var uri = _clientInfo?.ConnectionString; | ||
| return uri != null && uri.IsAbsoluteUri && !string.IsNullOrWhiteSpace(uri.Host) | ||
| ? uri.Host : "не определён"; | ||
| } | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| using Ascon.Pilot.SDK; | ||
| using PilotLookUp.Extensions; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace PilotLookUp.Model.Services | ||
| { | ||
| internal static class AccessExplanation | ||
| { | ||
| public static async Task<string> DescribeAsync(IObjectsRepository repository, IDataObject selected, int personId) | ||
| { | ||
| var id = selected.Id; | ||
| var effective = repository.GetCurrentAccess(id, personId); | ||
| var result = FormatAccess(effective, Environment.NewLine); | ||
| try | ||
| { | ||
| var person = repository.GetPerson(personId); | ||
| if (person.IsAdmin) | ||
| return result + "\n\nОснование — администратор базы Pilot."; | ||
|
|
||
| var current = selected; | ||
| var state = current.ObjectStateInfo?.State; | ||
| if (state == ObjectState.InRecycleBin || state == ObjectState.DeletedPermanently) | ||
| return result + "\n\nДоступ определён правилами Pilot для удалённого объекта."; | ||
| if (state == ObjectState.Frozen) | ||
| result += "\n\nОбъект заморожен. Pilot ограничивает действующие права."; | ||
|
|
||
| var units = new HashSet<int>(person.AllOrgUnits()); | ||
| var now = DateTime.UtcNow; | ||
| var typeId = current.Type.Id; | ||
| var records = new List<(IAccessRecord Record, Guid ObjectId, string ObjectName, bool Inherited)>(); | ||
| var visited = new HashSet<Guid>(); | ||
| var cursor = current; | ||
| var blockedBySecret = false; | ||
| string missing = null; | ||
| while (cursor != null && visited.Add(cursor.Id)) | ||
| { | ||
| bool inherited = cursor.Id != id; | ||
| foreach (var record in cursor.Access2 ?? Enumerable.Empty<IAccessRecord>()) | ||
| { | ||
| var access = record.Access; | ||
| if (!units.Contains(record.OrgUnitId) || access.ValidThrough < now || | ||
| (access.TypeIds != null && access.TypeIds.Length > 0 && !access.TypeIds.Contains(typeId))) | ||
| continue; | ||
| if (inherited && (!access.IsInheritable || | ||
| (blockedBySecret && access.Inheritance != AccessInheritance.InheritWholeSubtree))) | ||
| continue; | ||
| // Некоторые реализации возвращают уже унаследованные записи в Access2. | ||
| // Источник у них хранится в InheritanceSource. | ||
| var sourceId = record.Access.IsInherited && record.InheritanceSource != Guid.Empty | ||
| ? record.InheritanceSource : cursor.Id; | ||
| var sourceName = sourceId == cursor.Id ? cursor.DisplayName : null; | ||
| records.Add((record, sourceId, sourceName, sourceId != id)); | ||
| } | ||
|
|
||
| blockedBySecret |= cursor.IsSecret; | ||
| var parentId = cursor.ParentId; | ||
| if (parentId == Guid.Empty || parentId == cursor.Id) break; | ||
| if (visited.Contains(parentId)) | ||
| { | ||
| missing = "Обнаружен цикл в цепочке родителей."; | ||
| break; | ||
| } | ||
| IDataObject parent; | ||
| try | ||
| { | ||
| parent = await repository.GetObjectWithTimeout(parentId); | ||
| } | ||
| catch (Exception) | ||
| { | ||
| parent = null; | ||
| } | ||
| if (parent == null || parent.State != DataState.Loaded) | ||
| { | ||
| missing = $"Не удалось загрузить родительский объект {parentId}. Список оснований может быть неполным."; | ||
| break; | ||
| } | ||
| cursor = parent; | ||
| } | ||
|
|
||
| if (records.Count == 0) | ||
| return result + "\n\nВ доступных записях объекта нет действующих назначений для пользователя." | ||
| + (missing == null ? "" : "\n" + missing); | ||
|
|
||
| records = records.GroupBy(entry => new | ||
| { | ||
| entry.ObjectId, entry.Record.OrgUnitId, entry.Record.Access.Type, | ||
| entry.Record.Access.AccessLevel, entry.Record.Access.ValidThrough, | ||
| entry.Record.Access.Inheritance, | ||
| Types = string.Join(",", (entry.Record.Access.TypeIds ?? Array.Empty<int>()).OrderBy(x => x)) | ||
| }).Select(group => group.OrderByDescending(entry => entry.ObjectName != null).First()).ToList(); | ||
|
|
||
| var recipients = records.Select(r => r.Record.OrgUnitId).Distinct() | ||
| .ToDictionary(unitId => unitId, unitId => UnitName(repository, unitId)); | ||
| var rows = records.Select(entry => | ||
| { | ||
| var r = entry.Record; | ||
| var location = entry.Inherited | ||
| ? $"Унаследовано от «{entry.ObjectName ?? "имя недоступно"}» ({entry.ObjectId})" | ||
| : "На этом объекте"; | ||
| var kind = r.Access.Type == AccessType.Deny ? "Запрет" : "Разрешение"; | ||
| return $"{location}\n{recipients[r.OrgUnitId]} · {kind}: {FormatAccess(r.Access.AccessLevel, ", ")}"; | ||
| }); | ||
| if (missing != null) result += "\n\n" + missing; | ||
| return result + "\n\nНазначения прав\n\n" + string.Join("\n\n", rows); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| return result + "\n\nНе удалось прочитать основания доступа. " + ex.Message; | ||
| } | ||
| } | ||
|
|
||
| private static string UnitName(IObjectsRepository repository, int id) | ||
| { | ||
| var unit = repository.GetOrganisationUnit(id); | ||
| if (unit == null) return $"Оргединица #{id}"; | ||
| var kind = unit.Kind() switch | ||
| { | ||
| OrganizationUnitKind.Group => "Группа", | ||
| OrganizationUnitKind.Position => "Должность", | ||
| _ => "Подразделение" | ||
| }; | ||
| return $"{kind} «{unit.Title}» (#{id})"; | ||
| } | ||
|
|
||
| private static string FormatAccess(AccessLevel access, string separator) | ||
| { | ||
| if (access == AccessLevel.None) return "Нет прав на объект."; | ||
| var actions = new (AccessLevel Flag, string Title)[] | ||
| { | ||
| (AccessLevel.View, "Просмотр"), (AccessLevel.Create, "Создание"), | ||
| (AccessLevel.EditAttributes, "Изменение атрибутов"), (AccessLevel.EditFiles, "Изменение файлов"), | ||
| (AccessLevel.Delete, "Удаление"), (AccessLevel.Agreement, "Согласование"), | ||
|
Comment on lines
+134
to
+135
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Проверьте расширение на актуальном Pilot SDK. PR меняет Если требуется поддержка клиентов с SDK 26.15, это отдельная проверка совместимости. В 26.15 единый |
||
| (AccessLevel.Freeze, "Замораживание"), (AccessLevel.Share, "Делегирование прав") | ||
| }; | ||
| var labels = actions.Where(a => access.HasFlag(a.Flag)).Select(a => a.Title); | ||
| return string.Join(separator, labels); | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] Обновляйте объект перед чтением локальных назначений. Итоговые права запрашиваются при выборе сотрудника, а локальные назначения берутся из объекта, переданного при открытии окна. Если администратор отзовёт разрешение, пока окно открыто, итог может уже учитывать отзыв, а список всё ещё покажет старое разрешение. Загружайте актуальный объект перед построением списка оснований.