mirror of
https://github.com/Govor-team/Govor.git
synced 2026-09-21 02:10:56 +00:00
Switch to SmartRes Result/Error, upgrade to .NET 10
Migrate codebase to use SmartRes Result<T, Error> (and Unit) across services and interfaces, replacing previous Result usage and updating many method signatures and implementations. Add ResultExtensions to convert SmartRes results to ASP.NET ActionResult and refactor AuthController to use functional Bind/Tap chains for registration/login flows. Upgrade projects to .NET 10 and bump related NuGet packages; add libs/SmartRes.dll and project references. Simplify DbContext registration to use Npgsql only with retry policies and enable detailed logging. Update Swagger/launch settings and other minor fixes (AutoMapper registration change, whitespace/exception handling, and removal of the Govor.ConsoleClient files).
This commit is contained in:
@@ -98,7 +98,7 @@ public static class ConfigurationProgramExtensions
|
||||
|
||||
|
||||
// Auto Mapper
|
||||
services.AddAutoMapper(typeof(MappingProfile));
|
||||
services.AddAutoMapper(op => { }, typeof(MappingProfile));
|
||||
|
||||
services.AddScoped<IHubUserAccessor, HubUserAccessor>();
|
||||
|
||||
@@ -111,52 +111,26 @@ public static class ConfigurationProgramExtensions
|
||||
|
||||
services.AddScoped<IProfileService, ProfileService>();
|
||||
}
|
||||
|
||||
|
||||
public static void AddGovorDbContext(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var useMySql = configuration.GetValue<bool>("UseMySql");
|
||||
|
||||
if (useMySql)
|
||||
services.AddDbContext<GovorDbContext>(options =>
|
||||
{
|
||||
services.AddDbContext<GovorDbContext>(options =>
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString(nameof(GovorDbContext));
|
||||
options.UseNpgsql(
|
||||
configuration.GetConnectionString(nameof(GovorDbContext)),
|
||||
npgsqlOptions =>
|
||||
{
|
||||
// retry for transient failures
|
||||
npgsqlOptions.EnableRetryOnFailure(
|
||||
5,
|
||||
TimeSpan.FromSeconds(5),
|
||||
null);
|
||||
});
|
||||
|
||||
options.UseMySql(
|
||||
connectionString,
|
||||
new MySqlServerVersion(new Version(8, 0, 21)),
|
||||
mySqlOptions =>
|
||||
{
|
||||
mySqlOptions.EnableRetryOnFailure(
|
||||
maxRetryCount: 5,
|
||||
maxRetryDelay: TimeSpan.FromSeconds(5),
|
||||
errorNumbersToAdd: null);
|
||||
});
|
||||
|
||||
options.EnableSensitiveDataLogging();
|
||||
options.EnableDetailedErrors();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
services.AddDbContext<GovorDbContext>(options =>
|
||||
{
|
||||
options.UseNpgsql(
|
||||
configuration.GetConnectionString(nameof(GovorDbContext)),
|
||||
npgsqlOptions =>
|
||||
{
|
||||
// retry for transient failures
|
||||
npgsqlOptions.EnableRetryOnFailure(
|
||||
maxRetryCount: 5,
|
||||
maxRetryDelay: TimeSpan.FromSeconds(5),
|
||||
errorCodesToAdd: null);
|
||||
});
|
||||
|
||||
//options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
|
||||
|
||||
options.EnableSensitiveDataLogging();
|
||||
options.EnableDetailedErrors();
|
||||
});
|
||||
}
|
||||
//options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
|
||||
|
||||
options.EnableSensitiveDataLogging();
|
||||
options.EnableDetailedErrors();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Govor.Domain.Common;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.API.Common.Extensions;
|
||||
|
||||
public static class ResultExtensions
|
||||
{
|
||||
public static ActionResult ToActionResult<T>(this Result<T, Error> result)
|
||||
{
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
// Если тип Unit, возвращаем 204 No Content, иначе 200 OK со значением
|
||||
return typeof(T) == typeof(Unit)
|
||||
? new StatusCodeResult(StatusCodes.Status204NoContent)
|
||||
: new OkObjectResult(result.Value);
|
||||
}
|
||||
|
||||
return GenerateProblemDetails(result.Error);
|
||||
}
|
||||
|
||||
private static ActionResult GenerateProblemDetails(Error error)
|
||||
{
|
||||
var statusCode = error.Type switch
|
||||
{
|
||||
ErrorType.NotFound => StatusCodes.Status404NotFound,
|
||||
ErrorType.Validation => StatusCodes.Status400BadRequest,
|
||||
ErrorType.Conflict => StatusCodes.Status409Conflict,
|
||||
ErrorType.Unauthorized => StatusCodes.Status401Unauthorized,
|
||||
ErrorType.Forbidden => StatusCodes.Status403Forbidden,
|
||||
_ => StatusCodes.Status400BadRequest
|
||||
};
|
||||
|
||||
var problemDetails = new ProblemDetails
|
||||
{
|
||||
Status = statusCode,
|
||||
Title = GetTitleForErrorType(error.Type),
|
||||
Detail = error.Message,
|
||||
};
|
||||
|
||||
problemDetails.Extensions.Add("errorCode", error.Code);
|
||||
|
||||
if (error.Errors is not null)
|
||||
{
|
||||
problemDetails.Extensions.Add("errors", error.Errors);
|
||||
}
|
||||
|
||||
return new ObjectResult(problemDetails) { StatusCode = statusCode };
|
||||
}
|
||||
|
||||
private static string GetTitleForErrorType(ErrorType type) => type switch
|
||||
{
|
||||
ErrorType.NotFound => "Not Found",
|
||||
ErrorType.Validation => "Validation Error",
|
||||
ErrorType.Conflict => "Conflict",
|
||||
ErrorType.Unauthorized => "Unauthorized",
|
||||
ErrorType.Forbidden => "Forbidden",
|
||||
_ => "Bad Request"
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.Application.Authentication;
|
||||
using Govor.Application.Authentication.Exceptions;
|
||||
using Govor.Application.Users.UserSessions;
|
||||
using Govor.Contracts.Requests;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.API.Controllers.Authentication;
|
||||
|
||||
@@ -30,82 +31,47 @@ public class AuthController : Controller
|
||||
}
|
||||
|
||||
[HttpPost("register")] // api/auth/register
|
||||
public async Task<IActionResult> Register([FromBody] RegistrationRequest registrationRequest)
|
||||
public async Task<IActionResult> Register([FromBody] RegistrationRequest request)
|
||||
{
|
||||
|
||||
var inviteResult = await _invitesService.ValidateAsync(registrationRequest.InviteLink);
|
||||
if (!inviteResult.IsSuccess)
|
||||
_logger.LogInformation("Processing registration request for: {Name}", request.Name);
|
||||
|
||||
var result = await _invitesService.ValidateAsync(request.InviteLink)
|
||||
.BindAsync(invite => _accountService.RegistrationAsync(request.Name, request.Password, invite))
|
||||
.TapAsync(user => _logger.LogInformation("User {Username} ({Id}) registered successfully", user.Username, user.Id))
|
||||
.BindAsync(user => _userSession.OpenSessionAsync(user, request.DeviceInfo));
|
||||
|
||||
if (result.IsFailure)
|
||||
{
|
||||
_logger.LogWarning("Invite link invalid: {InviteLink}. Error: {Error}", registrationRequest.InviteLink,
|
||||
inviteResult.Error);
|
||||
return BadRequest($"Invite link invalid: {inviteResult.Error.Message}");
|
||||
_logger.LogWarning("Registration pipeline failed. Error: {Code} - {Message}",
|
||||
result.Error.Code, result.Error.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Session opened successfully for the request.");
|
||||
}
|
||||
|
||||
var userResult = await _accountService.RegistrationAsync(
|
||||
registrationRequest.Name,
|
||||
registrationRequest.Password,
|
||||
inviteResult.Value);
|
||||
|
||||
if (userResult.IsFailure)
|
||||
{
|
||||
_logger.LogWarning("Registration failed for user {Name}. Error: {Error}", registrationRequest.Name,
|
||||
userResult.Error);
|
||||
|
||||
return userResult.Error.Code switch
|
||||
{
|
||||
nameof(UserAlreadyExistException) => BadRequest($"Registration failed: {userResult.Error.Message}"),
|
||||
nameof(InvalidUsernameException) => BadRequest($"Invalid username: {userResult.Error.Message}"),
|
||||
_ => BadRequest($"Registration failed: {userResult.Error.Message}")
|
||||
};
|
||||
}
|
||||
|
||||
var user = userResult.Value;
|
||||
_logger.LogInformation("Register request for {Username} with id {Id} processed successfully", user.Username,
|
||||
user.Id);
|
||||
|
||||
var sessionResult = await _userSession.OpenSessionAsync(user, registrationRequest.DeviceInfo);
|
||||
if (sessionResult.IsFailure)
|
||||
{
|
||||
_logger.LogError("Failed to open session for user {Username}. Error: {Error}", user.Username,
|
||||
sessionResult.Error.Message);
|
||||
return StatusCode(500, "An error occurred while creating the session.");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Session for user {Username} with id {Id} has been opened", user.Username, user.Id);
|
||||
return Ok(sessionResult.Value);
|
||||
return result.ToActionResult();
|
||||
}
|
||||
|
||||
|
||||
[HttpPost("login")] // api/auth/login
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest)
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request)
|
||||
{
|
||||
var userResult = await _accountService.LoginAsync(loginRequest.Name, loginRequest.Password);
|
||||
_logger.LogInformation("Processing registration request for: {Name}", request.Name);
|
||||
|
||||
var result = await _accountService.LoginAsync(request.Name, request.Password)
|
||||
.TapAsync(user => _logger.LogInformation("User {Username} ({Id}) logged in.", user.Username, user.Id))
|
||||
.BindAsync(user => _userSession.OpenSessionAsync(user, request.DeviceInfo));
|
||||
|
||||
if (userResult.IsFailure)
|
||||
if (result.IsFailure)
|
||||
{
|
||||
_logger.LogWarning("Login failed for user {Name}. Error: {Code}", loginRequest.Name, userResult.Error);
|
||||
|
||||
return userResult.Error.Code switch
|
||||
{
|
||||
nameof(UserNotRegisteredException) => BadRequest("Login failed: user does not exist."),
|
||||
nameof(InvalidOperationException) => BadRequest("Login failed: username or password is incorrect."),
|
||||
_ => BadRequest($"Login failed: {userResult.Error.Message}")
|
||||
};
|
||||
_logger.LogWarning("Login pipeline failed. Error: {Code} - {Message}",
|
||||
result.Error.Code, result.Error.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Session opened successfully for the request.");
|
||||
}
|
||||
|
||||
var user = userResult.Value;
|
||||
_logger.LogInformation("Login request for {Username} with id {Id} processed successfully", user.Username, user.Id);
|
||||
|
||||
var sessionResult = await _userSession.OpenSessionAsync(user, loginRequest.DeviceInfo);
|
||||
|
||||
if (sessionResult.IsFailure)
|
||||
{
|
||||
_logger.LogError("Failed to open session for user {Username}. Error: {Error}", user.Username, sessionResult.Error);
|
||||
return StatusCode(500, "An error occurred while creating the session.");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Session for user {Username} with id {Id} has been opened", user.Username, user.Id);
|
||||
|
||||
return Ok(sessionResult.Value);
|
||||
return result.ToActionResult();
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ public class FriendshipController : Controller
|
||||
{
|
||||
_logger.LogWarning(ex, ex.Message);
|
||||
return Forbid(ex.Message);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, ex.Message);
|
||||
|
||||
+18
-12
@@ -1,27 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>disable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="12.0.1" />
|
||||
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="FirebaseAdmin" Version="3.4.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.5" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.6" />
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.2.0" />
|
||||
<PackageReference Include="FirebaseAdmin" Version="3.6.0" />
|
||||
<PackageReference Include="AutoMapper" Version="16.0.0" />
|
||||
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.10" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.10" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10" />
|
||||
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.3" />
|
||||
<PackageReference Include="NSwag.AspNetCore" Version="14.4.0" />
|
||||
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
|
||||
<PackageReference Include="Microting.EntityFrameworkCore.MySql" Version="10.0.10" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="SmartRes">
|
||||
<HintPath>..\libs\SmartRes.dll</HintPath>
|
||||
</Reference>
|
||||
<ProjectReference Include="..\Govor.Application\Govor.Application.csproj" />
|
||||
<ProjectReference Include="..\Govor.Contracts\Govor.Contracts.csproj" />
|
||||
<ProjectReference Include="..\Govor.Domain\Govor.Domain.csproj" />
|
||||
|
||||
+20
-14
@@ -7,7 +7,7 @@ using Govor.Application.Authentication.JWT;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
@@ -86,28 +86,34 @@ builder.Services.AddGovorDbContext(configuration); // GovorDbContext init
|
||||
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
|
||||
builder.Services.AddSwaggerGen(options =>
|
||||
services.AddSwaggerGen(options =>
|
||||
{
|
||||
const string schemeId = "Bearer";
|
||||
|
||||
options.SwaggerDoc("v1", new OpenApiInfo { Title = "Govor API", Version = "v1" });
|
||||
|
||||
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||
options.AddSecurityDefinition(schemeId, new OpenApiSecurityScheme
|
||||
{
|
||||
Description = "JWT Authorization header using the Bearer scheme. Example: 'Bearer {token}'",
|
||||
Name = "Authorization",
|
||||
In = ParameterLocation.Header,
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer"
|
||||
In = ParameterLocation.Header,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "JWT",
|
||||
Description = "JWT Authorization header using the Bearer scheme. Example: 'Bearer {token}'"
|
||||
});
|
||||
|
||||
options.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||
options.AddSecurityRequirement(document =>
|
||||
{
|
||||
var requirement = new OpenApiSecurityRequirement
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
|
||||
},
|
||||
Array.Empty<string>()
|
||||
}
|
||||
new OpenApiSecuritySchemeReference(schemeId)
|
||||
{
|
||||
Reference = new OpenApiReferenceWithDescription { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
|
||||
},
|
||||
[]
|
||||
}
|
||||
};
|
||||
return requirement;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -121,7 +127,7 @@ if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
//app.MapOpenApi();
|
||||
builder.WebHost.UseUrls("http://0.0.0.0:8080");
|
||||
builder.WebHost.UseUrls("http://10.8.0.5:5000");
|
||||
//builder.WebHost.UseUrls("http://10.8.0.5:5000");
|
||||
//builder.WebHost.UseUrls("http://192.168.1.107:8080");
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://0.0.0.0:8080;http://localhost:7155;http://10.8.0.5:5000",
|
||||
"applicationUrl": "http://0.0.0.0:8080;http://localhost:7155",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user