roles update
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../infra/prisma.service';
|
||||
|
||||
export interface UserAccessContext {
|
||||
@@ -55,21 +55,29 @@ export class AccessService {
|
||||
};
|
||||
}
|
||||
|
||||
const links = await this.prisma.userRole.findMany({
|
||||
where: { userId },
|
||||
include: {
|
||||
role: {
|
||||
include: {
|
||||
permissions: {
|
||||
include: { permission: true }
|
||||
const [roleLinks, directLinks] = await Promise.all([
|
||||
this.prisma.userRole.findMany({
|
||||
where: { userId },
|
||||
include: {
|
||||
role: {
|
||||
include: {
|
||||
permissions: {
|
||||
include: { permission: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}),
|
||||
this.prisma.userPermission.findMany({
|
||||
where: { userId },
|
||||
include: { permission: true }
|
||||
})
|
||||
]);
|
||||
|
||||
const roles = links.map((link) => link.role.slug);
|
||||
const permissions = [...new Set(links.flatMap((link) => link.role.permissions.map((item) => item.permission.slug)))];
|
||||
const roles = roleLinks.map((link) => link.role.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 canManageOAuth = hasAnyPermission(permissions, 'oauth.manage', 'oauth.manage.all');
|
||||
@@ -82,7 +90,7 @@ export class AccessService {
|
||||
roles,
|
||||
permissions,
|
||||
canAccessAdmin: permissions.includes('admin.access'),
|
||||
canManageRoles: false,
|
||||
canManageRoles: permissions.includes('rbac.manage'),
|
||||
canViewOAuth,
|
||||
canManageOAuth,
|
||||
canManageAllOAuth,
|
||||
@@ -104,6 +112,18 @@ export class AccessService {
|
||||
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) {
|
||||
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
|
||||
if (!actor?.isSuperAdmin) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaService } from '../infra/prisma.service';
|
||||
import { DEFAULT_USER_ROLE_SLUG } from './rbac.constants';
|
||||
import { RbacService } from './rbac.service';
|
||||
|
||||
const PERMISSIONS = [
|
||||
@@ -14,28 +15,42 @@ const PERMISSIONS = [
|
||||
{ slug: 'users.manage.all', name: 'Полное управление пользователями', description: 'Расширенное управление всеми пользователями' },
|
||||
{ slug: 'users.read', name: 'Просмотр пользователей (устар.)', description: 'Устаревшее право, заменено на users.view' },
|
||||
{ slug: 'settings.manage', name: 'Управление настройками', description: 'Изменение глобальных SystemSetting' },
|
||||
{ slug: 'rbac.manage', name: 'Управление ролями', description: 'Назначение ролей и прав (только супер-админ)' },
|
||||
{ slug: 'rbac.manage', name: 'Управление ролями и правами', description: 'Назначение ролей, прав пользователям и редактирование ролей' },
|
||||
{ slug: 'documents.view_others', name: 'Просмотр документов пользователей', description: 'Просмотр документов и фото других пользователей' }
|
||||
] as const;
|
||||
|
||||
const ROLES = [
|
||||
{
|
||||
slug: DEFAULT_USER_ROLE_SLUG,
|
||||
name: 'Пользователь',
|
||||
description: 'Стандартная роль всех пользователей системы',
|
||||
permissions: [] as string[],
|
||||
isSystem: true,
|
||||
isDefault: true
|
||||
},
|
||||
{
|
||||
slug: 'admin',
|
||||
name: 'Администратор',
|
||||
description: 'Полный доступ к админ-панели без назначения ролей',
|
||||
permissions: ['admin.access', 'oauth.manage.all', 'oauth.view.all', 'users.manage.all', 'users.view.all', 'settings.manage']
|
||||
description: 'Полный доступ к админ-панели',
|
||||
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',
|
||||
name: 'Модератор',
|
||||
description: 'Просмотр пользователей и базовый доступ к админке',
|
||||
permissions: ['admin.access', 'users.view', 'users.view.all']
|
||||
permissions: ['admin.access', 'users.view', 'users.view.all'],
|
||||
isSystem: false,
|
||||
isDefault: false
|
||||
},
|
||||
{
|
||||
slug: 'manager',
|
||||
name: 'Менеджер',
|
||||
description: 'Управление OAuth-приложениями',
|
||||
permissions: ['admin.access', 'oauth.manage', 'oauth.view']
|
||||
permissions: ['admin.access', 'oauth.manage', 'oauth.view'],
|
||||
isSystem: false,
|
||||
isDefault: false
|
||||
}
|
||||
] as const;
|
||||
|
||||
@@ -76,13 +91,20 @@ export class AdminSeedService implements OnModuleInit {
|
||||
data: {
|
||||
slug: role.slug,
|
||||
name: role.name,
|
||||
description: role.description
|
||||
description: role.description,
|
||||
isSystem: role.isSystem,
|
||||
isDefault: role.isDefault
|
||||
}
|
||||
}));
|
||||
|
||||
await this.prisma.role.update({
|
||||
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) {
|
||||
@@ -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,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { userRoles: { include: { role: true } } }
|
||||
include: {
|
||||
userRoles: { include: { role: true } },
|
||||
userPermissions: { include: { permission: true } }
|
||||
}
|
||||
});
|
||||
|
||||
return users.map((user) => this.toAdminUser(user));
|
||||
@@ -35,7 +38,7 @@ export class AdminService {
|
||||
const user = await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data,
|
||||
include: { userRoles: { include: { role: true } } }
|
||||
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
|
||||
});
|
||||
return this.toAdminUser(user);
|
||||
}
|
||||
@@ -49,7 +52,7 @@ export class AdminService {
|
||||
const user = await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
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);
|
||||
}
|
||||
@@ -60,7 +63,7 @@ export class AdminService {
|
||||
const user = await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { status: UserStatus.SUSPENDED },
|
||||
include: { userRoles: { include: { role: true } } }
|
||||
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
|
||||
});
|
||||
return this.toAdminUser(user);
|
||||
}
|
||||
@@ -84,7 +87,7 @@ export class AdminService {
|
||||
const user = await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { isSuperAdmin },
|
||||
include: { userRoles: { include: { role: true } } }
|
||||
include: { userRoles: { include: { role: true } }, userPermissions: { include: { permission: true } } }
|
||||
});
|
||||
return this.toAdminUser(user);
|
||||
}
|
||||
@@ -94,7 +97,7 @@ export class AdminService {
|
||||
const user = await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
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);
|
||||
}
|
||||
@@ -111,6 +114,7 @@ export class AdminService {
|
||||
status: UserStatus;
|
||||
createdAt: Date;
|
||||
userRoles?: { role: { slug: string } }[];
|
||||
userPermissions?: { permission: { slug: string } }[];
|
||||
}) {
|
||||
return {
|
||||
id: user.id,
|
||||
@@ -123,7 +127,8 @@ export class AdminService {
|
||||
isSuperAdmin: user.isSuperAdmin,
|
||||
status: user.status,
|
||||
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,
|
||||
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,
|
||||
@@ -234,6 +236,8 @@ export class AuthGrpcController {
|
||||
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,
|
||||
@@ -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')
|
||||
async assignUserRole(command: { actorUserId: string; userId: string; roleSlug: string }) {
|
||||
const roles = await this.rbac.assignRole(command.actorUserId, command.userId, command.roleSlug);
|
||||
@@ -255,6 +294,18 @@ export class AuthGrpcController {
|
||||
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')
|
||||
async createOAuthClient(command: { actorUserId: string; name: string; redirectUris: string[]; scopes: string[]; type?: string }) {
|
||||
const { client, clientSecret } = await this.rbac.createOAuthClient(command.actorUserId, {
|
||||
@@ -306,6 +357,11 @@ export class AuthGrpcController {
|
||||
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')
|
||||
async listActiveDevices(command: { userId: string; exceptSessionId?: string }) {
|
||||
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 { canonicalPhoneE164, phoneLookupVariants } from '../infra/phone.util';
|
||||
import { TotpService } from './totp.service';
|
||||
import { RbacService } from './rbac.service';
|
||||
|
||||
const FIRST_ADMIN_LOCK = 'locks:first-super-admin';
|
||||
const TOTP_LOGIN_CHALLENGE_TTL_SECONDS = 5 * 60;
|
||||
@@ -33,7 +34,8 @@ export class AuthService {
|
||||
private readonly ldapClient: LdapClientService,
|
||||
private readonly messaging: MessagingService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly totp: TotpService
|
||||
private readonly totp: TotpService,
|
||||
private readonly rbac: RbacService
|
||||
) {}
|
||||
|
||||
async register(command: RegisterCommand): Promise<PublicUser> {
|
||||
@@ -66,6 +68,7 @@ export class AuthService {
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
||||
);
|
||||
|
||||
await this.rbac.ensureDefaultUserRole(user.id);
|
||||
return await this.toPublicUser(user);
|
||||
} catch (error) {
|
||||
if (this.isUniqueError(error)) {
|
||||
@@ -533,7 +536,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.prisma.$transaction(
|
||||
const user = await this.prisma.$transaction(
|
||||
async (tx) => {
|
||||
const usersCount = await tx.user.count({ where: { deletedAt: null } });
|
||||
return tx.user.create({
|
||||
@@ -557,6 +560,8 @@ export class AuthService {
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
||||
);
|
||||
await this.rbac.ensureDefaultUserRole(user.id);
|
||||
return user;
|
||||
} finally {
|
||||
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);
|
||||
if (!lockAcquired) throw new BadRequestException('Регистрация временно недоступна, повторите попытку');
|
||||
try {
|
||||
return this.prisma.$transaction(
|
||||
const user = await this.prisma.$transaction(
|
||||
async (tx) => {
|
||||
const usersCount = await tx.user.count({ where: { deletedAt: null } });
|
||||
return tx.user.create({
|
||||
@@ -741,6 +746,8 @@ export class AuthService {
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }
|
||||
);
|
||||
await this.rbac.ensureDefaultUserRole(user.id);
|
||||
return user;
|
||||
} finally {
|
||||
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 { PrismaService } from '../infra/prisma.service';
|
||||
import { AccessService, UserAccessContext } from './access.service';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
import { DEFAULT_USER_ROLE_SLUG } from './rbac.constants';
|
||||
|
||||
export interface OAuthClientListItem {
|
||||
id: string;
|
||||
@@ -21,11 +23,12 @@ export interface OAuthClientListItem {
|
||||
export class RbacService {
|
||||
constructor(
|
||||
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[] }) {
|
||||
await this.access.assertSuperAdmin(actorUserId);
|
||||
await this.access.assertRbacManage(actorUserId);
|
||||
return this.prisma.role.create({
|
||||
data: {
|
||||
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) {
|
||||
await this.access.assertSuperAdmin(actorUserId);
|
||||
await this.access.assertRbacManage(actorUserId);
|
||||
const role = await this.prisma.role.findUnique({ where: { slug: roleSlug } });
|
||||
if (!role) {
|
||||
throw new NotFoundException('Роль не найдена');
|
||||
}
|
||||
await this.ensureUserExists(userId);
|
||||
await this.prisma.userRole.upsert({
|
||||
where: { userId_roleId: { userId, roleId: role.id } },
|
||||
create: { userId, roleId: role.id },
|
||||
update: {}
|
||||
|
||||
const existingLink = await this.prisma.userRole.findUnique({
|
||||
where: { userId_roleId: { userId, roleId: role.id } }
|
||||
});
|
||||
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);
|
||||
}
|
||||
|
||||
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 } });
|
||||
if (!role) {
|
||||
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.notifications.create(userId, 'role_removed', 'Роли', `С вас снята роль: ${role.name}`, {
|
||||
roleSlug: role.slug,
|
||||
roleName: role.name
|
||||
});
|
||||
|
||||
return this.getUserRoleSlugs(userId);
|
||||
}
|
||||
|
||||
@@ -163,6 +243,54 @@ export class RbacService {
|
||||
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) {
|
||||
const existing = await this.prisma.oAuthClient.findUnique({ where: { clientId } });
|
||||
if (!existing) {
|
||||
@@ -256,6 +384,14 @@ export class RbacService {
|
||||
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) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
|
||||
Reference in New Issue
Block a user