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 LiteCqrs;
|
||||||
using TeleWave.Api.Common;
|
using TeleWave.Api.Common;
|
||||||
using TeleWave.Application.Admin.Users.BlockUser;
|
using TeleWave.Application.Admin.Users.BlockUser;
|
||||||
|
using TeleWave.Application.Admin.Users.CreateUser;
|
||||||
using TeleWave.Application.Admin.Users.DeleteUser;
|
using TeleWave.Application.Admin.Users.DeleteUser;
|
||||||
using TeleWave.Application.Admin.Users.GetUser;
|
using TeleWave.Application.Admin.Users.GetUser;
|
||||||
using TeleWave.Application.Admin.Users.ListUsers;
|
using TeleWave.Application.Admin.Users.ListUsers;
|
||||||
@@ -20,6 +21,7 @@ public static class AdminUserEndpoints
|
|||||||
.RequireAuthorization(policy => policy.RequireRole(RoleNames.Admin));
|
.RequireAuthorization(policy => policy.RequireRole(RoleNames.Admin));
|
||||||
|
|
||||||
admin.MapGet("", ListUsers).Produces<PagedList<UserSummaryDto>>();
|
admin.MapGet("", ListUsers).Produces<PagedList<UserSummaryDto>>();
|
||||||
|
admin.MapPost("", CreateUser).Produces<CreatedIdResponse>(StatusCodes.Status201Created);
|
||||||
admin.MapGet("/{id:guid}", GetUser).Produces<UserSummaryDto>();
|
admin.MapGet("/{id:guid}", GetUser).Produces<UserSummaryDto>();
|
||||||
admin
|
admin
|
||||||
.MapPost("/{id:guid}/block", BlockUser)
|
.MapPost("/{id:guid}/block", BlockUser)
|
||||||
@@ -49,6 +51,21 @@ public static class AdminUserEndpoints
|
|||||||
return Results.Ok(result);
|
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(
|
private static async Task<IResult> GetUser(
|
||||||
Guid id,
|
Guid id,
|
||||||
ISender sender,
|
ISender sender,
|
||||||
@@ -89,3 +106,5 @@ public static class AdminUserEndpoints
|
|||||||
return result.ToHttpResult();
|
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>());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,12 +4,14 @@ import { useTranslation } from 'react-i18next'
|
|||||||
import { HttpError } from '@/shared/api/client'
|
import { HttpError } from '@/shared/api/client'
|
||||||
import { Badge } from '@/shared/ui/badge'
|
import { Badge } from '@/shared/ui/badge'
|
||||||
import { Button } from '@/shared/ui/button'
|
import { Button } from '@/shared/ui/button'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'
|
||||||
import { Input } from '@/shared/ui/input'
|
import { Input } from '@/shared/ui/input'
|
||||||
|
import { Label } from '@/shared/ui/label'
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
|
||||||
import { toast } from '@/shared/ui/toast-store'
|
import { toast } from '@/shared/ui/toast-store'
|
||||||
import { changeUserRole } from '@/features/admin/roles/api'
|
import { changeUserRole } from '@/features/admin/roles/api'
|
||||||
import { listRoles } from '@/features/admin/roles/api'
|
import { listRoles } from '@/features/admin/roles/api'
|
||||||
import { blockUser, deleteUser, listUsers, unblockUser } from './api'
|
import { blockUser, createUser, deleteUser, listUsers, unblockUser } from './api'
|
||||||
|
|
||||||
const PAGE_SIZE = 20
|
const PAGE_SIZE = 20
|
||||||
|
|
||||||
@@ -19,6 +21,9 @@ export function UsersPanel() {
|
|||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
const [roleId, setRoleId] = useState<string>('')
|
const [roleId, setRoleId] = useState<string>('')
|
||||||
|
const [newUserName, setNewUserName] = useState('')
|
||||||
|
const [newPassword, setNewPassword] = useState('')
|
||||||
|
const [newRoleId, setNewRoleId] = useState('')
|
||||||
|
|
||||||
const { data: roles } = useQuery({ queryKey: ['admin', 'roles'], queryFn: listRoles })
|
const { data: roles } = useQuery({ queryKey: ['admin', 'roles'], queryFn: listRoles })
|
||||||
const { data, isLoading } = useQuery({
|
const { data, isLoading } = useQuery({
|
||||||
@@ -34,18 +39,90 @@ export function UsersPanel() {
|
|||||||
const unblockMutation = useMutation({ mutationFn: unblockUser, onSuccess: invalidate, onError })
|
const unblockMutation = useMutation({ mutationFn: unblockUser, onSuccess: invalidate, onError })
|
||||||
const deleteMutation = useMutation({ mutationFn: deleteUser, onSuccess: invalidate, onError })
|
const deleteMutation = useMutation({ mutationFn: deleteUser, onSuccess: invalidate, onError })
|
||||||
const changeRoleMutation = useMutation({
|
const changeRoleMutation = useMutation({
|
||||||
mutationFn: ({ userId, roleId: newRoleId }: { userId: string; roleId: string }) =>
|
mutationFn: ({ userId, roleId: nextRoleId }: { userId: string; roleId: string }) =>
|
||||||
changeUserRole(userId, newRoleId),
|
changeUserRole(userId, nextRoleId),
|
||||||
onSuccess: invalidate,
|
onSuccess: invalidate,
|
||||||
onError,
|
onError,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Роль по умолчанию для новой учётки — «user» (если есть), иначе первая роль.
|
||||||
|
const defaultRoleId = roles?.find((r) => r.name === 'user')?.id ?? roles?.[0]?.id ?? ''
|
||||||
|
const effectiveNewRoleId = newRoleId || defaultRoleId
|
||||||
|
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
createUser({
|
||||||
|
userName: newUserName.trim(),
|
||||||
|
password: newPassword,
|
||||||
|
roleId: effectiveNewRoleId,
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
setNewUserName('')
|
||||||
|
setNewPassword('')
|
||||||
|
setNewRoleId('')
|
||||||
|
toast.success(t('admin.users.created'))
|
||||||
|
invalidate()
|
||||||
|
},
|
||||||
|
onError,
|
||||||
|
})
|
||||||
|
|
||||||
|
const canCreate =
|
||||||
|
newUserName.trim().length >= 3 && newPassword.length >= 8 && effectiveNewRoleId !== ''
|
||||||
|
|
||||||
const totalPages = data ? Math.max(1, Math.ceil(data.total / PAGE_SIZE)) : 1
|
const totalPages = data ? Math.max(1, Math.ceil(data.total / PAGE_SIZE)) : 1
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
<h2 className="crt-glow text-xl font-semibold">{t('admin.users.title')}</h2>
|
<h2 className="crt-glow text-xl font-semibold">{t('admin.users.title')}</h2>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{t('admin.users.createTitle')}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-wrap items-end gap-3">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label>{t('admin.users.userName')}</Label>
|
||||||
|
<Input
|
||||||
|
className="w-56"
|
||||||
|
value={newUserName}
|
||||||
|
onChange={(e) => setNewUserName(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label>{t('admin.users.password')}</Label>
|
||||||
|
<Input
|
||||||
|
type="password"
|
||||||
|
className="w-56"
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => setNewPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label>{t('admin.users.role')}</Label>
|
||||||
|
<Select value={effectiveNewRoleId} onValueChange={setNewRoleId}>
|
||||||
|
<SelectTrigger className="w-40">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{roles?.map((role) => (
|
||||||
|
<SelectItem key={role.id} value={role.id}>
|
||||||
|
{role.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
disabled={!canCreate || createMutation.isPending}
|
||||||
|
onClick={() => createMutation.mutate()}
|
||||||
|
>
|
||||||
|
{t('admin.users.create')}
|
||||||
|
</Button>
|
||||||
|
<p className="w-full text-xs text-muted-foreground">{t('admin.users.passwordHint')}</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
<Input
|
<Input
|
||||||
className="max-w-xs"
|
className="max-w-xs"
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { apiRequest } from '@/shared/api/client'
|
import { apiRequest } from '@/shared/api/client'
|
||||||
import type { PagedList, UserSummaryDto } from '@/shared/api/types'
|
import type { CreatedIdResponse, PagedList, UserSummaryDto } from '@/shared/api/types'
|
||||||
|
|
||||||
export type ListUsersParams = {
|
export type ListUsersParams = {
|
||||||
page: number
|
page: number
|
||||||
@@ -21,6 +21,10 @@ export function listUsers(params: ListUsersParams) {
|
|||||||
return apiRequest<PagedList<UserSummaryDto>>(`/admin/users?${query.toString()}`)
|
return apiRequest<PagedList<UserSummaryDto>>(`/admin/users?${query.toString()}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function createUser(body: { userName: string; password: string; roleId: string }) {
|
||||||
|
return apiRequest<CreatedIdResponse>('/admin/users', { method: 'POST', body })
|
||||||
|
}
|
||||||
|
|
||||||
export function blockUser(id: string) {
|
export function blockUser(id: string) {
|
||||||
return apiRequest<void>(`/admin/users/${id}/block`, { method: 'POST' })
|
return apiRequest<void>(`/admin/users/${id}/block`, { method: 'POST' })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,6 +105,11 @@ const resources = {
|
|||||||
block: 'Заблокировать',
|
block: 'Заблокировать',
|
||||||
unblock: 'Разблокировать',
|
unblock: 'Разблокировать',
|
||||||
filterAll: 'Все роли',
|
filterAll: 'Все роли',
|
||||||
|
createTitle: 'Создать пользователя',
|
||||||
|
password: 'Пароль',
|
||||||
|
passwordHint: 'Минимум 8 символов, хотя бы одна цифра и заглавная буква.',
|
||||||
|
create: 'Создать',
|
||||||
|
created: 'Пользователь создан',
|
||||||
},
|
},
|
||||||
media: {
|
media: {
|
||||||
title: 'Медиа',
|
title: 'Медиа',
|
||||||
@@ -344,6 +349,11 @@ const resources = {
|
|||||||
block: 'Block',
|
block: 'Block',
|
||||||
unblock: 'Unblock',
|
unblock: 'Unblock',
|
||||||
filterAll: 'All roles',
|
filterAll: 'All roles',
|
||||||
|
createTitle: 'Create user',
|
||||||
|
password: 'Password',
|
||||||
|
passwordHint: 'At least 8 characters, including a digit and an uppercase letter.',
|
||||||
|
create: 'Create',
|
||||||
|
created: 'User created',
|
||||||
},
|
},
|
||||||
media: {
|
media: {
|
||||||
title: 'Media',
|
title: 'Media',
|
||||||
|
|||||||
Reference in New Issue
Block a user