Переделал на MVC и добавил swagger doc
Build UniVerse plugin / Build library (push) Failing after 14m54s
Build UniVerse plugin / Build library (push) Failing after 14m54s
This commit is contained in:
@@ -0,0 +1,53 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace SfeduSchedule.Plugin.UniVerse.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("plugins/universe")]
|
||||||
|
public sealed class UniverseController(IUniverseUserLookupService lookupService) : ControllerBase
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Получить Sub ID пользователя по полному имени.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fullname">Полное имя пользователя для поиска в Modeus.</param>
|
||||||
|
/// <param name="cancellationToken">Токен отмены запроса.</param>
|
||||||
|
/// <returns>UniVerse Sub ID пользователя в формате plain text.</returns>
|
||||||
|
/// <response code="200">Пользователь найден, возвращается его UniVerse Sub ID.</response>
|
||||||
|
/// <response code="400">Не передан обязательный query-параметр fullname.</response>
|
||||||
|
/// <response code="401">Не передан или некорректен API-ключ.</response>
|
||||||
|
/// <response code="403">API-ключ не имеет доступа к методу.</response>
|
||||||
|
/// <response code="404">Пользователь не найден.</response>
|
||||||
|
/// <response code="502">Вышестоящий сервис вернул ошибку или некорректный ответ.</response>
|
||||||
|
/// <response code="500">Внутренняя ошибка обработки запроса.</response>
|
||||||
|
[HttpGet("subid", Name = "UniVerseGetSubId")]
|
||||||
|
[Authorize(AuthenticationSchemes = "ApiKey")]
|
||||||
|
[Produces("text/plain")]
|
||||||
|
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||||
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status502BadGateway)]
|
||||||
|
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
|
||||||
|
public async Task<IActionResult> GetSubId(
|
||||||
|
[FromQuery] string? fullname,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(fullname))
|
||||||
|
return BadRequest("Query parameter 'fullname' is required.");
|
||||||
|
|
||||||
|
var result = await lookupService.FindSubIdAsync(fullname, cancellationToken);
|
||||||
|
|
||||||
|
return result.Status switch
|
||||||
|
{
|
||||||
|
UniverseUserLookupStatus.Found => Content(result.SubId!, "text/plain"),
|
||||||
|
UniverseUserLookupStatus.NotFound => NotFound(),
|
||||||
|
UniverseUserLookupStatus.UpstreamError => Problem(
|
||||||
|
result.ErrorMessage,
|
||||||
|
statusCode: StatusCodes.Status502BadGateway),
|
||||||
|
_ => Problem(statusCode: StatusCodes.Status500InternalServerError)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
-15
@@ -3,21 +3,6 @@ using System.Text.Json.Serialization;
|
|||||||
|
|
||||||
namespace SfeduSchedule.Plugin.UniVerse;
|
namespace SfeduSchedule.Plugin.UniVerse;
|
||||||
|
|
||||||
public sealed record UniverseUserLookupResult(
|
|
||||||
UniverseUserLookupStatus Status,
|
|
||||||
string? SubId = null,
|
|
||||||
string? ErrorMessage = null)
|
|
||||||
{
|
|
||||||
public static UniverseUserLookupResult Found(string subId) =>
|
|
||||||
new(UniverseUserLookupStatus.Found, subId);
|
|
||||||
|
|
||||||
public static UniverseUserLookupResult NotFound() =>
|
|
||||||
new(UniverseUserLookupStatus.NotFound);
|
|
||||||
|
|
||||||
public static UniverseUserLookupResult UpstreamError(string message) =>
|
|
||||||
new(UniverseUserLookupStatus.UpstreamError, ErrorMessage: message);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed record UniverseUsersGraphQlRequest(
|
internal sealed record UniverseUsersGraphQlRequest(
|
||||||
[property: JsonPropertyName("query")] string Query,
|
[property: JsonPropertyName("query")] string Query,
|
||||||
[property: JsonPropertyName("variables")] UniverseUsersGraphQlVariables Variables);
|
[property: JsonPropertyName("variables")] UniverseUsersGraphQlVariables Variables);
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
namespace SfeduSchedule.Plugin.UniVerse;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Результат поиска пользователя.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Status">Статус выполнения поиска.</param>
|
||||||
|
/// <param name="SubId">Найденный Sub ID пользователя.</param>
|
||||||
|
/// <param name="ErrorMessage">Описание ошибки вышестоящего сервиса.</param>
|
||||||
|
public sealed record UniverseUserLookupResult(
|
||||||
|
UniverseUserLookupStatus Status,
|
||||||
|
string? SubId = null,
|
||||||
|
string? ErrorMessage = null)
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Успешный результат поиска.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="subId">Найденный Sub ID пользователя.</param>
|
||||||
|
/// <returns>Результат со статусом Found.</returns>
|
||||||
|
public static UniverseUserLookupResult Found(string subId) =>
|
||||||
|
new(UniverseUserLookupStatus.Found, subId);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Результат для случая, когда пользователь не найден.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>Результат со статусом NotFound.</returns>
|
||||||
|
public static UniverseUserLookupResult NotFound() =>
|
||||||
|
new(UniverseUserLookupStatus.NotFound);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Результат ошибки вышестоящего сервиса.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="message">Описание ошибки.</param>
|
||||||
|
/// <returns>Результат со статусом UpstreamError.</returns>
|
||||||
|
public static UniverseUserLookupResult UpstreamError(string message) =>
|
||||||
|
new(UniverseUserLookupStatus.UpstreamError, ErrorMessage: message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum UniverseUserLookupStatus
|
||||||
|
{
|
||||||
|
Found,
|
||||||
|
NotFound,
|
||||||
|
UpstreamError
|
||||||
|
}
|
||||||
@@ -1,20 +1,11 @@
|
|||||||
using System.Net.Http.Headers;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using System.Text.Json;
|
|
||||||
using Microsoft.AspNetCore.Builder;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.AspNetCore.Routing;
|
using Microsoft.AspNetCore.Routing;
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using ModeusSchedule.Abstractions;
|
using ModeusSchedule.Abstractions;
|
||||||
|
|
||||||
namespace SfeduSchedule.Plugin.UniVerse;
|
namespace SfeduSchedule.Plugin.UniVerse;
|
||||||
|
|
||||||
public sealed class UniVersePlugin : IPlugin
|
public sealed class UniVersePlugin : IPlugin
|
||||||
{
|
{
|
||||||
private const string ApiKeyScheme = "ApiKey";
|
|
||||||
|
|
||||||
public string Name => "UniVerse";
|
public string Name => "UniVerse";
|
||||||
|
|
||||||
public void ConfigureServices(IServiceCollection services)
|
public void ConfigureServices(IServiceCollection services)
|
||||||
@@ -24,124 +15,5 @@ public sealed class UniVersePlugin : IPlugin
|
|||||||
|
|
||||||
public void MapEndpoints(IEndpointRouteBuilder endpoints)
|
public void MapEndpoints(IEndpointRouteBuilder endpoints)
|
||||||
{
|
{
|
||||||
endpoints.MapGet("/plugins/universe/subid",
|
|
||||||
async (string? fullname, IUniverseUserLookupService lookupService, CancellationToken cancellationToken) =>
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(fullname))
|
|
||||||
return Results.BadRequest("Query parameter 'fullname' is required.");
|
|
||||||
|
|
||||||
var result = await lookupService.FindSubIdAsync(fullname, cancellationToken);
|
|
||||||
|
|
||||||
return result.Status switch
|
|
||||||
{
|
|
||||||
UniverseUserLookupStatus.Found => Results.Text(result.SubId, "text/plain"),
|
|
||||||
UniverseUserLookupStatus.NotFound => Results.NotFound(),
|
|
||||||
UniverseUserLookupStatus.UpstreamError => Results.Problem(
|
|
||||||
result.ErrorMessage,
|
|
||||||
statusCode: StatusCodes.Status502BadGateway),
|
|
||||||
_ => Results.Problem(statusCode: StatusCodes.Status500InternalServerError)
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.RequireAuthorization(policy => policy
|
|
||||||
.AddAuthenticationSchemes(ApiKeyScheme)
|
|
||||||
.RequireAuthenticatedUser())
|
|
||||||
.WithName("UniVerseGetSubId")
|
|
||||||
.Produces<string>(StatusCodes.Status200OK, "text/plain")
|
|
||||||
.Produces(StatusCodes.Status400BadRequest)
|
|
||||||
.Produces(StatusCodes.Status401Unauthorized)
|
|
||||||
.Produces(StatusCodes.Status403Forbidden)
|
|
||||||
.Produces(StatusCodes.Status404NotFound)
|
|
||||||
.ProducesProblem(StatusCodes.Status502BadGateway);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public interface IUniverseUserLookupService
|
|
||||||
{
|
|
||||||
Task<UniverseUserLookupResult> FindSubIdAsync(string fullName, CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class UniverseUserLookupService(
|
|
||||||
HttpClient httpClient,
|
|
||||||
IConfiguration configuration,
|
|
||||||
ILogger<UniverseUserLookupService> logger) : IUniverseUserLookupService
|
|
||||||
{
|
|
||||||
private const string AccessControlApiPath = "access-control/api";
|
|
||||||
private const string UsersQuery = """
|
|
||||||
query($t:String!){ users(filter:{text:$t}, pager:{activePage:1,pageSize:10}) { items { id name displayName description } } }
|
|
||||||
""";
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
|
||||||
|
|
||||||
public async Task<UniverseUserLookupResult> FindSubIdAsync(
|
|
||||||
string fullName,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var token = configuration["TOKEN"];
|
|
||||||
if (string.IsNullOrWhiteSpace(token))
|
|
||||||
return UniverseUserLookupResult.UpstreamError("Modeus TOKEN is not configured.");
|
|
||||||
|
|
||||||
var modeusUrl = configuration["MODEUS_URL"];
|
|
||||||
if (string.IsNullOrWhiteSpace(modeusUrl))
|
|
||||||
return UniverseUserLookupResult.UpstreamError("MODEUS_URL is not configured.");
|
|
||||||
|
|
||||||
httpClient.BaseAddress = new Uri(modeusUrl, UriKind.Absolute);
|
|
||||||
|
|
||||||
using var request = new HttpRequestMessage(HttpMethod.Post, AccessControlApiPath);
|
|
||||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
|
||||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
|
||||||
request.Content = JsonContent.Create(
|
|
||||||
new UniverseUsersGraphQlRequest(
|
|
||||||
UsersQuery,
|
|
||||||
new UniverseUsersGraphQlVariables(fullName)),
|
|
||||||
options: JsonOptions);
|
|
||||||
|
|
||||||
using var response = await httpClient.SendAsync(request, cancellationToken);
|
|
||||||
if (!response.IsSuccessStatusCode)
|
|
||||||
{
|
|
||||||
logger.LogWarning(
|
|
||||||
"Modeus access-control/api returned {StatusCode} while searching user by fullName.",
|
|
||||||
response.StatusCode);
|
|
||||||
return UniverseUserLookupResult.UpstreamError(
|
|
||||||
$"Modeus access-control/api returned {(int)response.StatusCode}.");
|
|
||||||
}
|
|
||||||
|
|
||||||
UniverseUsersGraphQlResponse? payload;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await using var contentStream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
|
||||||
payload = await JsonSerializer.DeserializeAsync<UniverseUsersGraphQlResponse>(
|
|
||||||
contentStream,
|
|
||||||
JsonOptions,
|
|
||||||
cancellationToken);
|
|
||||||
}
|
|
||||||
catch (JsonException exception)
|
|
||||||
{
|
|
||||||
logger.LogWarning(exception, "Unable to deserialize Modeus access-control/api response.");
|
|
||||||
return UniverseUserLookupResult.UpstreamError("Modeus access-control/api returned invalid JSON.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (payload?.Errors is { Count: > 0 })
|
|
||||||
{
|
|
||||||
logger.LogWarning(
|
|
||||||
"Modeus access-control/api returned GraphQL errors: {Errors}",
|
|
||||||
JsonSerializer.Serialize(payload.Errors, JsonOptions));
|
|
||||||
return UniverseUserLookupResult.UpstreamError("Modeus access-control/api returned GraphQL errors.");
|
|
||||||
}
|
|
||||||
|
|
||||||
var users = payload?.Data?.Users?.Items;
|
|
||||||
if (users is null || users.Count == 0)
|
|
||||||
return UniverseUserLookupResult.NotFound();
|
|
||||||
|
|
||||||
var subId = users[0].Name;
|
|
||||||
return string.IsNullOrWhiteSpace(subId)
|
|
||||||
? UniverseUserLookupResult.NotFound()
|
|
||||||
: UniverseUserLookupResult.Found(subId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum UniverseUserLookupStatus
|
|
||||||
{
|
|
||||||
Found,
|
|
||||||
NotFound,
|
|
||||||
UpstreamError
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace SfeduSchedule.Plugin.UniVerse;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сервис поиска Sub ID через API Modeus.
|
||||||
|
/// </summary>
|
||||||
|
public interface IUniverseUserLookupService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Найти Sub ID пользователя по полному имени.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fullName">Полное имя пользователя.</param>
|
||||||
|
/// <param name="cancellationToken">Токен отмены запроса.</param>
|
||||||
|
/// <returns>Результат поиска пользователя и его Sub ID, если он найден.</returns>
|
||||||
|
Task<UniverseUserLookupResult> FindSubIdAsync(string fullName, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace SfeduSchedule.Plugin.UniVerse;
|
||||||
|
|
||||||
|
public sealed class UniverseUserLookupService(
|
||||||
|
HttpClient httpClient,
|
||||||
|
IConfiguration configuration,
|
||||||
|
ILogger<UniverseUserLookupService> logger) : IUniverseUserLookupService
|
||||||
|
{
|
||||||
|
private const string AccessControlApiPath = "access-control/api";
|
||||||
|
private const string UsersQuery = """
|
||||||
|
query($t:String!){ users(filter:{text:$t}, pager:{activePage:1,pageSize:10}) { items { id name displayName description } } }
|
||||||
|
""";
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||||
|
|
||||||
|
public async Task<UniverseUserLookupResult> FindSubIdAsync(
|
||||||
|
string fullName,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var token = configuration["TOKEN"];
|
||||||
|
if (string.IsNullOrWhiteSpace(token))
|
||||||
|
return UniverseUserLookupResult.UpstreamError("Modeus TOKEN is not configured.");
|
||||||
|
|
||||||
|
var modeusUrl = configuration["MODEUS_URL"];
|
||||||
|
if (string.IsNullOrWhiteSpace(modeusUrl))
|
||||||
|
return UniverseUserLookupResult.UpstreamError("MODEUS_URL is not configured.");
|
||||||
|
|
||||||
|
httpClient.BaseAddress = new Uri(modeusUrl, UriKind.Absolute);
|
||||||
|
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, AccessControlApiPath);
|
||||||
|
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||||
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
|
request.Content = JsonContent.Create(
|
||||||
|
new UniverseUsersGraphQlRequest(
|
||||||
|
UsersQuery,
|
||||||
|
new UniverseUsersGraphQlVariables(fullName)),
|
||||||
|
options: JsonOptions);
|
||||||
|
|
||||||
|
using var response = await httpClient.SendAsync(request, cancellationToken);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
logger.LogWarning(
|
||||||
|
"Modeus access-control/api returned {StatusCode} while searching user by fullName.",
|
||||||
|
response.StatusCode);
|
||||||
|
return UniverseUserLookupResult.UpstreamError(
|
||||||
|
$"Modeus access-control/api returned {(int)response.StatusCode}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
UniverseUsersGraphQlResponse? payload;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var contentStream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||||
|
payload = await JsonSerializer.DeserializeAsync<UniverseUsersGraphQlResponse>(
|
||||||
|
contentStream,
|
||||||
|
JsonOptions,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
catch (JsonException exception)
|
||||||
|
{
|
||||||
|
logger.LogWarning(exception, "Unable to deserialize Modeus access-control/api response.");
|
||||||
|
return UniverseUserLookupResult.UpstreamError("Modeus access-control/api returned invalid JSON.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload?.Errors is { Count: > 0 })
|
||||||
|
{
|
||||||
|
logger.LogWarning(
|
||||||
|
"Modeus access-control/api returned GraphQL errors: {Errors}",
|
||||||
|
JsonSerializer.Serialize(payload.Errors, JsonOptions));
|
||||||
|
return UniverseUserLookupResult.UpstreamError("Modeus access-control/api returned GraphQL errors.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var users = payload?.Data?.Users?.Items;
|
||||||
|
if (users is null || users.Count == 0)
|
||||||
|
return UniverseUserLookupResult.NotFound();
|
||||||
|
|
||||||
|
var subId = users[0].Name;
|
||||||
|
return string.IsNullOrWhiteSpace(subId)
|
||||||
|
? UniverseUserLookupResult.NotFound()
|
||||||
|
: UniverseUserLookupResult.Found(subId);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user