Add user creation functionality: implement API endpoint for creating new users, including request handling and response management. Update frontend to support user creation with a new form in the UsersPanel, integrating role selection and input validation. Enhance i18n for new user-related strings.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
using LiteCqrs;
|
||||
using TeleWave.Api.Common;
|
||||
using TeleWave.Application.Admin.Users.BlockUser;
|
||||
using TeleWave.Application.Admin.Users.CreateUser;
|
||||
using TeleWave.Application.Admin.Users.DeleteUser;
|
||||
using TeleWave.Application.Admin.Users.GetUser;
|
||||
using TeleWave.Application.Admin.Users.ListUsers;
|
||||
@@ -20,6 +21,7 @@ public static class AdminUserEndpoints
|
||||
.RequireAuthorization(policy => policy.RequireRole(RoleNames.Admin));
|
||||
|
||||
admin.MapGet("", ListUsers).Produces<PagedList<UserSummaryDto>>();
|
||||
admin.MapPost("", CreateUser).Produces<CreatedIdResponse>(StatusCodes.Status201Created);
|
||||
admin.MapGet("/{id:guid}", GetUser).Produces<UserSummaryDto>();
|
||||
admin
|
||||
.MapPost("/{id:guid}/block", BlockUser)
|
||||
@@ -49,6 +51,21 @@ public static class AdminUserEndpoints
|
||||
return Results.Ok(result);
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateUser(
|
||||
CreateUserBody body,
|
||||
ISender sender,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
var result = await sender.Send(
|
||||
new CreateUserCommand(body.UserName, body.Password, body.RoleId),
|
||||
cancellationToken
|
||||
);
|
||||
return result.IsSuccess
|
||||
? Results.Created($"/api/admin/users/{result.Value}", new CreatedIdResponse(result.Value))
|
||||
: result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetUser(
|
||||
Guid id,
|
||||
ISender sender,
|
||||
@@ -89,3 +106,5 @@ public static class AdminUserEndpoints
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record CreateUserBody(string UserName, string Password, Guid RoleId);
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
using LiteCqrs;
|
||||
using TeleWave.Application.Common.Models;
|
||||
|
||||
namespace TeleWave.Application.Admin.Users.CreateUser;
|
||||
|
||||
/// <summary>Создание пользователя администратором (в обход открытой регистрации), с выбором роли.</summary>
|
||||
public sealed record CreateUserCommand(string UserName, string Password, Guid RoleId)
|
||||
: ICommand<Result<Guid>>;
|
||||
@@ -0,0 +1,40 @@
|
||||
using LiteCqrs;
|
||||
using TeleWave.Application.Admin.Roles;
|
||||
using TeleWave.Application.Common.Interfaces;
|
||||
using TeleWave.Application.Common.Models;
|
||||
|
||||
namespace TeleWave.Application.Admin.Users.CreateUser;
|
||||
|
||||
public sealed class CreateUserCommandHandler(
|
||||
IIdentityService identityService,
|
||||
IRoleService roleService
|
||||
) : ICommandHandler<CreateUserCommand, Result<Guid>>
|
||||
{
|
||||
public async Task<Result<Guid>> Handle(
|
||||
CreateUserCommand command,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
// Роль проверяем до создания, чтобы не оставить пользователя с ролью по умолчанию при опечатке.
|
||||
var roles = await roleService.ListRolesAsync(cancellationToken);
|
||||
if (roles.All(r => r.Id != command.RoleId))
|
||||
return Result.Failure<Guid>(RoleErrors.NotFound);
|
||||
|
||||
var createResult = await identityService.CreateUserAsync(
|
||||
command.UserName,
|
||||
command.Password,
|
||||
cancellationToken
|
||||
);
|
||||
if (!createResult.IsSuccess)
|
||||
return Result.Failure<Guid>(createResult.Error);
|
||||
|
||||
var userId = createResult.Value;
|
||||
|
||||
// CreateUserAsync назначает роль по умолчанию — выставляем выбранную админом.
|
||||
var roleResult = await roleService.ChangeUserRoleAsync(userId, command.RoleId, cancellationToken);
|
||||
if (!roleResult.IsSuccess)
|
||||
return Result.Failure<Guid>(roleResult.Error);
|
||||
|
||||
return Result.Success(userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace TeleWave.Application.Admin.Users.CreateUser;
|
||||
|
||||
public sealed class CreateUserCommandValidator : AbstractValidator<CreateUserCommand>
|
||||
{
|
||||
public CreateUserCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.UserName).NotEmpty().MinimumLength(3).MaximumLength(64);
|
||||
RuleFor(x => x.Password).NotEmpty().MinimumLength(8);
|
||||
RuleFor(x => x.RoleId).NotEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using NSubstitute;
|
||||
using TeleWave.Application.Admin.Roles;
|
||||
using TeleWave.Application.Admin.Users.CreateUser;
|
||||
using TeleWave.Application.Common.Interfaces;
|
||||
using TeleWave.Application.Common.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace TeleWave.Application.Tests.Admin.Users;
|
||||
|
||||
public class CreateUserCommandHandlerTests
|
||||
{
|
||||
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
|
||||
private readonly IRoleService _roleService = Substitute.For<IRoleService>();
|
||||
|
||||
private CreateUserCommandHandler CreateHandler() => new(_identityService, _roleService);
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WithValidRole_CreatesUserAndAssignsRole()
|
||||
{
|
||||
var roleId = Guid.NewGuid();
|
||||
var userId = Guid.NewGuid();
|
||||
_roleService
|
||||
.ListRolesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<RoleDto> { new(roleId, "user", true) });
|
||||
_identityService
|
||||
.CreateUserAsync("bob", "Password1", Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success(userId));
|
||||
_roleService
|
||||
.ChangeUserRoleAsync(userId, roleId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Success());
|
||||
|
||||
var result = await CreateHandler()
|
||||
.Handle(new CreateUserCommand("bob", "Password1", roleId), CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(userId, result.Value);
|
||||
await _roleService.Received(1).ChangeUserRoleAsync(userId, roleId, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WithUnknownRole_ReturnsNotFoundAndDoesNotCreate()
|
||||
{
|
||||
_roleService.ListRolesAsync(Arg.Any<CancellationToken>()).Returns(new List<RoleDto>());
|
||||
|
||||
var result = await CreateHandler()
|
||||
.Handle(new CreateUserCommand("bob", "Password1", Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Equal(RoleErrors.NotFound, result.Error);
|
||||
await _identityService
|
||||
.DidNotReceive()
|
||||
.CreateUserAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user