Добавлен CORS, исправлен профиль

This commit is contained in:
Халимов Рустам
2026-02-13 11:45:41 +03:00
parent a474313cec
commit b24b9d697f
3 changed files with 70 additions and 11 deletions

View File

@@ -4,14 +4,14 @@ using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Nashel.Modules.Catalog.Infrastructure;
using Nashel.Modules.Catalog.Presentation.Endpoints;
using Nashel.Modules.Collaboration.Infrastructure;
using Nashel.Modules.Collaboration.Presentation;
using Nashel.Modules.Geo.Infrastructure;
using Nashel.Modules.Geo.Presentation;
using Nashel.Modules.Identity.Infrastructure;
using Nashel.Modules.Identity.Presentation.Endpoints;
using Nashel.Modules.Order.Infrastructure;
using Nashel.Modules.Order.Presentation;
using Nashel.Modules.Collaboration.Infrastructure;
using Nashel.Modules.Collaboration.Presentation;
using Nashel.Modules.Reputation.Infrastructure;
using Nashel.Modules.Reputation.Presentation;
@@ -91,6 +91,17 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
builder.Services.AddAuthorization();
builder.Services.AddCors(options =>
{
options.AddPolicy("FrontendPolicy", policy =>
{
policy.WithOrigins("http://localhost:3000", "http://127.0.0.1:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
var app = builder.Build();
// Настройка конвейера HTTP-запросов.
@@ -103,6 +114,8 @@ if (app.Environment.IsDevelopment())
});
}
app.UseCors("FrontendPolicy");
// Включение аутентификации и авторизации
app.UseAuthentication();
app.UseAuthorization();

View File

@@ -0,0 +1,41 @@
using MediatR;
using Nashel.BuildingBlocks.Application.Abstractions;
using Nashel.Modules.Identity.Domain.Repositories;
namespace Nashel.Modules.Identity.Application.Queries.GetProfile;
public record GetProfileQuery : IRequest<ProfileResponse>;
public record ProfileResponse(Guid Id, string Phone, List<string> Roles);
public class GetProfileQueryHandler : IRequestHandler<GetProfileQuery, ProfileResponse>
{
private readonly IAccountRepository _accountRepository;
private readonly ICurrentUserService _currentUserService;
public GetProfileQueryHandler(IAccountRepository accountRepository, ICurrentUserService currentUserService)
{
_accountRepository = accountRepository;
_currentUserService = currentUserService;
}
public async Task<ProfileResponse> Handle(GetProfileQuery request, CancellationToken cancellationToken)
{
var userId = _currentUserService.UserId;
if (userId == null)
{
throw new UnauthorizedAccessException();
}
var account = await _accountRepository.GetByIdAsync(userId.Value, cancellationToken);
if (account == null)
{
throw new Exception("Account not found");
}
return new ProfileResponse(
account.Id,
account.Phone,
account.Roles.Select(r => r.ToString()).ToList());
}
}

View File

@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Nashel.Modules.Identity.Application.Commands;
using Nashel.Modules.Identity.Application.Queries.GetProfile;
namespace Nashel.Modules.Identity.Presentation.Endpoints;
@@ -18,30 +19,34 @@ public static class IdentityEndpoints
return Results.Ok(result);
})
.WithName("Register")
.WithOpenApi(operation => new(operation) { Summary = "Регистрация пользователя", Description = "Регистрирует нового пользователя по номеру телефона и паролю." });
.WithOpenApi(operation => new(operation) { Summary = "Регистрация пользователя" });
authGroup.MapPost("/login", async (LoginCommand command, ISender sender) =>
{
var token = await sender.Send(command);
return Results.Ok(new LoginResponse(token));
return Results.Ok(new LoginResponse(token, token)); // Пока что возвращаем один токен для обоих полей
})
.WithName("Login")
.WithOpenApi(operation => new(operation) { Summary = "Вход в систему", Description = "Аутентификация пользователя и получение JWT токена." });
.WithOpenApi(operation => new(operation) { Summary = "Вход в систему" });
var profileGroup = app.MapGroup("/api/profile").WithTags("Profile").RequireAuthorization();
profileGroup.MapGet("/", async (ISender sender) =>
{
var profile = await sender.Send(new GetProfileQuery());
return Results.Ok(profile);
})
.WithName("GetProfile")
.WithOpenApi(operation => new(operation) { Summary = "Получить профиль" });
profileGroup.MapPost("/become-performer", async (ISender sender) =>
{
await sender.Send(new BecomePerformerCommand());
return Results.Ok();
})
.WithName("BecomePerformer")
.WithOpenApi(operation => new(operation) { Summary = "Стать исполнителем", Description = "Присваивает текущему пользователю роль исполнителя." });
.WithOpenApi(operation => new(operation) { Summary = "Стать исполнителем" });
}
}
/// <summary>
/// Ответ на успешный вход в систему.
/// </summary>
/// <param name="Token">JWT токен доступа.</param>
public record LoginResponse(string Token);
public record LoginResponse(string AccessToken, string RefreshToken);