roles update
This commit is contained in:
@@ -21,7 +21,7 @@ import { ChatController } from './controllers/chat.controller';
|
|||||||
import { NotificationsController } from './controllers/notifications.controller';
|
import { NotificationsController } from './controllers/notifications.controller';
|
||||||
import { MediaController } from './controllers/media.controller';
|
import { MediaController } from './controllers/media.controller';
|
||||||
import { CoreGrpcService } from './core-grpc.service';
|
import { CoreGrpcService } from './core-grpc.service';
|
||||||
import { AdminGuard, SuperAdminGuard } from './guards/admin.guard';
|
import { AdminGuard, RbacManageGuard, SuperAdminGuard } from './guards/admin.guard';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -56,6 +56,6 @@ import { AdminGuard, SuperAdminGuard } from './guards/admin.guard';
|
|||||||
])
|
])
|
||||||
],
|
],
|
||||||
controllers: [AuthController, AdminController, RbacController, SecurityController, SettingsController, PublicSettingsController, HealthController, ProfileController, DocumentsController, AddressesController, OAuthController, WellKnownController, OAuthAuthorizeDiscoveryController, AdvancedAuthController, FamilyController, ChatController, NotificationsController, MediaController],
|
controllers: [AuthController, AdminController, RbacController, SecurityController, SettingsController, PublicSettingsController, HealthController, ProfileController, DocumentsController, AddressesController, OAuthController, WellKnownController, OAuthAuthorizeDiscoveryController, AdvancedAuthController, FamilyController, ChatController, NotificationsController, MediaController],
|
||||||
providers: [CoreGrpcService, AdminGuard, SuperAdminGuard]
|
providers: [CoreGrpcService, AdminGuard, RbacManageGuard, SuperAdminGuard]
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -3,8 +3,22 @@ import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs
|
|||||||
import { map } from 'rxjs';
|
import { map } from 'rxjs';
|
||||||
import { CoreGrpcService } from '../core-grpc.service';
|
import { CoreGrpcService } from '../core-grpc.service';
|
||||||
import { CurrentAdmin } from '../decorators/current-admin.decorator';
|
import { CurrentAdmin } from '../decorators/current-admin.decorator';
|
||||||
import { AssignUserRoleDto, CreateOAuthClientDto, CreateRoleDto, UpdateOAuthClientDto } from '../dto/rbac.dto';
|
import {
|
||||||
import { AdminGuard, AdminRequestUser, assertAdminAnyPermission, assertAdminPermission, SuperAdminGuard } from '../guards/admin.guard';
|
AssignUserPermissionDto,
|
||||||
|
AssignUserRoleDto,
|
||||||
|
CreateOAuthClientDto,
|
||||||
|
CreateRoleDto,
|
||||||
|
UpdateOAuthClientDto,
|
||||||
|
UpdateRoleDto
|
||||||
|
} from '../dto/rbac.dto';
|
||||||
|
import {
|
||||||
|
AdminGuard,
|
||||||
|
AdminRequestUser,
|
||||||
|
assertAdminAnyPermission,
|
||||||
|
assertAdminPermission,
|
||||||
|
RbacManageGuard,
|
||||||
|
SuperAdminGuard
|
||||||
|
} from '../guards/admin.guard';
|
||||||
|
|
||||||
@ApiTags('RBAC и OAuth')
|
@ApiTags('RBAC и OAuth')
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@@ -30,7 +44,7 @@ export class RbacController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get('permissions')
|
@Get('permissions')
|
||||||
@UseGuards(SuperAdminGuard)
|
@UseGuards(RbacManageGuard)
|
||||||
@ApiOperation({ summary: 'Список прав', description: 'Возвращает все доступные permissions.' })
|
@ApiOperation({ summary: 'Список прав', description: 'Возвращает все доступные permissions.' })
|
||||||
listPermissions() {
|
listPermissions() {
|
||||||
return this.core.rbac.ListPermissions({});
|
return this.core.rbac.ListPermissions({});
|
||||||
@@ -51,16 +65,33 @@ export class RbacController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post('roles')
|
@Post('roles')
|
||||||
@UseGuards(SuperAdminGuard)
|
@UseGuards(RbacManageGuard)
|
||||||
@ApiOperation({ summary: 'Создать роль', description: 'Создаёт новую роль с набором прав. Только супер-администратор.' })
|
@ApiOperation({ summary: 'Создать роль', description: 'Создаёт новую роль с набором прав.' })
|
||||||
@ApiBody({ type: CreateRoleDto })
|
@ApiBody({ type: CreateRoleDto })
|
||||||
createRole(@Body() dto: CreateRoleDto, @CurrentAdmin() admin: AdminRequestUser) {
|
createRole(@Body() dto: CreateRoleDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||||
return this.core.rbac.CreateRole({ actorUserId: admin.id, ...dto });
|
return this.core.rbac.CreateRole({ actorUserId: admin.id, ...dto });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Patch('roles/:roleSlug')
|
||||||
|
@UseGuards(RbacManageGuard)
|
||||||
|
@ApiOperation({ summary: 'Обновить роль', description: 'Изменяет название, описание и права роли.' })
|
||||||
|
@ApiParam({ name: 'roleSlug', description: 'Slug роли' })
|
||||||
|
@ApiBody({ type: UpdateRoleDto })
|
||||||
|
updateRole(@Param('roleSlug') roleSlug: string, @Body() dto: UpdateRoleDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||||
|
return this.core.rbac.UpdateRole({ actorUserId: admin.id, roleSlug, ...dto });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('roles/:roleSlug')
|
||||||
|
@UseGuards(RbacManageGuard)
|
||||||
|
@ApiOperation({ summary: 'Удалить роль', description: 'Удаляет пользовательскую роль. Системные роли удалить нельзя.' })
|
||||||
|
@ApiParam({ name: 'roleSlug', description: 'Slug роли' })
|
||||||
|
deleteRole(@Param('roleSlug') roleSlug: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||||
|
return this.core.rbac.DeleteRole({ actorUserId: admin.id, roleSlug });
|
||||||
|
}
|
||||||
|
|
||||||
@Post('users/:userId/roles')
|
@Post('users/:userId/roles')
|
||||||
@UseGuards(SuperAdminGuard)
|
@UseGuards(RbacManageGuard)
|
||||||
@ApiOperation({ summary: 'Назначить роль пользователю', description: 'Только супер-администратор может назначать роли.' })
|
@ApiOperation({ summary: 'Назначить роль пользователю' })
|
||||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||||
@ApiBody({ type: AssignUserRoleDto })
|
@ApiBody({ type: AssignUserRoleDto })
|
||||||
assignRole(@Param('userId') userId: string, @Body() dto: AssignUserRoleDto, @CurrentAdmin() admin: AdminRequestUser) {
|
assignRole(@Param('userId') userId: string, @Body() dto: AssignUserRoleDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||||
@@ -68,14 +99,36 @@ export class RbacController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Delete('users/:userId/roles/:roleSlug')
|
@Delete('users/:userId/roles/:roleSlug')
|
||||||
@UseGuards(SuperAdminGuard)
|
@UseGuards(RbacManageGuard)
|
||||||
@ApiOperation({ summary: 'Снять роль с пользователя', description: 'Только супер-администратор может снимать роли.' })
|
@ApiOperation({ summary: 'Снять роль с пользователя' })
|
||||||
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||||
@ApiParam({ name: 'roleSlug', description: 'Slug роли' })
|
@ApiParam({ name: 'roleSlug', description: 'Slug роли' })
|
||||||
removeRole(@Param('userId') userId: string, @Param('roleSlug') roleSlug: string, @CurrentAdmin() admin: AdminRequestUser) {
|
removeRole(@Param('userId') userId: string, @Param('roleSlug') roleSlug: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||||
return this.core.rbac.RemoveUserRole({ actorUserId: admin.id, userId, roleSlug });
|
return this.core.rbac.RemoveUserRole({ actorUserId: admin.id, userId, roleSlug });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('users/:userId/permissions')
|
||||||
|
@UseGuards(RbacManageGuard)
|
||||||
|
@ApiOperation({ summary: 'Назначить право пользователю', description: 'Прямое назначение permission без смены роли.' })
|
||||||
|
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||||
|
@ApiBody({ type: AssignUserPermissionDto })
|
||||||
|
assignPermission(@Param('userId') userId: string, @Body() dto: AssignUserPermissionDto, @CurrentAdmin() admin: AdminRequestUser) {
|
||||||
|
return this.core.rbac.AssignUserPermission({ actorUserId: admin.id, userId, permissionSlug: dto.permissionSlug });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('users/:userId/permissions/:permissionSlug')
|
||||||
|
@UseGuards(RbacManageGuard)
|
||||||
|
@ApiOperation({ summary: 'Снять право с пользователя' })
|
||||||
|
@ApiParam({ name: 'userId', description: 'ID пользователя' })
|
||||||
|
@ApiParam({ name: 'permissionSlug', description: 'Slug права' })
|
||||||
|
removePermission(
|
||||||
|
@Param('userId') userId: string,
|
||||||
|
@Param('permissionSlug') permissionSlug: string,
|
||||||
|
@CurrentAdmin() admin: AdminRequestUser
|
||||||
|
) {
|
||||||
|
return this.core.rbac.RemoveUserPermission({ actorUserId: admin.id, userId, permissionSlug });
|
||||||
|
}
|
||||||
|
|
||||||
@Post('oauth-clients')
|
@Post('oauth-clients')
|
||||||
@ApiOperation({ summary: 'Создать OAuth-приложение', description: 'Создаёт OAuth2-клиент и возвращает client secret один раз.' })
|
@ApiOperation({ summary: 'Создать OAuth-приложение', description: 'Создаёт OAuth2-клиент и возвращает client secret один раз.' })
|
||||||
@ApiBody({ type: CreateOAuthClientDto })
|
@ApiBody({ type: CreateOAuthClientDto })
|
||||||
@@ -93,6 +146,14 @@ export class RbacController {
|
|||||||
return this.core.rbac.UpdateOAuthClient({ actorUserId: admin.id, clientId, ...dto });
|
return this.core.rbac.UpdateOAuthClient({ actorUserId: admin.id, clientId, ...dto });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Delete('oauth-clients/:clientId')
|
||||||
|
@ApiOperation({ summary: 'Удалить OAuth-приложение', description: 'Полностью удаляет OAuth2-клиент и связанные данные.' })
|
||||||
|
@ApiParam({ name: 'clientId', description: 'Client ID приложения' })
|
||||||
|
deleteOAuthClient(@Param('clientId') clientId: string, @CurrentAdmin() admin: AdminRequestUser) {
|
||||||
|
assertAdminPermission(admin, 'canManageOAuth');
|
||||||
|
return this.core.rbac.DeleteOAuthClient({ actorUserId: admin.id, clientId });
|
||||||
|
}
|
||||||
|
|
||||||
@Post('oauth-clients/:clientId/rotate-secret')
|
@Post('oauth-clients/:clientId/rotate-secret')
|
||||||
@ApiOperation({ summary: 'Перевыпустить client secret', description: 'Генерирует новый secret для confidential-клиента.' })
|
@ApiOperation({ summary: 'Перевыпустить client secret', description: 'Генерирует новый secret для confidential-клиента.' })
|
||||||
@ApiParam({ name: 'clientId', description: 'Client ID приложения' })
|
@ApiParam({ name: 'clientId', description: 'Client ID приложения' })
|
||||||
|
|||||||
@@ -33,6 +33,30 @@ export class AssignUserRoleDto {
|
|||||||
roleSlug!: string;
|
roleSlug!: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class AssignUserPermissionDto {
|
||||||
|
@ApiProperty({ description: 'Slug права', example: 'oauth.manage' })
|
||||||
|
@IsString({ message: 'Slug права должен быть строкой' })
|
||||||
|
permissionSlug!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateRoleDto {
|
||||||
|
@ApiPropertyOptional({ description: 'Название роли' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString({ message: 'Название роли должно быть строкой' })
|
||||||
|
name?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ description: 'Описание роли' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString({ message: 'Описание должно быть строкой' })
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ description: 'Список slug прав', type: [String] })
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray({ message: 'Права должны быть массивом' })
|
||||||
|
@IsString({ each: true, message: 'Каждое право должно быть строкой' })
|
||||||
|
permissionSlugs?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
export class CreateOAuthClientDto {
|
export class CreateOAuthClientDto {
|
||||||
@ApiProperty({ description: 'Название приложения', example: 'Lendry Docs' })
|
@ApiProperty({ description: 'Название приложения', example: 'Lendry Docs' })
|
||||||
@IsString({ message: 'Название должно быть строкой' })
|
@IsString({ message: 'Название должно быть строкой' })
|
||||||
|
|||||||
@@ -66,6 +66,17 @@ export class AdminGuard implements CanActivate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RbacManageGuard implements CanActivate {
|
||||||
|
canActivate(context: ExecutionContext): boolean {
|
||||||
|
const request = context.switchToHttp().getRequest<{ adminUser?: AdminRequestUser }>();
|
||||||
|
if (request.adminUser?.isSuperAdmin || request.adminUser?.canManageRoles) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
throw new ForbiddenException('Недостаточно прав для управления ролями и правами');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SuperAdminGuard implements CanActivate {
|
export class SuperAdminGuard implements CanActivate {
|
||||||
canActivate(context: ExecutionContext): boolean {
|
canActivate(context: ExecutionContext): boolean {
|
||||||
|
|||||||
@@ -133,6 +133,19 @@ export default function AdminOAuthPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleDeleteClient(client: OAuthClient) {
|
||||||
|
if (!token) return;
|
||||||
|
if (!window.confirm(`Удалить приложение «${client.name}»? Это действие необратимо.`)) return;
|
||||||
|
try {
|
||||||
|
await apiFetch(`/admin/rbac/oauth-clients/${client.clientId}`, { method: 'DELETE' }, token);
|
||||||
|
showToast('Приложение удалено');
|
||||||
|
setSelectedClient(null);
|
||||||
|
await loadData();
|
||||||
|
} catch (error) {
|
||||||
|
showToast(error instanceof Error ? error.message : 'Не удалось удалить приложение');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function copyText(value: string, label: string) {
|
function copyText(value: string, label: string) {
|
||||||
void navigator.clipboard.writeText(value);
|
void navigator.clipboard.writeText(value);
|
||||||
showToast(`${label} скопирован`);
|
showToast(`${label} скопирован`);
|
||||||
@@ -213,6 +226,7 @@ export default function AdminOAuthPage() {
|
|||||||
onCopy={copyText}
|
onCopy={copyText}
|
||||||
onRotateSecret={(clientId) => void handleRotateSecret(clientId)}
|
onRotateSecret={(clientId) => void handleRotateSecret(clientId)}
|
||||||
onToggleActive={(client) => void handleToggleActive(client)}
|
onToggleActive={(client) => void handleToggleActive(client)}
|
||||||
|
onDelete={(client) => void handleDeleteClient(client)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { Loader2, Plus, ShieldCheck } from 'lucide-react';
|
import { Loader2, Pencil, Plus, ShieldCheck, Trash2 } from 'lucide-react';
|
||||||
import { AdminShell } from '@/components/id/admin-shell';
|
import { AdminShell } from '@/components/id/admin-shell';
|
||||||
import { useAuth } from '@/components/id/auth-provider';
|
import { useAuth } from '@/components/id/auth-provider';
|
||||||
import { useToast } from '@/components/id/toast-provider';
|
import { useToast } from '@/components/id/toast-provider';
|
||||||
@@ -11,15 +11,31 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
|
|||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { AdminPermission, AdminRole, apiFetch } from '@/lib/api';
|
import { AdminPermission, AdminRole, apiFetch } from '@/lib/api';
|
||||||
|
|
||||||
|
type RoleFormState = {
|
||||||
|
slug: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
permissionSlugs: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const emptyForm: RoleFormState = { slug: '', name: '', description: '', permissionSlugs: [] };
|
||||||
|
|
||||||
export default function AdminRbacPage() {
|
export default function AdminRbacPage() {
|
||||||
const { token, user } = useAuth();
|
const { token, user } = useAuth();
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
const [roles, setRoles] = useState<AdminRole[]>([]);
|
const [roles, setRoles] = useState<AdminRole[]>([]);
|
||||||
const [permissions, setPermissions] = useState<AdminPermission[]>([]);
|
const [permissions, setPermissions] = useState<AdminPermission[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [creating, setCreating] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [dialogOpen, setDialogOpen] = useState(false);
|
const [dialogOpen, setDialogOpen] = useState(false);
|
||||||
const [form, setForm] = useState({ slug: '', name: '', description: '', permissionSlugs: [] as string[] });
|
const [editingRole, setEditingRole] = useState<AdminRole | null>(null);
|
||||||
|
const [form, setForm] = useState<RoleFormState>(emptyForm);
|
||||||
|
|
||||||
|
async function reloadRoles() {
|
||||||
|
if (!token) return;
|
||||||
|
const response = await apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token);
|
||||||
|
setRoles(response.roles ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!token || !user?.canManageRoles) return;
|
if (!token || !user?.canManageRoles) return;
|
||||||
@@ -35,30 +51,74 @@ export default function AdminRbacPage() {
|
|||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
}, [showToast, token, user?.canManageRoles]);
|
}, [showToast, token, user?.canManageRoles]);
|
||||||
|
|
||||||
async function handleCreateRole() {
|
function openCreateDialog() {
|
||||||
|
setEditingRole(null);
|
||||||
|
setForm(emptyForm);
|
||||||
|
setDialogOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditDialog(role: AdminRole) {
|
||||||
|
setEditingRole(role);
|
||||||
|
setForm({
|
||||||
|
slug: role.slug,
|
||||||
|
name: role.name,
|
||||||
|
description: role.description ?? '',
|
||||||
|
permissionSlugs: role.permissions.map((permission) => permission.slug)
|
||||||
|
});
|
||||||
|
setDialogOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSaveRole() {
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
setCreating(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
|
if (editingRole) {
|
||||||
|
await apiFetch(`/admin/rbac/roles/${editingRole.slug}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: form.name,
|
||||||
|
description: form.description || undefined,
|
||||||
|
permissionSlugs: form.permissionSlugs
|
||||||
|
})
|
||||||
|
}, token);
|
||||||
|
showToast('Роль обновлена');
|
||||||
|
} else {
|
||||||
await apiFetch('/admin/rbac/roles', {
|
await apiFetch('/admin/rbac/roles', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify(form)
|
body: JSON.stringify(form)
|
||||||
}, token);
|
}, token);
|
||||||
showToast('Роль создана');
|
showToast('Роль создана');
|
||||||
|
}
|
||||||
setDialogOpen(false);
|
setDialogOpen(false);
|
||||||
setForm({ slug: '', name: '', description: '', permissionSlugs: [] });
|
setForm(emptyForm);
|
||||||
const response = await apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token);
|
setEditingRole(null);
|
||||||
setRoles(response.roles ?? []);
|
await reloadRoles();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showToast(error instanceof Error ? error.message : 'Не удалось создать роль');
|
showToast(error instanceof Error ? error.message : 'Не удалось сохранить роль');
|
||||||
} finally {
|
} finally {
|
||||||
setCreating(false);
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDeleteRole(role: AdminRole) {
|
||||||
|
if (!token || role.isSystem) return;
|
||||||
|
if (!window.confirm(`Удалить роль «${role.name}»? Она будет снята со всех пользователей.`)) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await apiFetch(`/admin/rbac/roles/${role.slug}`, { method: 'DELETE' }, token);
|
||||||
|
showToast('Роль удалена');
|
||||||
|
await reloadRoles();
|
||||||
|
} catch (error) {
|
||||||
|
showToast(error instanceof Error ? error.message : 'Не удалось удалить роль');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!user?.canManageRoles) {
|
if (!user?.canManageRoles) {
|
||||||
return (
|
return (
|
||||||
<AdminShell active="/admin/rbac">
|
<AdminShell active="/admin/rbac">
|
||||||
<p className="text-[#667085]">Управление ролями доступно только супер-администратору.</p>
|
<p className="text-[#667085]">Управление ролями доступно пользователям с правом rbac.manage.</p>
|
||||||
</AdminShell>
|
</AdminShell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -68,9 +128,9 @@ export default function AdminRbacPage() {
|
|||||||
<div className="mb-6 flex items-center justify-between gap-4">
|
<div className="mb-6 flex items-center justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-2xl font-medium">Роли и права</h2>
|
<h2 className="text-2xl font-medium">Роли и права</h2>
|
||||||
<p className="text-sm text-[#667085]">Только супер-администратор может создавать роли и назначать их пользователям</p>
|
<p className="text-sm text-[#667085]">Редактируйте роли, назначайте права всем пользователям или отдельным аккаунтам</p>
|
||||||
</div>
|
</div>
|
||||||
<Button onClick={() => setDialogOpen(true)}>
|
<Button onClick={openCreateDialog}>
|
||||||
<Plus className="h-4 w-4" />
|
<Plus className="h-4 w-4" />
|
||||||
Создать роль
|
Создать роль
|
||||||
</Button>
|
</Button>
|
||||||
@@ -86,17 +146,37 @@ export default function AdminRbacPage() {
|
|||||||
{roles.map((role) => (
|
{roles.map((role) => (
|
||||||
<Card key={role.id} className="bg-[#f8f9fb] shadow-none">
|
<Card key={role.id} className="bg-[#f8f9fb] shadow-none">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<ShieldCheck className="h-6 w-6" />
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<ShieldCheck className="h-6 w-6 shrink-0" />
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Редактировать роль" onClick={() => openEditDialog(role)}>
|
||||||
|
<Pencil className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
{!role.isSystem ? (
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Удалить роль" disabled={saving} onClick={() => void handleDeleteRole(role)}>
|
||||||
|
<Trash2 className="h-4 w-4 text-red-600" />
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<CardTitle>{role.name}</CardTitle>
|
<CardTitle>{role.name}</CardTitle>
|
||||||
<CardDescription>{role.permissions.length} прав · {role.slug}</CardDescription>
|
<CardDescription>
|
||||||
|
{role.permissions.length} прав · {role.slug}
|
||||||
|
{role.isSystem ? ' · системная' : ''}
|
||||||
|
{role.isDefault ? ' · по умолчанию' : ''}
|
||||||
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-2">
|
<CardContent className="space-y-2">
|
||||||
{role.permissions.map((permission) => (
|
{role.permissions.length ? (
|
||||||
|
role.permissions.map((permission) => (
|
||||||
<div key={permission.id} className="rounded-xl bg-white px-3 py-2 text-sm">
|
<div key={permission.id} className="rounded-xl bg-white px-3 py-2 text-sm">
|
||||||
<div className="font-medium">{permission.name}</div>
|
<div className="font-medium">{permission.name}</div>
|
||||||
<div className="text-xs text-[#667085]">{permission.slug}</div>
|
<div className="text-xs text-[#667085]">{permission.slug}</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-[#667085]">Права не назначены</p>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
))}
|
))}
|
||||||
@@ -106,10 +186,14 @@ export default function AdminRbacPage() {
|
|||||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Новая роль</DialogTitle>
|
<DialogTitle>{editingRole ? `Редактирование: ${editingRole.name}` : 'Новая роль'}</DialogTitle>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{!editingRole ? (
|
||||||
<Input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="slug, например support" />
|
<Input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="slug, например support" />
|
||||||
|
) : (
|
||||||
|
<p className="rounded-xl bg-[#f4f5f8] px-3 py-2 text-sm text-[#667085]">Slug: {editingRole.slug}</p>
|
||||||
|
)}
|
||||||
<Input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} placeholder="Название роли" />
|
<Input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} placeholder="Название роли" />
|
||||||
<Input value={form.description} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} placeholder="Описание" />
|
<Input value={form.description} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} placeholder="Описание" />
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -132,8 +216,8 @@ export default function AdminRbacPage() {
|
|||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<Button className="w-full" disabled={creating} onClick={() => void handleCreateRole()}>
|
<Button className="w-full" disabled={saving || !form.name.trim() || (!editingRole && !form.slug.trim())} onClick={() => void handleSaveRole()}>
|
||||||
{creating ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Создать роль'}
|
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : editingRole ? 'Сохранить изменения' : 'Создать роль'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { Button } from '@/components/ui/button';
|
|||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||||
import { AdminRole, AdminUser, apiFetch } from '@/lib/api';
|
import { AdminPermission, AdminRole, AdminUser, apiFetch } from '@/lib/api';
|
||||||
import { getAdminLandingPath } from '@/lib/admin-access';
|
import { getAdminLandingPath } from '@/lib/admin-access';
|
||||||
|
|
||||||
const statusLabels: Record<string, string> = {
|
const statusLabels: Record<string, string> = {
|
||||||
@@ -21,18 +21,22 @@ const statusLabels: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const roleLabels: Record<string, string> = {
|
const roleLabels: Record<string, string> = {
|
||||||
|
user: 'Пользователь',
|
||||||
admin: 'Администратор',
|
admin: 'Администратор',
|
||||||
moderator: 'Модератор',
|
moderator: 'Модератор',
|
||||||
manager: 'Менеджер',
|
manager: 'Менеджер',
|
||||||
'super-admin': 'Супер-админ'
|
'super-admin': 'Супер-админ'
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const DEFAULT_USER_ROLE = 'user';
|
||||||
|
|
||||||
export default function AdminUsersPage() {
|
export default function AdminUsersPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { token, user: currentUser } = useAuth();
|
const { token, user: currentUser } = useAuth();
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
const [users, setUsers] = useState<AdminUser[]>([]);
|
const [users, setUsers] = useState<AdminUser[]>([]);
|
||||||
const [roles, setRoles] = useState<AdminRole[]>([]);
|
const [roles, setRoles] = useState<AdminRole[]>([]);
|
||||||
|
const [permissions, setPermissions] = useState<AdminPermission[]>([]);
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
|
const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
|
||||||
@@ -68,12 +72,26 @@ export default function AdminUsersPage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!token || !currentUser?.canManageRoles) return;
|
if (!token || !currentUser?.canManageRoles) return;
|
||||||
apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token)
|
Promise.all([
|
||||||
.then((response) => setRoles(response.roles ?? []))
|
apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token),
|
||||||
|
apiFetch<{ permissions: AdminPermission[] }>('/admin/rbac/permissions', {}, token)
|
||||||
|
])
|
||||||
|
.then(([rolesResponse, permissionsResponse]) => {
|
||||||
|
setRoles(rolesResponse.roles ?? []);
|
||||||
|
setPermissions(permissionsResponse.permissions ?? []);
|
||||||
|
})
|
||||||
.catch(() => undefined);
|
.catch(() => undefined);
|
||||||
}, [currentUser?.canManageRoles, token]);
|
}, [currentUser?.canManageRoles, token]);
|
||||||
|
|
||||||
const assignableRoles = useMemo(() => roles.filter((role) => role.slug !== 'super-admin'), [roles]);
|
const assignableRoles = useMemo(
|
||||||
|
() => roles.filter((role) => role.slug !== 'super-admin' && !role.isDefault),
|
||||||
|
[roles]
|
||||||
|
);
|
||||||
|
|
||||||
|
const permissionLabelBySlug = useMemo(
|
||||||
|
() => Object.fromEntries(permissions.map((permission) => [permission.slug, permission.name])),
|
||||||
|
[permissions]
|
||||||
|
);
|
||||||
|
|
||||||
async function handleSuspend(user: AdminUser) {
|
async function handleSuspend(user: AdminUser) {
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
@@ -171,11 +189,52 @@ export default function AdminUsersPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleAssignPermission(permissionSlug: string) {
|
||||||
|
if (!token || !selectedUser) return;
|
||||||
|
setActionLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await apiFetch<{ permissions: string[] }>(`/admin/rbac/users/${selectedUser.id}/permissions`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ permissionSlug })
|
||||||
|
}, token);
|
||||||
|
setSelectedUser({ ...selectedUser, directPermissions: response.permissions ?? [] });
|
||||||
|
showToast('Право назначено');
|
||||||
|
await loadUsers();
|
||||||
|
} catch (error) {
|
||||||
|
showToast(error instanceof Error ? error.message : 'Не удалось назначить право');
|
||||||
|
} finally {
|
||||||
|
setActionLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRemovePermission(permissionSlug: string) {
|
||||||
|
if (!token || !selectedUser) return;
|
||||||
|
setActionLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await apiFetch<{ permissions: string[] }>(`/admin/rbac/users/${selectedUser.id}/permissions/${permissionSlug}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
}, token);
|
||||||
|
setSelectedUser({ ...selectedUser, directPermissions: response.permissions ?? [] });
|
||||||
|
showToast('Право снято');
|
||||||
|
await loadUsers();
|
||||||
|
} catch (error) {
|
||||||
|
showToast(error instanceof Error ? error.message : 'Не удалось снять право');
|
||||||
|
} finally {
|
||||||
|
setActionLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function renderRoles(user: AdminUser) {
|
function renderRoles(user: AdminUser) {
|
||||||
const userRoles = user.roles ?? [];
|
const userRoles = user.roles ?? [];
|
||||||
const labels = user.isSuperAdmin ? ['Супер-админ', ...userRoles.map((role) => roleLabels[role] ?? role)] : userRoles.map((role) => roleLabels[role] ?? role);
|
const extraRoles = userRoles.filter((role) => role !== DEFAULT_USER_ROLE);
|
||||||
if (!labels.length) return 'Пользователь';
|
const direct = user.directPermissions ?? [];
|
||||||
return labels.join(', ');
|
const labels = user.isSuperAdmin
|
||||||
|
? ['Супер-админ', ...extraRoles.map((role) => roleLabels[role] ?? role)]
|
||||||
|
: extraRoles.map((role) => roleLabels[role] ?? role);
|
||||||
|
const directLabels = direct.map((slug) => permissionLabelBySlug[slug] ?? slug);
|
||||||
|
const parts = [...labels, ...directLabels.map((label) => `+ ${label}`)];
|
||||||
|
if (!parts.length) return roleLabels.user;
|
||||||
|
return parts.join(', ');
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -312,10 +371,14 @@ export default function AdminUsersPage() {
|
|||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{(selectedUser?.roles ?? []).map((role) => (
|
{(selectedUser?.roles ?? []).map((role) => (
|
||||||
<div key={role} className="flex items-center justify-between rounded-xl bg-[#f4f5f8] px-3 py-2">
|
<div key={role} className="flex items-center justify-between rounded-xl bg-[#f4f5f8] px-3 py-2">
|
||||||
<span>{roleLabels[role] ?? role}</span>
|
<span>{roleLabels[role] ?? role}{role === DEFAULT_USER_ROLE ? ' (стандартная)' : ''}</span>
|
||||||
|
{role === DEFAULT_USER_ROLE ? (
|
||||||
|
<span className="text-xs text-[#667085]">Нельзя снять</span>
|
||||||
|
) : (
|
||||||
<Button variant="ghost" size="sm" disabled={actionLoading} onClick={() => void handleRemoveRole(role)}>
|
<Button variant="ghost" size="sm" disabled={actionLoading} onClick={() => void handleRemoveRole(role)}>
|
||||||
Снять
|
Снять
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{!(selectedUser?.roles ?? []).length ? <p className="text-sm text-[#667085]">Роли не назначены</p> : null}
|
{!(selectedUser?.roles ?? []).length ? <p className="text-sm text-[#667085]">Роли не назначены</p> : null}
|
||||||
@@ -335,6 +398,37 @@ export default function AdminUsersPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="mt-6 space-y-2 border-t border-[#eceef4] pt-4">
|
||||||
|
<p className="text-sm font-medium">Прямые права</p>
|
||||||
|
<p className="text-xs text-[#667085]">Дополнительные permissions без смены роли. Например, oauth.manage для одного пользователя.</p>
|
||||||
|
{(selectedUser?.directPermissions ?? []).map((permissionSlug) => (
|
||||||
|
<div key={permissionSlug} className="flex items-center justify-between rounded-xl bg-[#eef4ff] px-3 py-2">
|
||||||
|
<span className="text-sm">{permissionLabelBySlug[permissionSlug] ?? permissionSlug}</span>
|
||||||
|
<Button variant="ghost" size="sm" disabled={actionLoading} onClick={() => void handleRemovePermission(permissionSlug)}>
|
||||||
|
Снять
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{!(selectedUser?.directPermissions ?? []).length ? (
|
||||||
|
<p className="text-sm text-[#667085]">Прямые права не назначены</p>
|
||||||
|
) : null}
|
||||||
|
<div className="max-h-48 space-y-1 overflow-y-auto pt-2">
|
||||||
|
{permissions
|
||||||
|
.filter((permission) => !(selectedUser?.directPermissions ?? []).includes(permission.slug))
|
||||||
|
.map((permission) => (
|
||||||
|
<Button
|
||||||
|
key={permission.id}
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
className="w-full justify-start"
|
||||||
|
disabled={actionLoading}
|
||||||
|
onClick={() => void handleAssignPermission(permission.slug)}
|
||||||
|
>
|
||||||
|
+ {permission.name}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { Copy, ExternalLink, KeyRound, RefreshCw } from 'lucide-react';
|
import { Copy, ExternalLink, KeyRound, RefreshCw, Trash2 } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
import { OAuthClient } from '@/lib/api';
|
import { OAuthClient } from '@/lib/api';
|
||||||
@@ -27,7 +27,8 @@ export function OAuthClientDetailDialog({
|
|||||||
onOpenChange,
|
onOpenChange,
|
||||||
onCopy,
|
onCopy,
|
||||||
onRotateSecret,
|
onRotateSecret,
|
||||||
onToggleActive
|
onToggleActive,
|
||||||
|
onDelete
|
||||||
}: {
|
}: {
|
||||||
client: OAuthClient | null;
|
client: OAuthClient | null;
|
||||||
endpoints: OAuthEndpoints;
|
endpoints: OAuthEndpoints;
|
||||||
@@ -36,6 +37,7 @@ export function OAuthClientDetailDialog({
|
|||||||
onCopy: (value: string, label: string) => void;
|
onCopy: (value: string, label: string) => void;
|
||||||
onRotateSecret: (clientId: string) => void;
|
onRotateSecret: (clientId: string) => void;
|
||||||
onToggleActive: (client: OAuthClient) => void;
|
onToggleActive: (client: OAuthClient) => void;
|
||||||
|
onDelete: (client: OAuthClient) => void;
|
||||||
}) {
|
}) {
|
||||||
if (!client) return null;
|
if (!client) return null;
|
||||||
|
|
||||||
@@ -125,6 +127,15 @@ export function OAuthClientDetailDialog({
|
|||||||
<Button variant="secondary" size="sm" onClick={() => onToggleActive(client)}>
|
<Button variant="secondary" size="sm" onClick={() => onToggleActive(client)}>
|
||||||
{client.isActive ? 'Отключить' : 'Включить'}
|
{client.isActive ? 'Отключить' : 'Включить'}
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
className="text-red-600 hover:text-red-700"
|
||||||
|
onClick={() => onDelete(client)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
Удалить
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -63,6 +63,9 @@ export function NotificationBell() {
|
|||||||
if (event.type === 'family_invite') {
|
if (event.type === 'family_invite') {
|
||||||
showToast(event.message || 'Новое приглашение в семью');
|
showToast(event.message || 'Новое приглашение в семью');
|
||||||
}
|
}
|
||||||
|
if (event.type === 'role_assigned' || event.type === 'role_removed') {
|
||||||
|
showToast(event.message || 'Изменение ролей');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}, [load, showToast, subscribe]);
|
}, [load, showToast, subscribe]);
|
||||||
|
|
||||||
@@ -80,6 +83,11 @@ export function NotificationBell() {
|
|||||||
if (payload.groupId) {
|
if (payload.groupId) {
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
router.push(`/family/${payload.groupId}`);
|
router.push(`/family/${payload.groupId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (item.type === 'role_assigned' || item.type === 'role_removed') {
|
||||||
|
setOpen(false);
|
||||||
|
router.push('/admin');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -74,7 +74,12 @@ export function RealtimeProvider({ children }: { children: React.ReactNode }) {
|
|||||||
try {
|
try {
|
||||||
const data = JSON.parse(event.data as string) as RealtimeEvent;
|
const data = JSON.parse(event.data as string) as RealtimeEvent;
|
||||||
emit(data);
|
emit(data);
|
||||||
if (data.type === 'family_invite' || (data.type === 'chat_message' && data.payload?.notificationId)) {
|
if (
|
||||||
|
data.type === 'family_invite' ||
|
||||||
|
data.type === 'role_assigned' ||
|
||||||
|
data.type === 'role_removed' ||
|
||||||
|
(data.type === 'chat_message' && data.payload?.notificationId)
|
||||||
|
) {
|
||||||
setUnreadCount((count) => count + 1);
|
setUnreadCount((count) => count + 1);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -91,6 +91,7 @@ export interface AdminUser {
|
|||||||
status: string;
|
status: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
roles: string[];
|
roles: string[];
|
||||||
|
directPermissions?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AdminRole {
|
export interface AdminRole {
|
||||||
@@ -98,6 +99,8 @@ export interface AdminRole {
|
|||||||
slug: string;
|
slug: string;
|
||||||
name: string;
|
name: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
|
isSystem?: boolean;
|
||||||
|
isDefault?: boolean;
|
||||||
permissions: { id: string; slug: string; name: string; description?: string }[];
|
permissions: { id: string; slug: string; name: string; description?: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ model User {
|
|||||||
authCodes AuthCode[]
|
authCodes AuthCode[]
|
||||||
linkedAccounts LinkedAccount[]
|
linkedAccounts LinkedAccount[]
|
||||||
userRoles UserRole[]
|
userRoles UserRole[]
|
||||||
|
userPermissions UserPermission[]
|
||||||
profile UserProfile?
|
profile UserProfile?
|
||||||
documents UserDocument[]
|
documents UserDocument[]
|
||||||
addresses Address[]
|
addresses Address[]
|
||||||
@@ -183,6 +184,8 @@ model Role {
|
|||||||
slug String @unique
|
slug String @unique
|
||||||
name String
|
name String
|
||||||
description String?
|
description String?
|
||||||
|
isSystem Boolean @default(false)
|
||||||
|
isDefault Boolean @default(false)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
users UserRole[]
|
users UserRole[]
|
||||||
@@ -196,6 +199,17 @@ model Permission {
|
|||||||
description String?
|
description String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
roles RolePermission[]
|
roles RolePermission[]
|
||||||
|
users UserPermission[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model UserPermission {
|
||||||
|
userId String
|
||||||
|
permissionId String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([userId, permissionId])
|
||||||
}
|
}
|
||||||
|
|
||||||
model UserRole {
|
model UserRole {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
import { PrismaService } from '../infra/prisma.service';
|
import { PrismaService } from '../infra/prisma.service';
|
||||||
|
|
||||||
export interface UserAccessContext {
|
export interface UserAccessContext {
|
||||||
@@ -55,7 +55,8 @@ export class AccessService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const links = await this.prisma.userRole.findMany({
|
const [roleLinks, directLinks] = await Promise.all([
|
||||||
|
this.prisma.userRole.findMany({
|
||||||
where: { userId },
|
where: { userId },
|
||||||
include: {
|
include: {
|
||||||
role: {
|
role: {
|
||||||
@@ -66,10 +67,17 @@ export class AccessService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
}),
|
||||||
|
this.prisma.userPermission.findMany({
|
||||||
|
where: { userId },
|
||||||
|
include: { permission: true }
|
||||||
|
})
|
||||||
|
]);
|
||||||
|
|
||||||
const roles = links.map((link) => link.role.slug);
|
const roles = roleLinks.map((link) => link.role.slug);
|
||||||
const permissions = [...new Set(links.flatMap((link) => link.role.permissions.map((item) => item.permission.slug)))];
|
const rolePermissions = roleLinks.flatMap((link) => link.role.permissions.map((item) => item.permission.slug));
|
||||||
|
const directPermissions = directLinks.map((link) => link.permission.slug);
|
||||||
|
const permissions = [...new Set([...rolePermissions, ...directPermissions])];
|
||||||
|
|
||||||
const canViewOAuth = hasAnyPermission(permissions, 'oauth.view', 'oauth.view.all', 'oauth.manage', 'oauth.manage.all');
|
const canViewOAuth = hasAnyPermission(permissions, 'oauth.view', 'oauth.view.all', 'oauth.manage', 'oauth.manage.all');
|
||||||
const canManageOAuth = hasAnyPermission(permissions, 'oauth.manage', 'oauth.manage.all');
|
const canManageOAuth = hasAnyPermission(permissions, 'oauth.manage', 'oauth.manage.all');
|
||||||
@@ -82,7 +90,7 @@ export class AccessService {
|
|||||||
roles,
|
roles,
|
||||||
permissions,
|
permissions,
|
||||||
canAccessAdmin: permissions.includes('admin.access'),
|
canAccessAdmin: permissions.includes('admin.access'),
|
||||||
canManageRoles: false,
|
canManageRoles: permissions.includes('rbac.manage'),
|
||||||
canViewOAuth,
|
canViewOAuth,
|
||||||
canManageOAuth,
|
canManageOAuth,
|
||||||
canManageAllOAuth,
|
canManageAllOAuth,
|
||||||
@@ -104,6 +112,18 @@ export class AccessService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async assertRbacManage(actorUserId: string) {
|
||||||
|
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
|
||||||
|
if (!actor) {
|
||||||
|
throw new NotFoundException('Пользователь не найден');
|
||||||
|
}
|
||||||
|
if (actor.isSuperAdmin) return;
|
||||||
|
const access = await this.getUserAccess(actorUserId, false);
|
||||||
|
if (!access.canManageRoles) {
|
||||||
|
throw new ForbiddenException('Недостаточно прав для управления ролями и правами');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async assertSuperAdmin(actorUserId: string) {
|
async assertSuperAdmin(actorUserId: string) {
|
||||||
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
|
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
|
||||||
if (!actor?.isSuperAdmin) {
|
if (!actor?.isSuperAdmin) {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||||
import { PrismaService } from '../infra/prisma.service';
|
import { PrismaService } from '../infra/prisma.service';
|
||||||
|
import { DEFAULT_USER_ROLE_SLUG } from './rbac.constants';
|
||||||
import { RbacService } from './rbac.service';
|
import { RbacService } from './rbac.service';
|
||||||
|
|
||||||
const PERMISSIONS = [
|
const PERMISSIONS = [
|
||||||
@@ -14,28 +15,42 @@ const PERMISSIONS = [
|
|||||||
{ slug: 'users.manage.all', name: 'Полное управление пользователями', description: 'Расширенное управление всеми пользователями' },
|
{ slug: 'users.manage.all', name: 'Полное управление пользователями', description: 'Расширенное управление всеми пользователями' },
|
||||||
{ slug: 'users.read', name: 'Просмотр пользователей (устар.)', description: 'Устаревшее право, заменено на users.view' },
|
{ slug: 'users.read', name: 'Просмотр пользователей (устар.)', description: 'Устаревшее право, заменено на users.view' },
|
||||||
{ slug: 'settings.manage', name: 'Управление настройками', description: 'Изменение глобальных SystemSetting' },
|
{ slug: 'settings.manage', name: 'Управление настройками', description: 'Изменение глобальных SystemSetting' },
|
||||||
{ slug: 'rbac.manage', name: 'Управление ролями', description: 'Назначение ролей и прав (только супер-админ)' },
|
{ slug: 'rbac.manage', name: 'Управление ролями и правами', description: 'Назначение ролей, прав пользователям и редактирование ролей' },
|
||||||
{ slug: 'documents.view_others', name: 'Просмотр документов пользователей', description: 'Просмотр документов и фото других пользователей' }
|
{ slug: 'documents.view_others', name: 'Просмотр документов пользователей', description: 'Просмотр документов и фото других пользователей' }
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const ROLES = [
|
const ROLES = [
|
||||||
|
{
|
||||||
|
slug: DEFAULT_USER_ROLE_SLUG,
|
||||||
|
name: 'Пользователь',
|
||||||
|
description: 'Стандартная роль всех пользователей системы',
|
||||||
|
permissions: [] as string[],
|
||||||
|
isSystem: true,
|
||||||
|
isDefault: true
|
||||||
|
},
|
||||||
{
|
{
|
||||||
slug: 'admin',
|
slug: 'admin',
|
||||||
name: 'Администратор',
|
name: 'Администратор',
|
||||||
description: 'Полный доступ к админ-панели без назначения ролей',
|
description: 'Полный доступ к админ-панели',
|
||||||
permissions: ['admin.access', 'oauth.manage.all', 'oauth.view.all', 'users.manage.all', 'users.view.all', 'settings.manage']
|
permissions: ['admin.access', 'oauth.manage.all', 'oauth.view.all', 'users.manage.all', 'users.view.all', 'settings.manage', 'rbac.manage'],
|
||||||
|
isSystem: false,
|
||||||
|
isDefault: false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
slug: 'moderator',
|
slug: 'moderator',
|
||||||
name: 'Модератор',
|
name: 'Модератор',
|
||||||
description: 'Просмотр пользователей и базовый доступ к админке',
|
description: 'Просмотр пользователей и базовый доступ к админке',
|
||||||
permissions: ['admin.access', 'users.view', 'users.view.all']
|
permissions: ['admin.access', 'users.view', 'users.view.all'],
|
||||||
|
isSystem: false,
|
||||||
|
isDefault: false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
slug: 'manager',
|
slug: 'manager',
|
||||||
name: 'Менеджер',
|
name: 'Менеджер',
|
||||||
description: 'Управление OAuth-приложениями',
|
description: 'Управление OAuth-приложениями',
|
||||||
permissions: ['admin.access', 'oauth.manage', 'oauth.view']
|
permissions: ['admin.access', 'oauth.manage', 'oauth.view'],
|
||||||
|
isSystem: false,
|
||||||
|
isDefault: false
|
||||||
}
|
}
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
@@ -76,13 +91,20 @@ export class AdminSeedService implements OnModuleInit {
|
|||||||
data: {
|
data: {
|
||||||
slug: role.slug,
|
slug: role.slug,
|
||||||
name: role.name,
|
name: role.name,
|
||||||
description: role.description
|
description: role.description,
|
||||||
|
isSystem: role.isSystem,
|
||||||
|
isDefault: role.isDefault
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
|
|
||||||
await this.prisma.role.update({
|
await this.prisma.role.update({
|
||||||
where: { id: roleRecord.id },
|
where: { id: roleRecord.id },
|
||||||
data: { name: role.name, description: role.description }
|
data: {
|
||||||
|
name: role.name,
|
||||||
|
description: role.description,
|
||||||
|
isSystem: role.isSystem,
|
||||||
|
isDefault: role.isDefault
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
for (const slug of role.permissions) {
|
for (const slug of role.permissions) {
|
||||||
@@ -95,5 +117,10 @@ export class AdminSeedService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const users = await this.prisma.user.findMany({ where: { deletedAt: null }, select: { id: true } });
|
||||||
|
for (const user of users) {
|
||||||
|
await this.rbac.ensureDefaultUserRole(user.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,10 @@ export class AdminService {
|
|||||||
}
|
}
|
||||||
: undefined,
|
: undefined,
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
include: { userRoles: { include: { role: true } } }
|
include: {
|
||||||
|
userRoles: { include: { role: true } },
|
||||||
|
userPermissions: { include: { permission: true } }
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return users.map((user) => this.toAdminUser(user));
|
return users.map((user) => this.toAdminUser(user));
|
||||||
@@ -35,7 +38,7 @@ export class AdminService {
|
|||||||
const user = await this.prisma.user.update({
|
const user = await this.prisma.user.update({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
data,
|
data,
|
||||||
include: { userRoles: { include: { role: true } } }
|
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
|
||||||
});
|
});
|
||||||
return this.toAdminUser(user);
|
return this.toAdminUser(user);
|
||||||
}
|
}
|
||||||
@@ -49,7 +52,7 @@ export class AdminService {
|
|||||||
const user = await this.prisma.user.update({
|
const user = await this.prisma.user.update({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
data: { passwordHash: await bcrypt.hash(newPassword, 12) },
|
data: { passwordHash: await bcrypt.hash(newPassword, 12) },
|
||||||
include: { userRoles: { include: { role: true } } }
|
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
|
||||||
});
|
});
|
||||||
return this.toAdminUser(user);
|
return this.toAdminUser(user);
|
||||||
}
|
}
|
||||||
@@ -60,7 +63,7 @@ export class AdminService {
|
|||||||
const user = await this.prisma.user.update({
|
const user = await this.prisma.user.update({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
data: { status: UserStatus.SUSPENDED },
|
data: { status: UserStatus.SUSPENDED },
|
||||||
include: { userRoles: { include: { role: true } } }
|
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
|
||||||
});
|
});
|
||||||
return this.toAdminUser(user);
|
return this.toAdminUser(user);
|
||||||
}
|
}
|
||||||
@@ -84,7 +87,7 @@ export class AdminService {
|
|||||||
const user = await this.prisma.user.update({
|
const user = await this.prisma.user.update({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
data: { isSuperAdmin },
|
data: { isSuperAdmin },
|
||||||
include: { userRoles: { include: { role: true } } }
|
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
|
||||||
});
|
});
|
||||||
return this.toAdminUser(user);
|
return this.toAdminUser(user);
|
||||||
}
|
}
|
||||||
@@ -94,7 +97,7 @@ export class AdminService {
|
|||||||
const user = await this.prisma.user.update({
|
const user = await this.prisma.user.update({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
data: { status: UserStatus.DELETED, deletedAt: new Date() },
|
data: { status: UserStatus.DELETED, deletedAt: new Date() },
|
||||||
include: { userRoles: { include: { role: true } } }
|
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
|
||||||
});
|
});
|
||||||
return this.toAdminUser(user);
|
return this.toAdminUser(user);
|
||||||
}
|
}
|
||||||
@@ -111,6 +114,7 @@ export class AdminService {
|
|||||||
status: UserStatus;
|
status: UserStatus;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
userRoles?: { role: { slug: string } }[];
|
userRoles?: { role: { slug: string } }[];
|
||||||
|
userPermissions?: { permission: { slug: string } }[];
|
||||||
}) {
|
}) {
|
||||||
return {
|
return {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
@@ -123,7 +127,8 @@ export class AdminService {
|
|||||||
isSuperAdmin: user.isSuperAdmin,
|
isSuperAdmin: user.isSuperAdmin,
|
||||||
status: user.status,
|
status: user.status,
|
||||||
createdAt: user.createdAt.toISOString(),
|
createdAt: user.createdAt.toISOString(),
|
||||||
roles: user.userRoles?.map((link) => link.role.slug) ?? []
|
roles: user.userRoles?.map((link) => link.role.slug) ?? [],
|
||||||
|
directPermissions: user.userPermissions?.map((link) => link.permission.slug) ?? []
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -166,6 +166,8 @@ export class AuthGrpcController {
|
|||||||
slug: role.slug,
|
slug: role.slug,
|
||||||
name: role.name,
|
name: role.name,
|
||||||
description: role.description ?? undefined,
|
description: role.description ?? undefined,
|
||||||
|
isSystem: role.isSystem,
|
||||||
|
isDefault: role.isDefault,
|
||||||
permissions: role.permissions.map((link) => ({
|
permissions: role.permissions.map((link) => ({
|
||||||
id: link.permission.id,
|
id: link.permission.id,
|
||||||
slug: link.permission.slug,
|
slug: link.permission.slug,
|
||||||
@@ -234,6 +236,8 @@ export class AuthGrpcController {
|
|||||||
slug: role.slug,
|
slug: role.slug,
|
||||||
name: role.name,
|
name: role.name,
|
||||||
description: role.description ?? undefined,
|
description: role.description ?? undefined,
|
||||||
|
isSystem: role.isSystem,
|
||||||
|
isDefault: role.isDefault,
|
||||||
permissions: role.permissions.map((link) => ({
|
permissions: role.permissions.map((link) => ({
|
||||||
id: link.permission.id,
|
id: link.permission.id,
|
||||||
slug: link.permission.slug,
|
slug: link.permission.slug,
|
||||||
@@ -243,6 +247,41 @@ export class AuthGrpcController {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GrpcMethod('RbacService', 'UpdateRole')
|
||||||
|
async updateRole(command: {
|
||||||
|
actorUserId: string;
|
||||||
|
roleSlug: string;
|
||||||
|
name?: string;
|
||||||
|
description?: string;
|
||||||
|
permissionSlugs?: string[];
|
||||||
|
}) {
|
||||||
|
const role = await this.rbac.updateRole(command.actorUserId, command.roleSlug, {
|
||||||
|
name: command.name,
|
||||||
|
description: command.description,
|
||||||
|
permissionSlugs: command.permissionSlugs
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id: role.id,
|
||||||
|
slug: role.slug,
|
||||||
|
name: role.name,
|
||||||
|
description: role.description ?? undefined,
|
||||||
|
isSystem: role.isSystem,
|
||||||
|
isDefault: role.isDefault,
|
||||||
|
permissions: role.permissions.map((link) => ({
|
||||||
|
id: link.permission.id,
|
||||||
|
slug: link.permission.slug,
|
||||||
|
name: link.permission.name,
|
||||||
|
description: link.permission.description ?? undefined
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@GrpcMethod('RbacService', 'DeleteRole')
|
||||||
|
async deleteRole(command: { actorUserId: string; roleSlug: string }) {
|
||||||
|
await this.rbac.deleteRole(command.actorUserId, command.roleSlug);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
@GrpcMethod('RbacService', 'AssignUserRole')
|
@GrpcMethod('RbacService', 'AssignUserRole')
|
||||||
async assignUserRole(command: { actorUserId: string; userId: string; roleSlug: string }) {
|
async assignUserRole(command: { actorUserId: string; userId: string; roleSlug: string }) {
|
||||||
const roles = await this.rbac.assignRole(command.actorUserId, command.userId, command.roleSlug);
|
const roles = await this.rbac.assignRole(command.actorUserId, command.userId, command.roleSlug);
|
||||||
@@ -255,6 +294,18 @@ export class AuthGrpcController {
|
|||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GrpcMethod('RbacService', 'AssignUserPermission')
|
||||||
|
async assignUserPermission(command: { actorUserId: string; userId: string; permissionSlug: string }) {
|
||||||
|
const permissions = await this.rbac.assignUserPermission(command.actorUserId, command.userId, command.permissionSlug);
|
||||||
|
return { userId: command.userId, permissions };
|
||||||
|
}
|
||||||
|
|
||||||
|
@GrpcMethod('RbacService', 'RemoveUserPermission')
|
||||||
|
async removeUserPermission(command: { actorUserId: string; userId: string; permissionSlug: string }) {
|
||||||
|
const permissions = await this.rbac.removeUserPermission(command.actorUserId, command.userId, command.permissionSlug);
|
||||||
|
return { userId: command.userId, permissions };
|
||||||
|
}
|
||||||
|
|
||||||
@GrpcMethod('RbacService', 'CreateOAuthClient')
|
@GrpcMethod('RbacService', 'CreateOAuthClient')
|
||||||
async createOAuthClient(command: { actorUserId: string; name: string; redirectUris: string[]; scopes: string[]; type?: string }) {
|
async createOAuthClient(command: { actorUserId: string; name: string; redirectUris: string[]; scopes: string[]; type?: string }) {
|
||||||
const { client, clientSecret } = await this.rbac.createOAuthClient(command.actorUserId, {
|
const { client, clientSecret } = await this.rbac.createOAuthClient(command.actorUserId, {
|
||||||
@@ -306,6 +357,11 @@ export class AuthGrpcController {
|
|||||||
return this.rbac.rotateOAuthSecret(command.actorUserId, command.clientId);
|
return this.rbac.rotateOAuthSecret(command.actorUserId, command.clientId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GrpcMethod('RbacService', 'DeleteOAuthClient')
|
||||||
|
async deleteOAuthClient(command: { actorUserId: string; clientId: string }) {
|
||||||
|
return this.rbac.deleteOAuthClient(command.actorUserId, command.clientId);
|
||||||
|
}
|
||||||
|
|
||||||
@GrpcMethod('SecurityService', 'ListActiveDevices')
|
@GrpcMethod('SecurityService', 'ListActiveDevices')
|
||||||
async listActiveDevices(command: { userId: string; exceptSessionId?: string }) {
|
async listActiveDevices(command: { userId: string; exceptSessionId?: string }) {
|
||||||
const devices = await this.security.listActiveDevices(command.userId, command.exceptSessionId);
|
const devices = await this.security.listActiveDevices(command.userId, command.exceptSessionId);
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { MessagingService } from '../infra/messaging.service';
|
|||||||
import { NotificationsService } from './notifications.service';
|
import { NotificationsService } from './notifications.service';
|
||||||
import { canonicalPhoneE164, phoneLookupVariants } from '../infra/phone.util';
|
import { canonicalPhoneE164, phoneLookupVariants } from '../infra/phone.util';
|
||||||
import { TotpService } from './totp.service';
|
import { TotpService } from './totp.service';
|
||||||
|
import { RbacService } from './rbac.service';
|
||||||
|
|
||||||
const FIRST_ADMIN_LOCK = 'locks:first-super-admin';
|
const FIRST_ADMIN_LOCK = 'locks:first-super-admin';
|
||||||
const TOTP_LOGIN_CHALLENGE_TTL_SECONDS = 5 * 60;
|
const TOTP_LOGIN_CHALLENGE_TTL_SECONDS = 5 * 60;
|
||||||
@@ -33,7 +34,8 @@ export class AuthService {
|
|||||||
private readonly ldapClient: LdapClientService,
|
private readonly ldapClient: LdapClientService,
|
||||||
private readonly messaging: MessagingService,
|
private readonly messaging: MessagingService,
|
||||||
private readonly notifications: NotificationsService,
|
private readonly notifications: NotificationsService,
|
||||||
private readonly totp: TotpService
|
private readonly totp: TotpService,
|
||||||
|
private readonly rbac: RbacService
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async register(command: RegisterCommand): Promise<PublicUser> {
|
async register(command: RegisterCommand): Promise<PublicUser> {
|
||||||
@@ -66,6 +68,7 @@ export class AuthService {
|
|||||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
await this.rbac.ensureDefaultUserRole(user.id);
|
||||||
return await this.toPublicUser(user);
|
return await this.toPublicUser(user);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (this.isUniqueError(error)) {
|
if (this.isUniqueError(error)) {
|
||||||
@@ -533,7 +536,7 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await this.prisma.$transaction(
|
const user = await this.prisma.$transaction(
|
||||||
async (tx) => {
|
async (tx) => {
|
||||||
const usersCount = await tx.user.count({ where: { deletedAt: null } });
|
const usersCount = await tx.user.count({ where: { deletedAt: null } });
|
||||||
return tx.user.create({
|
return tx.user.create({
|
||||||
@@ -557,6 +560,8 @@ export class AuthService {
|
|||||||
},
|
},
|
||||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
||||||
);
|
);
|
||||||
|
await this.rbac.ensureDefaultUserRole(user.id);
|
||||||
|
return user;
|
||||||
} finally {
|
} finally {
|
||||||
await this.redis.releaseLock(FIRST_ADMIN_LOCK);
|
await this.redis.releaseLock(FIRST_ADMIN_LOCK);
|
||||||
}
|
}
|
||||||
@@ -726,7 +731,7 @@ export class AuthService {
|
|||||||
const lockAcquired = await this.redis.acquireLock(FIRST_ADMIN_LOCK, 10_000);
|
const lockAcquired = await this.redis.acquireLock(FIRST_ADMIN_LOCK, 10_000);
|
||||||
if (!lockAcquired) throw new BadRequestException('Регистрация временно недоступна, повторите попытку');
|
if (!lockAcquired) throw new BadRequestException('Регистрация временно недоступна, повторите попытку');
|
||||||
try {
|
try {
|
||||||
return this.prisma.$transaction(
|
const user = await this.prisma.$transaction(
|
||||||
async (tx) => {
|
async (tx) => {
|
||||||
const usersCount = await tx.user.count({ where: { deletedAt: null } });
|
const usersCount = await tx.user.count({ where: { deletedAt: null } });
|
||||||
return tx.user.create({
|
return tx.user.create({
|
||||||
@@ -741,6 +746,8 @@ export class AuthService {
|
|||||||
},
|
},
|
||||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
||||||
);
|
);
|
||||||
|
await this.rbac.ensureDefaultUserRole(user.id);
|
||||||
|
return user;
|
||||||
} finally {
|
} finally {
|
||||||
await this.redis.releaseLock(FIRST_ADMIN_LOCK);
|
await this.redis.releaseLock(FIRST_ADMIN_LOCK);
|
||||||
}
|
}
|
||||||
|
|||||||
1
apps/sso-core/src/domain/rbac.constants.ts
Normal file
1
apps/sso-core/src/domain/rbac.constants.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export const DEFAULT_USER_ROLE_SLUG = 'user';
|
||||||
@@ -3,6 +3,8 @@ import { randomBytes } from 'node:crypto';
|
|||||||
import { OAuthClientType } from '../generated/prisma/client';
|
import { OAuthClientType } from '../generated/prisma/client';
|
||||||
import { PrismaService } from '../infra/prisma.service';
|
import { PrismaService } from '../infra/prisma.service';
|
||||||
import { AccessService, UserAccessContext } from './access.service';
|
import { AccessService, UserAccessContext } from './access.service';
|
||||||
|
import { NotificationsService } from './notifications.service';
|
||||||
|
import { DEFAULT_USER_ROLE_SLUG } from './rbac.constants';
|
||||||
|
|
||||||
export interface OAuthClientListItem {
|
export interface OAuthClientListItem {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -21,11 +23,12 @@ export interface OAuthClientListItem {
|
|||||||
export class RbacService {
|
export class RbacService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly access: AccessService
|
private readonly access: AccessService,
|
||||||
|
private readonly notifications: NotificationsService
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async createRole(actorUserId: string, data: { slug: string; name: string; description?: string; permissionSlugs?: string[] }) {
|
async createRole(actorUserId: string, data: { slug: string; name: string; description?: string; permissionSlugs?: string[] }) {
|
||||||
await this.access.assertSuperAdmin(actorUserId);
|
await this.access.assertRbacManage(actorUserId);
|
||||||
return this.prisma.role.create({
|
return this.prisma.role.create({
|
||||||
data: {
|
data: {
|
||||||
slug: data.slug,
|
slug: data.slug,
|
||||||
@@ -51,28 +54,105 @@ export class RbacService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateRole(
|
||||||
|
actorUserId: string,
|
||||||
|
roleSlug: string,
|
||||||
|
data: { name?: string; description?: string; permissionSlugs?: string[] }
|
||||||
|
) {
|
||||||
|
await this.access.assertRbacManage(actorUserId);
|
||||||
|
const role = await this.prisma.role.findUnique({ where: { slug: roleSlug } });
|
||||||
|
if (!role) {
|
||||||
|
throw new NotFoundException('Роль не найдена');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.permissionSlugs !== undefined) {
|
||||||
|
await this.prisma.rolePermission.deleteMany({ where: { roleId: role.id } });
|
||||||
|
for (const slug of data.permissionSlugs) {
|
||||||
|
const permission = await this.prisma.permission.findUnique({ where: { slug } });
|
||||||
|
if (!permission) continue;
|
||||||
|
await this.prisma.rolePermission.create({
|
||||||
|
data: { roleId: role.id, permissionId: permission.id }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.prisma.role.update({
|
||||||
|
where: { id: role.id },
|
||||||
|
data: {
|
||||||
|
name: data.name,
|
||||||
|
description: data.description
|
||||||
|
},
|
||||||
|
include: { permissions: { include: { permission: true } } }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteRole(actorUserId: string, roleSlug: string) {
|
||||||
|
await this.access.assertRbacManage(actorUserId);
|
||||||
|
const role = await this.prisma.role.findUnique({ where: { slug: roleSlug } });
|
||||||
|
if (!role) {
|
||||||
|
throw new NotFoundException('Роль не найдена');
|
||||||
|
}
|
||||||
|
if (role.isSystem) {
|
||||||
|
throw new BadRequestException('Системную роль нельзя удалить');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.userRole.deleteMany({ where: { roleId: role.id } });
|
||||||
|
await this.prisma.rolePermission.deleteMany({ where: { roleId: role.id } });
|
||||||
|
await this.prisma.role.delete({ where: { id: role.id } });
|
||||||
|
return { slug: roleSlug };
|
||||||
|
}
|
||||||
|
|
||||||
async assignRole(actorUserId: string, userId: string, roleSlug: string) {
|
async assignRole(actorUserId: string, userId: string, roleSlug: string) {
|
||||||
await this.access.assertSuperAdmin(actorUserId);
|
await this.access.assertRbacManage(actorUserId);
|
||||||
const role = await this.prisma.role.findUnique({ where: { slug: roleSlug } });
|
const role = await this.prisma.role.findUnique({ where: { slug: roleSlug } });
|
||||||
if (!role) {
|
if (!role) {
|
||||||
throw new NotFoundException('Роль не найдена');
|
throw new NotFoundException('Роль не найдена');
|
||||||
}
|
}
|
||||||
await this.ensureUserExists(userId);
|
await this.ensureUserExists(userId);
|
||||||
await this.prisma.userRole.upsert({
|
|
||||||
where: { userId_roleId: { userId, roleId: role.id } },
|
const existingLink = await this.prisma.userRole.findUnique({
|
||||||
create: { userId, roleId: role.id },
|
where: { userId_roleId: { userId, roleId: role.id } }
|
||||||
update: {}
|
|
||||||
});
|
});
|
||||||
|
if (existingLink) {
|
||||||
|
return this.getUserRoleSlugs(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.userRole.create({
|
||||||
|
data: { userId, roleId: role.id }
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.notifications.create(userId, 'role_assigned', 'Роли', `Вам назначена роль: ${role.name}`, {
|
||||||
|
roleSlug: role.slug,
|
||||||
|
roleName: role.name
|
||||||
|
});
|
||||||
|
|
||||||
return this.getUserRoleSlugs(userId);
|
return this.getUserRoleSlugs(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
async removeRole(actorUserId: string, userId: string, roleSlug: string) {
|
async removeRole(actorUserId: string, userId: string, roleSlug: string) {
|
||||||
await this.access.assertSuperAdmin(actorUserId);
|
await this.access.assertRbacManage(actorUserId);
|
||||||
const role = await this.prisma.role.findUnique({ where: { slug: roleSlug } });
|
const role = await this.prisma.role.findUnique({ where: { slug: roleSlug } });
|
||||||
if (!role) {
|
if (!role) {
|
||||||
throw new NotFoundException('Роль не найдена');
|
throw new NotFoundException('Роль не найдена');
|
||||||
}
|
}
|
||||||
|
if (role.isSystem || role.isDefault || role.slug === DEFAULT_USER_ROLE_SLUG) {
|
||||||
|
throw new BadRequestException('Стандартную роль «Пользователь» нельзя снять');
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingLink = await this.prisma.userRole.findUnique({
|
||||||
|
where: { userId_roleId: { userId, roleId: role.id } }
|
||||||
|
});
|
||||||
|
if (!existingLink) {
|
||||||
|
return this.getUserRoleSlugs(userId);
|
||||||
|
}
|
||||||
|
|
||||||
await this.prisma.userRole.deleteMany({ where: { userId, roleId: role.id } });
|
await this.prisma.userRole.deleteMany({ where: { userId, roleId: role.id } });
|
||||||
|
|
||||||
|
await this.notifications.create(userId, 'role_removed', 'Роли', `С вас снята роль: ${role.name}`, {
|
||||||
|
roleSlug: role.slug,
|
||||||
|
roleName: role.name
|
||||||
|
});
|
||||||
|
|
||||||
return this.getUserRoleSlugs(userId);
|
return this.getUserRoleSlugs(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,6 +243,54 @@ export class RbacService {
|
|||||||
return { client: updated, clientSecret: undefined as string | undefined };
|
return { client: updated, clientSecret: undefined as string | undefined };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async deleteOAuthClient(actorUserId: string, clientId: string) {
|
||||||
|
const existing = await this.prisma.oAuthClient.findUnique({ where: { clientId } });
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundException('OAuth-приложение не найдено');
|
||||||
|
}
|
||||||
|
await this.assertCanManageOAuthClient(actorUserId, existing);
|
||||||
|
await this.prisma.oAuthClient.delete({ where: { id: existing.id } });
|
||||||
|
return { clientId };
|
||||||
|
}
|
||||||
|
|
||||||
|
async ensureDefaultUserRole(userId: string) {
|
||||||
|
const role = await this.prisma.role.findUnique({ where: { slug: DEFAULT_USER_ROLE_SLUG } });
|
||||||
|
if (!role) return;
|
||||||
|
await this.prisma.userRole.upsert({
|
||||||
|
where: { userId_roleId: { userId, roleId: role.id } },
|
||||||
|
create: { userId, roleId: role.id },
|
||||||
|
update: {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async assignUserPermission(actorUserId: string, userId: string, permissionSlug: string) {
|
||||||
|
await this.access.assertRbacManage(actorUserId);
|
||||||
|
await this.ensureUserExists(userId);
|
||||||
|
const permission = await this.prisma.permission.findUnique({ where: { slug: permissionSlug } });
|
||||||
|
if (!permission) {
|
||||||
|
throw new NotFoundException('Право не найдено');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.userPermission.upsert({
|
||||||
|
where: { userId_permissionId: { userId, permissionId: permission.id } },
|
||||||
|
create: { userId, permissionId: permission.id },
|
||||||
|
update: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.getUserPermissionSlugs(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeUserPermission(actorUserId: string, userId: string, permissionSlug: string) {
|
||||||
|
await this.access.assertRbacManage(actorUserId);
|
||||||
|
const permission = await this.prisma.permission.findUnique({ where: { slug: permissionSlug } });
|
||||||
|
if (!permission) {
|
||||||
|
throw new NotFoundException('Право не найдено');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.userPermission.deleteMany({ where: { userId, permissionId: permission.id } });
|
||||||
|
return this.getUserPermissionSlugs(userId);
|
||||||
|
}
|
||||||
|
|
||||||
async rotateOAuthSecret(actorUserId: string, clientId: string) {
|
async rotateOAuthSecret(actorUserId: string, clientId: string) {
|
||||||
const existing = await this.prisma.oAuthClient.findUnique({ where: { clientId } });
|
const existing = await this.prisma.oAuthClient.findUnique({ where: { clientId } });
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
@@ -256,6 +384,14 @@ export class RbacService {
|
|||||||
return links.map((link) => link.role.slug);
|
return links.map((link) => link.role.slug);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async getUserPermissionSlugs(userId: string) {
|
||||||
|
const links = await this.prisma.userPermission.findMany({
|
||||||
|
where: { userId },
|
||||||
|
include: { permission: true }
|
||||||
|
});
|
||||||
|
return links.map((link) => link.permission.slug);
|
||||||
|
}
|
||||||
|
|
||||||
private async ensureUserExists(userId: string) {
|
private async ensureUserExists(userId: string) {
|
||||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||||
if (!user) {
|
if (!user) {
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ message AdminUser {
|
|||||||
string status = 9;
|
string status = 9;
|
||||||
string createdAt = 10;
|
string createdAt = 10;
|
||||||
repeated string roles = 11;
|
repeated string roles = 11;
|
||||||
|
repeated string directPermissions = 12;
|
||||||
}
|
}
|
||||||
|
|
||||||
message ListUsersResponse {
|
message ListUsersResponse {
|
||||||
|
|||||||
@@ -8,10 +8,15 @@ service RbacService {
|
|||||||
rpc ListOAuthScopes (Empty) returns (ListOAuthScopesResponse);
|
rpc ListOAuthScopes (Empty) returns (ListOAuthScopesResponse);
|
||||||
rpc ListOAuthClients (ListOAuthClientsRequest) returns (ListOAuthClientsResponse);
|
rpc ListOAuthClients (ListOAuthClientsRequest) returns (ListOAuthClientsResponse);
|
||||||
rpc CreateRole (CreateRoleRequest) returns (Role);
|
rpc CreateRole (CreateRoleRequest) returns (Role);
|
||||||
|
rpc UpdateRole (UpdateRoleRequest) returns (Role);
|
||||||
|
rpc DeleteRole (DeleteRoleRequest) returns (Empty);
|
||||||
rpc AssignUserRole (AssignUserRoleRequest) returns (AssignUserRoleResponse);
|
rpc AssignUserRole (AssignUserRoleRequest) returns (AssignUserRoleResponse);
|
||||||
rpc RemoveUserRole (RemoveUserRoleRequest) returns (Empty);
|
rpc RemoveUserRole (RemoveUserRoleRequest) returns (Empty);
|
||||||
|
rpc AssignUserPermission (AssignUserPermissionRequest) returns (AssignUserPermissionResponse);
|
||||||
|
rpc RemoveUserPermission (RemoveUserPermissionRequest) returns (AssignUserPermissionResponse);
|
||||||
rpc CreateOAuthClient (CreateOAuthClientRequest) returns (OAuthClientDetail);
|
rpc CreateOAuthClient (CreateOAuthClientRequest) returns (OAuthClientDetail);
|
||||||
rpc UpdateOAuthClient (UpdateOAuthClientRequest) returns (OAuthClientDetail);
|
rpc UpdateOAuthClient (UpdateOAuthClientRequest) returns (OAuthClientDetail);
|
||||||
|
rpc DeleteOAuthClient (DeleteOAuthClientRequest) returns (DeleteOAuthClientResponse);
|
||||||
rpc RotateOAuthSecret (RotateOAuthSecretRequest) returns (RotateOAuthSecretResponse);
|
rpc RotateOAuthSecret (RotateOAuthSecretRequest) returns (RotateOAuthSecretResponse);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,6 +35,8 @@ message Role {
|
|||||||
string name = 3;
|
string name = 3;
|
||||||
optional string description = 4;
|
optional string description = 4;
|
||||||
repeated Permission permissions = 5;
|
repeated Permission permissions = 5;
|
||||||
|
bool isSystem = 6;
|
||||||
|
bool isDefault = 7;
|
||||||
}
|
}
|
||||||
|
|
||||||
message OAuthScope {
|
message OAuthScope {
|
||||||
@@ -94,6 +101,19 @@ message CreateRoleRequest {
|
|||||||
repeated string permissionSlugs = 5;
|
repeated string permissionSlugs = 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message UpdateRoleRequest {
|
||||||
|
string actorUserId = 1;
|
||||||
|
string roleSlug = 2;
|
||||||
|
optional string name = 3;
|
||||||
|
optional string description = 4;
|
||||||
|
repeated string permissionSlugs = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
message DeleteRoleRequest {
|
||||||
|
string actorUserId = 1;
|
||||||
|
string roleSlug = 2;
|
||||||
|
}
|
||||||
|
|
||||||
message AssignUserRoleRequest {
|
message AssignUserRoleRequest {
|
||||||
string actorUserId = 1;
|
string actorUserId = 1;
|
||||||
string userId = 2;
|
string userId = 2;
|
||||||
@@ -111,6 +131,23 @@ message RemoveUserRoleRequest {
|
|||||||
string roleSlug = 3;
|
string roleSlug = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message AssignUserPermissionRequest {
|
||||||
|
string actorUserId = 1;
|
||||||
|
string userId = 2;
|
||||||
|
string permissionSlug = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message AssignUserPermissionResponse {
|
||||||
|
string userId = 1;
|
||||||
|
repeated string permissions = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
message RemoveUserPermissionRequest {
|
||||||
|
string actorUserId = 1;
|
||||||
|
string userId = 2;
|
||||||
|
string permissionSlug = 3;
|
||||||
|
}
|
||||||
|
|
||||||
message CreateOAuthClientRequest {
|
message CreateOAuthClientRequest {
|
||||||
string actorUserId = 1;
|
string actorUserId = 1;
|
||||||
string name = 2;
|
string name = 2;
|
||||||
@@ -128,6 +165,15 @@ message UpdateOAuthClientRequest {
|
|||||||
optional bool isActive = 6;
|
optional bool isActive = 6;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message DeleteOAuthClientRequest {
|
||||||
|
string actorUserId = 1;
|
||||||
|
string clientId = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
message DeleteOAuthClientResponse {
|
||||||
|
string clientId = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message RotateOAuthSecretRequest {
|
message RotateOAuthSecretRequest {
|
||||||
string actorUserId = 1;
|
string actorUserId = 1;
|
||||||
string clientId = 2;
|
string clientId = 2;
|
||||||
|
|||||||
Reference in New Issue
Block a user