refactor: to return the result according to the RFC 7807 standard and add a traceId

This commit is contained in:
2024-12-22 05:25:19 +03:00
parent f2e79e51f2
commit e4b942d062
10 changed files with 68 additions and 74 deletions

View File

@ -15,6 +15,7 @@ using Mirea.Api.Security.Common.Domain;
using Mirea.Api.Security.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Claims;
using System.Threading.Tasks;
using OAuthProvider = Mirea.Api.Security.Common.Domain.OAuthProvider;
@ -31,17 +32,17 @@ public class AuthController(IOptionsSnapshot<Admin> user, IOptionsSnapshot<Gener
Path = UrlHelper.GetSubPathWithoutFirstApiName + "api"
};
private static string GenerateHtmlResponse(string title, string message, OAuthProvider? provider, bool isError = false)
private static string GenerateHtmlResponse(string title, string message, OAuthProvider? provider, bool isError = false, string? traceId = null)
{
string messageColor = isError ? "red" : "white";
string script = "<script>setTimeout(()=>{if(window.opener){window.opener.postMessage(" +
"{success:" + !isError +
"{success:" + (!isError).ToString().ToLower() +
",provider:'" + (provider == null ? "null" : (int)provider) +
"',providerName:'" + (provider == null ? "null" : Enum.GetName(provider.Value)) +
"',message:'" + message.Replace("'", "\\'") +
"'},'*');}window.close();}, 5000);</script>";
"'},'*');}window.close();}, 15000);</script>";
return $"<!DOCTYPE html><html lang=ru><head><meta charset=UTF-8><meta content=\"width=device-width,initial-scale=1\"name=viewport><link href=\"https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap\"rel=stylesheet><style>body{{background-color:#121212;color:#fff;font-family:Roboto,sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;text-align:center}}.container{{max-width:600px;padding:20px;border-radius:8px;background-color:#1e1e1e;box-shadow:0 4px 20px rgba(0,0,0,.5)}}h1{{font-size:24px;margin-bottom:20px}}p{{font-size:16px;color:{messageColor}}}</style><title>{title}</title></head><body><div class=container><h1>{title}</h1><p>{message}<p style=font-size:14px;color:silver;>Это информационная страница. Вы можете закрыть её.</div>{script}</body></html>";
return $"<!DOCTYPE html><html lang=ru><head><meta charset=UTF-8><meta content=\"width=device-width,initial-scale=1\"name=viewport><link href=\"https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap\"rel=stylesheet><style>body{{background-color:#121212;color:#fff;font-family:Roboto,sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;text-align:center}}.container{{max-width:600px;padding:20px;border-radius:8px;background-color:#1e1e1e;box-shadow:0 4px 20px rgba(0,0,0,.5)}}h1{{font-size:24px;margin-bottom:20px}}p{{font-size:16px;color:{messageColor}}}</style><title>{title}</title></head><body><div class=container><h1>{title}</h1><p>{message}</p><p style=font-size:14px;color:silver;>Это информационная страница. Вы можете закрыть её.</p>{(!string.IsNullOrEmpty(traceId) ? $"<code style=font-size:12px;color:gray;>TraceId={traceId}</code>" : string.Empty)}</div>{script}</body></html>";
}
[HttpGet("OAuth2")]
@ -56,6 +57,7 @@ public class AuthController(IOptionsSnapshot<Admin> user, IOptionsSnapshot<Gener
string message;
OAuthProvider provider;
OAuthUser oAuthUser;
var traceId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
try
{
@ -66,7 +68,7 @@ public class AuthController(IOptionsSnapshot<Admin> user, IOptionsSnapshot<Gener
{
title = "Произошла ошибка при общении с провайдером OAuth!";
message = e.Message;
return Content(GenerateHtmlResponse(title, message, null, true), "text/html");
return Content(GenerateHtmlResponse(title, message, null, true, traceId), "text/html");
}
var userEntity = user.Value;
@ -79,7 +81,7 @@ public class AuthController(IOptionsSnapshot<Admin> user, IOptionsSnapshot<Gener
{
title = "Ошибка связи аккаунта!";
message = "Этот OAuth провайдер уже связан с вашей учетной записью. Пожалуйста, используйте другого провайдера или удалите связь с аккаунтом.";
return Content(GenerateHtmlResponse(title, message, provider, true), "text/html");
return Content(GenerateHtmlResponse(title, message, provider, true, traceId), "text/html");
}
userEntity.SaveSetting();

View File

@ -81,7 +81,7 @@ public class ProfessorController(IMediator mediator) : BaseController
public async Task<ActionResult<List<ProfessorResponse>>> GetDetails(string name)
{
if (string.IsNullOrEmpty(name) || name.Length < 4)
return BadRequest($"The minimum number of characters is 4 (current: {name.Length}).");
throw new ControllerArgumentException($"The minimum number of characters is 4 (current: {name.Length}).");
var result = await mediator.Send(new GetProfessorInfoSearchQuery()
{

View File

@ -8,6 +8,7 @@ using Mirea.Api.Dto.Common;
using Mirea.Api.Dto.Requests;
using Mirea.Api.Dto.Responses;
using Mirea.Api.Endpoint.Common.Attributes;
using Mirea.Api.Endpoint.Common.Exceptions;
using Mirea.Api.Endpoint.Common.MapperDto;
using Mirea.Api.Endpoint.Configuration.Model;
using System;
@ -52,14 +53,10 @@ public class ScheduleController(IMediator mediator, IOptionsSnapshot<GeneralConf
(request.Professors == null || request.Professors.Length == 0) &&
(request.LectureHalls == null || request.LectureHalls.Length == 0))
{
return BadRequest(new ErrorResponse()
{
Error = "At least one of the arguments must be selected."
+ (request.IsEven.HasValue
? $" \"{nameof(request.IsEven)}\" is not a strong argument"
: string.Empty),
Code = StatusCodes.Status400BadRequest
});
throw new ControllerArgumentException("At least one of the arguments must be selected."
+ (request.IsEven.HasValue
? $" \"{nameof(request.IsEven)}\" is not a strong argument"
: string.Empty));
}
var result = (await mediator.Send(new GetScheduleListQuery

View File

@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Mirea.Api.Dto.Common;
using Mirea.Api.Endpoint.Common.Attributes;
using Mirea.Api.Endpoint.Common.Exceptions;
using Mirea.Api.Endpoint.Common.MapperDto;
using Mirea.Api.Endpoint.Configuration.Model;
using QRCoder;
@ -68,7 +69,7 @@ public class SecurityController(IOptionsSnapshot<GeneralConfig> generalConfig) :
}
catch (Exception ex)
{
return BadRequest($"Failed to generate QR code: {ex.Message}");
throw new ControllerArgumentException($"Failed to generate QR code: {ex.Message}");
}
}