основное сделано
This commit is contained in:
@@ -4,6 +4,7 @@ using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Tnsu.ApprovalRoute.Infrastructure.Persistence;
|
||||
using Tnsu.ApprovalRoute.Infrastructure.SharePoint;
|
||||
using Tnsu.ApprovalRoute.Infrastructure.TnsuPortal;
|
||||
|
||||
namespace Tnsu.ApprovalRoute.Infrastructure;
|
||||
@@ -20,6 +21,12 @@ public static class InfrastructureServiceCollectionExtensions
|
||||
.UseSnakeCaseNamingConvention());
|
||||
services.AddAsyncInitializer<DatabaseMigrationInitializer>();
|
||||
|
||||
services.Configure<SharePointOptions>(configuration.GetSection("SharePoint"));
|
||||
// Провайдер сертификата — синглтон: разобранный .pfx кешируется на всё
|
||||
// время жизни процесса (см. DbCertificateProvider).
|
||||
services.AddSingleton<ICertificateProvider, DbCertificateProvider>();
|
||||
services.AddHttpClient<ISharePointClient, SharePointClient>();
|
||||
|
||||
services.Configure<TnsuPortalOptions>(configuration.GetSection("TnsuPortal"));
|
||||
services.AddHttpClient<TnsuPortalTokenProvider>();
|
||||
services.AddHttpClient<ITnsuPortalClient, HttpTnsuPortalClient>((sp, client) =>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Tnsu.ApprovalRoute.Domain.Entities;
|
||||
using Tnsu.ApprovalRoute.Infrastructure.Persistence.Entities;
|
||||
|
||||
namespace Tnsu.ApprovalRoute.Infrastructure.Persistence;
|
||||
|
||||
@@ -8,9 +9,20 @@ public class ApprovalRouteDbContext(DbContextOptions<ApprovalRouteDbContext> opt
|
||||
public DbSet<RequestType> RequestTypes => Set<RequestType>();
|
||||
public DbSet<TemplateRoute> TemplateRoutes => Set<TemplateRoute>();
|
||||
public DbSet<TemplateRouteStep> TemplateRouteSteps => Set<TemplateRouteStep>();
|
||||
public DbSet<AppSetting> Settings => Set<AppSetting>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<AppSetting>(e =>
|
||||
{
|
||||
// Имя таблицы задано явно: соглашение по именам сделало бы из
|
||||
// AppSetting «app_settings», а таблица должна называться так же, как
|
||||
// в api-tnsu-portal, — settings.
|
||||
e.ToTable("settings");
|
||||
e.HasKey(x => x.OptionName);
|
||||
e.Property(x => x.OptionName).HasMaxLength(128);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<RequestType>(e =>
|
||||
{
|
||||
e.HasKey(x => x.Id);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace Tnsu.ApprovalRoute.Infrastructure.Persistence.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Настройка, которую нельзя держать в appsettings — сейчас это единственный
|
||||
/// случай: PFX-сертификат для похода в SharePoint (option_name = 'AzurePfx').
|
||||
///
|
||||
/// Живёт в Infrastructure, а не в Domain, намеренно: к предметной области
|
||||
/// маршрутов согласования отношения не имеет, это способ хранения секрета.
|
||||
///
|
||||
/// Форма таблицы повторяет settings в api-tnsu-portal (option_name + file_data),
|
||||
/// чтобы копию сертификата можно было перенести запросом один в один, без
|
||||
/// преобразований.
|
||||
/// </summary>
|
||||
public class AppSetting
|
||||
{
|
||||
/// <summary>Ключ настройки. Для сертификата SharePoint — 'AzurePfx'.</summary>
|
||||
public string OptionName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Двоичное содержимое (для 'AzurePfx' — сам .pfx как есть).</summary>
|
||||
public byte[]? FileData { get; set; }
|
||||
|
||||
/// <summary>Текстовое значение — для настроек, которым не нужен файл.</summary>
|
||||
public string? Value { get; set; }
|
||||
}
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using Tnsu.ApprovalRoute.Infrastructure.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Tnsu.ApprovalRoute.Infrastructure.Persistence.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApprovalRouteDbContext))]
|
||||
[Migration("20260812091325_AddSlaSettings")]
|
||||
partial class AddSlaSettings
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.10")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Domain.Entities.RequestType", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("id");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool?>("AskOverdueReason")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("ask_overdue_reason");
|
||||
|
||||
b.Property<string>("ListId")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)")
|
||||
.HasColumnName("list_id");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<string>("PageUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)")
|
||||
.HasColumnName("page_url");
|
||||
|
||||
b.Property<string>("Section")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("section");
|
||||
|
||||
b.Property<string>("SiteUrl")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)")
|
||||
.HasColumnName("site_url");
|
||||
|
||||
b.Property<int?>("SlaHours")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sla_hours");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_request_types");
|
||||
|
||||
b.ToTable("request_types", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Domain.Entities.TemplateRoute", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("id");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("ByProject")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("by_project");
|
||||
|
||||
b.Property<Guid?>("CompanyId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("company_id");
|
||||
|
||||
b.Property<Guid?>("DepartmentId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("department_id");
|
||||
|
||||
b.Property<int>("RequestTypeId")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("request_type_id");
|
||||
|
||||
b.Property<bool>("RequiresControl")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("requires_control");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_template_routes");
|
||||
|
||||
b.HasIndex("RequestTypeId", "DepartmentId", "CompanyId", "ByProject")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_template_routes_request_type_id_department_id_company_id_by");
|
||||
|
||||
b.ToTable("template_routes", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Domain.Entities.TemplateRouteStep", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("id");
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("AllowReassignToOtherApprovers")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("allow_reassign_to_other_approvers");
|
||||
|
||||
b.Property<bool?>("AskOverdueReason")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("ask_overdue_reason");
|
||||
|
||||
b.Property<string>("ExecutorEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("executor_email");
|
||||
|
||||
b.Property<string>("FieldName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)")
|
||||
.HasColumnName("field_name");
|
||||
|
||||
b.Property<string>("HeadType")
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("head_type");
|
||||
|
||||
b.Property<string>("Operation")
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("operation");
|
||||
|
||||
b.Property<int>("OrderNo")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("order_no");
|
||||
|
||||
b.Property<string>("Position")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)")
|
||||
.HasColumnName("position");
|
||||
|
||||
b.Property<string>("ProjectRole")
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("project_role");
|
||||
|
||||
b.Property<int>("RouteId")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("route_id");
|
||||
|
||||
b.Property<int?>("SlaHours")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sla_hours");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("status");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("value");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_template_route_steps");
|
||||
|
||||
b.HasIndex("RouteId", "OrderNo")
|
||||
.HasDatabaseName("ix_template_route_steps_route_id_order_no");
|
||||
|
||||
b.ToTable("template_route_steps", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Infrastructure.Persistence.Entities.AppSetting", b =>
|
||||
{
|
||||
b.Property<string>("OptionName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)")
|
||||
.HasColumnName("option_name");
|
||||
|
||||
b.Property<byte[]>("FileData")
|
||||
.HasColumnType("bytea")
|
||||
.HasColumnName("file_data");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("value");
|
||||
|
||||
b.HasKey("OptionName")
|
||||
.HasName("pk_settings");
|
||||
|
||||
b.ToTable("settings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Domain.Entities.TemplateRoute", b =>
|
||||
{
|
||||
b.HasOne("Tnsu.ApprovalRoute.Domain.Entities.RequestType", "RequestType")
|
||||
.WithMany("Routes")
|
||||
.HasForeignKey("RequestTypeId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_template_routes_request_types_request_type_id");
|
||||
|
||||
b.Navigation("RequestType");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Domain.Entities.TemplateRouteStep", b =>
|
||||
{
|
||||
b.HasOne("Tnsu.ApprovalRoute.Domain.Entities.TemplateRoute", "Route")
|
||||
.WithMany("Steps")
|
||||
.HasForeignKey("RouteId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired()
|
||||
.HasConstraintName("fk_template_route_steps_template_routes_route_id");
|
||||
|
||||
b.Navigation("Route");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Domain.Entities.RequestType", b =>
|
||||
{
|
||||
b.Navigation("Routes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Domain.Entities.TemplateRoute", b =>
|
||||
{
|
||||
b.Navigation("Steps");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Tnsu.ApprovalRoute.Infrastructure.Persistence.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddSlaSettings : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "ask_overdue_reason",
|
||||
table: "template_route_steps",
|
||||
type: "boolean",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "sla_hours",
|
||||
table: "template_route_steps",
|
||||
type: "integer",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "ask_overdue_reason",
|
||||
table: "request_types",
|
||||
type: "boolean",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "sla_hours",
|
||||
table: "request_types",
|
||||
type: "integer",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "settings",
|
||||
columns: table => new
|
||||
{
|
||||
option_name = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
|
||||
file_data = table.Column<byte[]>(type: "bytea", nullable: true),
|
||||
value = table.Column<string>(type: "text", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("pk_settings", x => x.option_name);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "settings");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ask_overdue_reason",
|
||||
table: "template_route_steps");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "sla_hours",
|
||||
table: "template_route_steps");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ask_overdue_reason",
|
||||
table: "request_types");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "sla_hours",
|
||||
table: "request_types");
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
@@ -31,6 +31,10 @@ namespace Tnsu.ApprovalRoute.Infrastructure.Persistence.Migrations
|
||||
|
||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool?>("AskOverdueReason")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("ask_overdue_reason");
|
||||
|
||||
b.Property<string>("ListId")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)")
|
||||
@@ -59,6 +63,10 @@ namespace Tnsu.ApprovalRoute.Infrastructure.Persistence.Migrations
|
||||
.HasColumnType("character varying(512)")
|
||||
.HasColumnName("site_url");
|
||||
|
||||
b.Property<int?>("SlaHours")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sla_hours");
|
||||
|
||||
b.HasKey("Id")
|
||||
.HasName("pk_request_types");
|
||||
|
||||
@@ -117,6 +125,10 @@ namespace Tnsu.ApprovalRoute.Infrastructure.Persistence.Migrations
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("allow_reassign_to_other_approvers");
|
||||
|
||||
b.Property<bool?>("AskOverdueReason")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("ask_overdue_reason");
|
||||
|
||||
b.Property<string>("ExecutorEmail")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
@@ -155,6 +167,10 @@ namespace Tnsu.ApprovalRoute.Infrastructure.Persistence.Migrations
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("route_id");
|
||||
|
||||
b.Property<int?>("SlaHours")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sla_hours");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
@@ -175,6 +191,27 @@ namespace Tnsu.ApprovalRoute.Infrastructure.Persistence.Migrations
|
||||
b.ToTable("template_route_steps", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Infrastructure.Persistence.Entities.AppSetting", b =>
|
||||
{
|
||||
b.Property<string>("OptionName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)")
|
||||
.HasColumnName("option_name");
|
||||
|
||||
b.Property<byte[]>("FileData")
|
||||
.HasColumnType("bytea")
|
||||
.HasColumnName("file_data");
|
||||
|
||||
b.Property<string>("Value")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("value");
|
||||
|
||||
b.HasKey("OptionName")
|
||||
.HasName("pk_settings");
|
||||
|
||||
b.ToTable("settings", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Tnsu.ApprovalRoute.Domain.Entities.TemplateRoute", b =>
|
||||
{
|
||||
b.HasOne("Tnsu.ApprovalRoute.Domain.Entities.RequestType", "RequestType")
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Tnsu.ApprovalRoute.Infrastructure.Persistence;
|
||||
|
||||
namespace Tnsu.ApprovalRoute.Infrastructure.SharePoint;
|
||||
|
||||
public interface ICertificateProvider
|
||||
{
|
||||
Task<X509Certificate2> GetCertificateAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Сертификат для входа в SharePoint — из таблицы settings (option_name задаётся
|
||||
/// в SharePointOptions.CertificateSettingName, по умолчанию 'AzurePfx').
|
||||
///
|
||||
/// Синглтон с кешем: разбор .pfx стоит заметно дороже запроса к базе, а сам
|
||||
/// сертификат меняется раз в год. Блокировка — чтобы параллельные запросы не
|
||||
/// разбирали его одновременно при холодном старте.
|
||||
///
|
||||
/// Собственная таблица, а не общая с api-tnsu-portal, — осознанный выбор: базы
|
||||
/// у сервисов разные и связывать их не хотим. Цена — копию сертификата придётся
|
||||
/// обновлять в двух местах.
|
||||
/// </summary>
|
||||
public sealed class DbCertificateProvider(
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IOptions<SharePointOptions> options) : ICertificateProvider
|
||||
{
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
private X509Certificate2? _cached;
|
||||
|
||||
public async Task<X509Certificate2> GetCertificateAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_cached is not null) return _cached;
|
||||
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (_cached is not null) return _cached;
|
||||
|
||||
var settingName = options.Value.CertificateSettingName;
|
||||
|
||||
// Своя область: провайдер — синглтон, а DbContext зарегистрирован
|
||||
// как scoped, напрямую внедрять его сюда нельзя.
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApprovalRouteDbContext>();
|
||||
|
||||
var pfx = await db.Settings.AsNoTracking()
|
||||
.Where(x => x.OptionName == settingName)
|
||||
.Select(x => x.FileData)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (pfx is null || pfx.Length == 0)
|
||||
throw new InvalidOperationException(
|
||||
$"Сертификат не найден: в таблице settings нет записи «{settingName}» с непустым file_data.");
|
||||
|
||||
_cached = X509CertificateLoader.LoadPkcs12(
|
||||
pfx,
|
||||
options.Value.CertificatePassword,
|
||||
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.EphemeralKeySet);
|
||||
|
||||
return _cached;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using Azure.Core;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Tnsu.ApprovalRoute.Infrastructure.SharePoint;
|
||||
|
||||
public interface ISharePointClient
|
||||
{
|
||||
/// <summary>Заголовок списка по его серверному относительному URL (см. RequestType.ListId).</summary>
|
||||
Task<string?> GetListTitleAsync(string siteUrl, string listServerRelativeUrl, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Серверный относительный URL списка, найденного по заголовку — нужен, чтобы
|
||||
/// построить условие Path в KQL-запросе (см. SearchListItemIdsAsync).
|
||||
/// </summary>
|
||||
Task<string?> GetListServerRelativeUrlAsync(string siteUrl, string listTitle, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Элементы списка данных, найденного по серверному относительному URL.</summary>
|
||||
Task<IReadOnlyList<JsonElement>> GetItemsByListUrlAsync(
|
||||
string siteUrl, string listServerRelativeUrl, string odataQuery, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Элементы списка, найденного по заголовку (списки согласования ищутся именно так).</summary>
|
||||
Task<IReadOnlyList<JsonElement>> GetItemsByListTitleAsync(
|
||||
string siteUrl, string listTitle, string odataQuery, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Id элементов, найденных Search'ем по KQL-запросу. Именно так, а не $filter,
|
||||
/// сужается набор строк списка согласования по статусу (Choice-колонка) —
|
||||
/// $filter по ней в SharePoint REST ненадёжен: см. подробный разбор в
|
||||
/// request-portal/myRequests.service.ts (MP_STATUS/ApprovalStatusOWSCHCS,
|
||||
/// тот же список, тот же managed property, подтверждено рабочим). Значения
|
||||
/// колонок не возвращает — только Id, дочитывать поля нужно отдельным REST-запросом.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<int>> SearchListItemIdsAsync(
|
||||
string siteUrl, string queryText, int rowLimit, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Доступ к SharePoint REST от имени приложения (сертификат из таблицы settings).
|
||||
///
|
||||
/// Сырой HttpClient, а не PnP.Core/CSOM — по образцу api-tnsu-portal и потому,
|
||||
/// что нужно всего одно действие: прочитать элементы двух списков. Тянуть ради
|
||||
/// этого клиентскую библиотеку со своей объектной моделью незачем.
|
||||
///
|
||||
/// Клиент намеренно «глупый»: отдаёт сырой JSON и ничего не знает ни про SLA, ни
|
||||
/// про строки маршрута — вся логика напоминаний живёт в Application.
|
||||
/// </summary>
|
||||
public sealed class SharePointClient(
|
||||
HttpClient httpClient,
|
||||
ICertificateProvider certificateProvider,
|
||||
IOptions<SharePointOptions> options) : ISharePointClient
|
||||
{
|
||||
// Токен запрашивается на КОНКРЕТНЫЙ хост SharePoint, поэтому и кеш по хосту:
|
||||
// списки разных типов заявок могут жить на разных сайтах.
|
||||
private readonly ConcurrentDictionary<string, AccessToken> _tokens = new(StringComparer.OrdinalIgnoreCase);
|
||||
private ClientCertificateCredential? _credential;
|
||||
private readonly SemaphoreSlim _credentialLock = new(1, 1);
|
||||
|
||||
public async Task<string?> GetListTitleAsync(
|
||||
string siteUrl, string listServerRelativeUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
var url = $"{siteUrl.TrimEnd('/')}/_api/web/getList('{Escape(listServerRelativeUrl)}')?$select=Title";
|
||||
var json = await GetAsync(siteUrl, url, cancellationToken);
|
||||
return json.TryGetProperty("Title", out var title) ? title.GetString() : null;
|
||||
}
|
||||
|
||||
public async Task<string?> GetListServerRelativeUrlAsync(
|
||||
string siteUrl, string listTitle, CancellationToken cancellationToken)
|
||||
{
|
||||
var url = $"{siteUrl.TrimEnd('/')}/_api/web/lists/getByTitle('{Escape(listTitle)}')" +
|
||||
"?$select=RootFolder/ServerRelativeUrl&$expand=RootFolder";
|
||||
var json = await GetAsync(siteUrl, url, cancellationToken);
|
||||
|
||||
return ParseServerRelativeUrl(json);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<int>> SearchListItemIdsAsync(
|
||||
string siteUrl, string queryText, int rowLimit, CancellationToken cancellationToken)
|
||||
{
|
||||
var url = $"{siteUrl.TrimEnd('/')}/_api/search/query" +
|
||||
$"?querytext='{Uri.EscapeDataString(queryText)}'" +
|
||||
"&selectproperties='ListItemID'" +
|
||||
$"&rowlimit={rowLimit}" +
|
||||
"&trimduplicates=false";
|
||||
var json = await GetAsync(siteUrl, url, cancellationToken);
|
||||
|
||||
return ParseSearchListItemIds(json);
|
||||
}
|
||||
|
||||
// Разбор вынесен в чистые статические функции — они не ходят в сеть и не
|
||||
// требуют токена, поэтому их (в отличие от остального клиента) можно
|
||||
// проверить тестом без живого SharePoint. Это самая непроверенная часть
|
||||
// клиента: форма ответа Search REST зафиксирована документацией, но без
|
||||
// реального тенанта убедиться в точном соответствии нельзя.
|
||||
internal static string? ParseServerRelativeUrl(JsonElement json) =>
|
||||
json.TryGetProperty("RootFolder", out var rootFolder) &&
|
||||
rootFolder.TryGetProperty("ServerRelativeUrl", out var relUrl)
|
||||
? relUrl.GetString()
|
||||
: null;
|
||||
|
||||
internal static IReadOnlyList<int> ParseSearchListItemIds(JsonElement json)
|
||||
{
|
||||
// Путь до строк результата — фиксированная форма ответа Search REST,
|
||||
// не зависит от запроса. С odata=nometadata Cells приходит уже "голым"
|
||||
// массивом (без обёртки .results) — но на случай, если сервер всё равно
|
||||
// завернёт его (разные версии API отвечали по-разному на практике в этом
|
||||
// проекте, см. комментарии в request-portal про managed properties),
|
||||
// читаем и то, и то (см. Unwrap).
|
||||
if (!json.TryGetProperty("PrimaryQueryResult", out var primary)) return [];
|
||||
if (!primary.TryGetProperty("RelevantResults", out var relevant)) return [];
|
||||
if (!relevant.TryGetProperty("Table", out var table)) return [];
|
||||
if (!table.TryGetProperty("Rows", out var rowsElement)) return [];
|
||||
|
||||
var ids = new List<int>();
|
||||
|
||||
foreach (var row in Unwrap(rowsElement))
|
||||
{
|
||||
if (!row.TryGetProperty("Cells", out var cellsElement)) continue;
|
||||
|
||||
foreach (var cell in Unwrap(cellsElement))
|
||||
{
|
||||
if (!cell.TryGetProperty("Key", out var key) || key.GetString() != "ListItemID") continue;
|
||||
if (!cell.TryGetProperty("Value", out var value)) continue;
|
||||
if (int.TryParse(value.GetString(), out var id)) ids.Add(id);
|
||||
}
|
||||
}
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
// odata=nometadata отдаёт коллекции внутри Search-ответа "голым" массивом;
|
||||
// без этого заголовка (или в старых версиях API) — обёрткой { results: [...] }.
|
||||
private static IEnumerable<JsonElement> Unwrap(JsonElement element)
|
||||
{
|
||||
if (element.ValueKind == JsonValueKind.Array) return element.EnumerateArray();
|
||||
|
||||
return element.TryGetProperty("results", out var results) && results.ValueKind == JsonValueKind.Array
|
||||
? results.EnumerateArray()
|
||||
: [];
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<JsonElement>> GetItemsByListUrlAsync(
|
||||
string siteUrl, string listServerRelativeUrl, string odataQuery, CancellationToken cancellationToken) =>
|
||||
GetItemsAsync(
|
||||
siteUrl,
|
||||
$"{siteUrl.TrimEnd('/')}/_api/web/getList('{Escape(listServerRelativeUrl)}')/items?{odataQuery}",
|
||||
cancellationToken);
|
||||
|
||||
public Task<IReadOnlyList<JsonElement>> GetItemsByListTitleAsync(
|
||||
string siteUrl, string listTitle, string odataQuery, CancellationToken cancellationToken) =>
|
||||
GetItemsAsync(
|
||||
siteUrl,
|
||||
$"{siteUrl.TrimEnd('/')}/_api/web/lists/getByTitle('{Escape(listTitle)}')/items?{odataQuery}",
|
||||
cancellationToken);
|
||||
|
||||
private async Task<IReadOnlyList<JsonElement>> GetItemsAsync(
|
||||
string siteUrl, string url, CancellationToken cancellationToken)
|
||||
{
|
||||
var json = await GetAsync(siteUrl, url, cancellationToken);
|
||||
|
||||
// odata=nometadata отдаёт элементы в "value"; на всякий случай терпим и
|
||||
// «голый» массив, если заголовок Accept вдруг не подействует.
|
||||
if (json.ValueKind == JsonValueKind.Array)
|
||||
return json.EnumerateArray().ToList();
|
||||
|
||||
return json.TryGetProperty("value", out var value) && value.ValueKind == JsonValueKind.Array
|
||||
? value.EnumerateArray().ToList()
|
||||
: [];
|
||||
}
|
||||
|
||||
private async Task<JsonElement> GetAsync(string siteUrl, string url, CancellationToken cancellationToken)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue(
|
||||
"Bearer", await GetTokenAsync(siteUrl, cancellationToken));
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")
|
||||
{
|
||||
Parameters = { new NameValueHeaderValue("odata", "nometadata") }
|
||||
});
|
||||
|
||||
using var response = await httpClient.SendAsync(request, cancellationToken);
|
||||
var body = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new InvalidOperationException(
|
||||
$"SharePoint ответил {(int)response.StatusCode} на {url}: {body}");
|
||||
|
||||
using var document = JsonDocument.Parse(body);
|
||||
return document.RootElement.Clone();
|
||||
}
|
||||
|
||||
private async Task<string> GetTokenAsync(string siteUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
var host = new Uri(siteUrl).Host;
|
||||
|
||||
// Токен живой ещё пять минут — переиспользуем. Запас нужен, чтобы токен
|
||||
// не истёк между проверкой и приходом запроса в SharePoint.
|
||||
if (_tokens.TryGetValue(host, out var cached) && cached.ExpiresOn > DateTimeOffset.UtcNow.AddMinutes(5))
|
||||
return cached.Token;
|
||||
|
||||
var credential = await GetCredentialAsync(cancellationToken);
|
||||
var token = await credential.GetTokenAsync(
|
||||
new TokenRequestContext([$"https://{host}/.default"]), cancellationToken);
|
||||
|
||||
_tokens[host] = token;
|
||||
return token.Token;
|
||||
}
|
||||
|
||||
private async Task<ClientCertificateCredential> GetCredentialAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_credential is not null) return _credential;
|
||||
|
||||
await _credentialLock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (_credential is not null) return _credential;
|
||||
|
||||
var certificate = await certificateProvider.GetCertificateAsync(cancellationToken);
|
||||
_credential = new ClientCertificateCredential(
|
||||
options.Value.TenantId, options.Value.ClientId, certificate);
|
||||
|
||||
return _credential;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_credentialLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
// Одинарная кавычка в OData-литерале экранируется её удвоением. Заголовки
|
||||
// списков содержат тире и кириллицу, но кавычка теоретически возможна —
|
||||
// без экранирования она сломала бы запрос.
|
||||
private static string Escape(string value) => value.Replace("'", "''");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace Tnsu.ApprovalRoute.Infrastructure.SharePoint;
|
||||
|
||||
public sealed class SharePointOptions
|
||||
{
|
||||
/// <summary>Тенант Entra — тот же, что у остальной авторизации.</summary>
|
||||
public string TenantId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Приложение, от имени которого идём в SharePoint. Ему нужны разрешения
|
||||
/// уровня приложения на чтение списков, выданные администратором тенанта.
|
||||
/// </summary>
|
||||
public string ClientId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Ключ в таблице settings, под которым лежит .pfx (option_name).</summary>
|
||||
public string CertificateSettingName { get; set; } = "AzurePfx";
|
||||
|
||||
/// <summary>
|
||||
/// Пароль от .pfx. Намеренно берётся из конфигурации, а не зашивается в код:
|
||||
/// в api-tnsu-portal он захардкожен в PostgresCertificateProvider, и повторять
|
||||
/// это здесь не стоит — пароль от сертификата в исходниках не место.
|
||||
/// </summary>
|
||||
public string CertificatePassword { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -3,6 +3,15 @@
|
||||
<ProjectReference Include="..\Tnsu.ApprovalRoute.Domain\Tnsu.ApprovalRoute.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- Даёт тестам доступ к internal-функциям чистого разбора JSON в SharePointClient
|
||||
(SharePointClientParsingTests) — сам клиент не потестировать без живого
|
||||
тенанта (аутентификация по сертификату ходит в Azure AD), а разбор ответа
|
||||
можно и нужно проверять без сети. -->
|
||||
<InternalsVisibleTo Include="Tnsu.ApprovalRoute.IntegrationTests" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- ClientCertificateCredential — вход в SharePoint по сертификату (см. SharePoint/). -->
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="EFCore.NamingConventions" />
|
||||
<PackageReference Include="Extensions.Hosting.AsyncInitialization" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" />
|
||||
|
||||
Reference in New Issue
Block a user