update oauth

This commit is contained in:
lendry
2026-06-25 14:23:55 +03:00
parent c3e06e03cf
commit 1796008a28
21 changed files with 340 additions and 64 deletions

View File

@@ -4,7 +4,7 @@ import { map } from 'rxjs';
import { CoreGrpcService } from '../core-grpc.service';
import { CurrentAdmin } from '../decorators/current-admin.decorator';
import { AssignUserRoleDto, CreateOAuthClientDto, CreateRoleDto, UpdateOAuthClientDto } from '../dto/rbac.dto';
import { AdminGuard, AdminRequestUser, assertAdminPermission, SuperAdminGuard } from '../guards/admin.guard';
import { AdminGuard, AdminRequestUser, assertAdminAnyPermission, assertAdminPermission, SuperAdminGuard } from '../guards/admin.guard';
@ApiTags('RBAC и OAuth')
@ApiBearerAuth()
@@ -39,15 +39,15 @@ export class RbacController {
@Get('oauth-scopes')
@ApiOperation({ summary: 'OAuth scopes', description: 'Возвращает доступные scopes для OAuth-приложений.' })
listOAuthScopes(@CurrentAdmin() admin: AdminRequestUser) {
assertAdminPermission(admin, 'canManageOAuth');
assertAdminAnyPermission(admin, 'canViewOAuth', 'canManageOAuth');
return this.core.rbac.ListOAuthScopes({});
}
@Get('oauth-clients')
@ApiOperation({ summary: 'OAuth приложения', description: 'Возвращает OAuth-клиенты и доступные scopes.' })
listOAuthClients(@CurrentAdmin() admin: AdminRequestUser) {
assertAdminPermission(admin, 'canManageOAuth');
return this.core.rbac.ListOAuthClients({});
assertAdminPermission(admin, 'canViewOAuth');
return this.core.rbac.ListOAuthClients({ actorUserId: admin.id });
}
@Post('roles')

View File

@@ -9,8 +9,11 @@ export interface AdminRequestUser {
isSuperAdmin: boolean;
canAccessAdmin: boolean;
canManageRoles: boolean;
canViewOAuth: boolean;
canManageOAuth: boolean;
canManageAllOAuth: boolean;
canManageUsers: boolean;
canManageAllUsers: boolean;
canViewUsers: boolean;
canManageSettings: boolean;
roles: string[];
@@ -48,8 +51,11 @@ export class AdminGuard implements CanActivate {
isSuperAdmin: profile.isSuperAdmin,
canAccessAdmin: Boolean(profile.canAccessAdmin),
canManageRoles: Boolean(profile.canManageRoles),
canViewOAuth: Boolean(profile.canViewOAuth),
canManageOAuth: Boolean(profile.canManageOAuth),
canManageAllOAuth: Boolean(profile.canManageAllOAuth),
canManageUsers: Boolean(profile.canManageUsers),
canManageAllUsers: Boolean(profile.canManageAllUsers),
canManageSettings: Boolean(profile.canManageSettings),
canViewUsers: Boolean(profile.canViewUsers),
roles: profile.roles ?? [],
@@ -71,8 +77,19 @@ export class SuperAdminGuard implements CanActivate {
}
}
export function assertAdminPermission(user: AdminRequestUser | undefined, permission: keyof Pick<AdminRequestUser, 'canManageOAuth' | 'canManageUsers' | 'canManageSettings'>) {
type AdminPermissionKey = keyof Pick<
AdminRequestUser,
'canViewOAuth' | 'canManageOAuth' | 'canManageUsers' | 'canViewUsers' | 'canManageSettings'
>;
export function assertAdminPermission(user: AdminRequestUser | undefined, permission: AdminPermissionKey) {
if (!user?.[permission]) {
throw new ForbiddenException('Недостаточно прав для выполнения действия');
}
}
export function assertAdminAnyPermission(user: AdminRequestUser | undefined, ...permissions: AdminPermissionKey[]) {
if (!user || !permissions.some((permission) => user[permission])) {
throw new ForbiddenException('Недостаточно прав для выполнения действия');
}
}

View File

@@ -1,7 +1,8 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { Copy, KeyRound, Loader2, LockKeyhole, Plus, RefreshCw } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { Copy, KeyRound, Loader2, LockKeyhole, Plus, RefreshCw, UserRound } from 'lucide-react';
import { AdminShell } from '@/components/id/admin-shell';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
@@ -10,9 +11,11 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { OAuthClient, OAuthScope, apiFetch } from '@/lib/api';
import { getAdminLandingPath } from '@/lib/admin-access';
export default function AdminOAuthPage() {
const { token } = useAuth();
const router = useRouter();
const { token, user } = useAuth();
const { showToast } = useToast();
const [clients, setClients] = useState<OAuthClient[]>([]);
const [scopes, setScopes] = useState<OAuthScope[]>([]);
@@ -23,25 +26,30 @@ export default function AdminOAuthPage() {
const [form, setForm] = useState({ name: '', redirectUris: '', type: 'CONFIDENTIAL', selectedScopes: ['openid', 'profile', 'email'] as string[] });
const loadData = useCallback(async () => {
if (!token) return;
if (!token || !user?.canViewOAuth) return;
setLoading(true);
try {
const [clientsResponse, scopesResponse] = await Promise.all([
apiFetch<{ clients: OAuthClient[] }>('/admin/rbac/oauth-clients', {}, token),
apiFetch<{ scopes: OAuthScope[] }>('/admin/rbac/oauth-scopes', {}, token)
]);
const clientsResponse = await apiFetch<{ clients: OAuthClient[] }>('/admin/rbac/oauth-clients', {}, token);
setClients(clientsResponse.clients ?? []);
if (user.canManageOAuth) {
const scopesResponse = await apiFetch<{ scopes: OAuthScope[] }>('/admin/rbac/oauth-scopes', {}, token);
setScopes(scopesResponse.scopes ?? []);
}
} catch (error) {
showToast(error instanceof Error ? error.message : 'Не удалось загрузить OAuth-приложения');
} finally {
setLoading(false);
}
}, [showToast, token]);
}, [showToast, token, user?.canManageOAuth, user?.canViewOAuth]);
useEffect(() => {
if (!user) return;
if (!user.canViewOAuth && !user.canManageOAuth) {
router.replace(getAdminLandingPath(user));
return;
}
void loadData();
}, [loadData]);
}, [loadData, router, user]);
async function handleCreate() {
if (!token) return;
@@ -116,7 +124,7 @@ export default function AdminOAuthPage() {
<h2 className="text-2xl font-medium">OAuth-приложения</h2>
<p className="text-sm text-[#667085]">Создание клиентов как на oauth.yandex.ru: client_id, secret, redirect URI и scopes</p>
</div>
<Button onClick={() => setDialogOpen(true)}>
<Button onClick={() => setDialogOpen(true)} disabled={!user?.canManageOAuth}>
<Plus className="h-4 w-4" />
Новое приложение
</Button>
@@ -134,7 +142,17 @@ export default function AdminOAuthPage() {
<CardHeader>
<LockKeyhole className="h-6 w-6" />
<CardTitle>{client.name}</CardTitle>
<CardDescription>{client.type === 'PUBLIC' ? 'Публичное приложение' : 'Confidential приложение'}</CardDescription>
<CardDescription>
{client.type === 'PUBLIC' ? 'Публичное приложение' : 'Confidential приложение'}
{client.createdByDisplayName ? (
<span className="mt-1 flex items-center gap-1.5 text-xs text-[#667085]">
<UserRound className="h-3.5 w-3.5" />
Создал: {client.createdByDisplayName}
</span>
) : client.createdById ? null : (
<span className="mt-1 block text-xs text-[#667085]">Создатель не указан</span>
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
@@ -161,6 +179,7 @@ export default function AdminOAuthPage() {
</div>
<p>{client.scopes.join(', ')}</p>
</div>
{client.canManage ? (
<div className="flex flex-wrap gap-2">
{client.type !== 'PUBLIC' ? (
<Button variant="secondary" size="sm" onClick={() => void handleRotateSecret(client.clientId)}>
@@ -172,6 +191,9 @@ export default function AdminOAuthPage() {
{client.isActive ? 'Отключить' : 'Включить'}
</Button>
</div>
) : (
<p className="text-xs text-[#667085]">Только просмотр управление доступно создателю или администратору с полными правами</p>
)}
</CardContent>
</Card>
))}

View File

@@ -1,5 +1,22 @@
import { redirect } from 'next/navigation';
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/components/id/auth-provider';
import { getAdminLandingPath } from '@/lib/admin-access';
export default function AdminIndexPage() {
redirect('/admin/users');
const router = useRouter();
const { user, isLoading } = useAuth();
useEffect(() => {
if (isLoading || !user) return;
router.replace(getAdminLandingPath(user));
}, [isLoading, router, user]);
return (
<div className="flex min-h-[40vh] items-center justify-center text-[#667085]">
Перенаправление в админ-панель...
</div>
);
}

View File

@@ -1,6 +1,7 @@
'use client';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Ban, Crown, FileText, KeyRound, Loader2, Search, ShieldPlus, UserCheck, UserCog } from 'lucide-react';
import { UserDocumentsDialog } from '@/components/documents/user-documents-dialog';
import { AdminShell } from '@/components/id/admin-shell';
@@ -11,6 +12,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
import { Input } from '@/components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { AdminRole, AdminUser, apiFetch } from '@/lib/api';
import { getAdminLandingPath } from '@/lib/admin-access';
const statusLabels: Record<string, string> = {
ACTIVE: 'Активен',
@@ -26,6 +28,7 @@ const roleLabels: Record<string, string> = {
};
export default function AdminUsersPage() {
const router = useRouter();
const { token, user: currentUser } = useAuth();
const { showToast } = useToast();
const [users, setUsers] = useState<AdminUser[]>([]);
@@ -52,8 +55,16 @@ export default function AdminUsersPage() {
}, [search, showToast, token]);
useEffect(() => {
if (!currentUser) return;
if (!currentUser.canViewUsers && !currentUser.canManageUsers) {
router.replace(getAdminLandingPath(currentUser));
}
}, [currentUser, router]);
useEffect(() => {
if (!currentUser?.canViewUsers && !currentUser?.canManageUsers) return;
void loadUsers();
}, [loadUsers]);
}, [currentUser?.canManageUsers, currentUser?.canViewUsers, loadUsers]);
useEffect(() => {
if (!token || !currentUser?.canManageRoles) return;

View File

@@ -3,11 +3,12 @@
import { ShieldCheck, Sparkles } from 'lucide-react';
import { cn } from '@/lib/utils';
import { PublicUser } from '@/lib/api';
import { getPrimaryRoleLabel } from '@/lib/admin-access';
export function AdminBadge({ user, className }: { user: PublicUser; className?: string }) {
if (!user.isSuperAdmin && !user.canAccessAdmin) return null;
const label = user.isSuperAdmin ? 'Супер-админ' : user.roles?.includes('admin') ? 'Администратор' : 'Админ';
const label = getPrimaryRoleLabel(user);
return (
<span

View File

@@ -6,16 +6,37 @@ import { cn } from '@/lib/utils';
import { PublicUser } from '@/lib/api';
const links = [
{ href: '/admin/users', label: 'Пользователи', icon: Users, permission: 'canViewUsers' as const, altPermission: 'canManageUsers' as const },
{ href: '/admin/oauth', label: 'OAuth', icon: Boxes, permission: 'canManageOAuth' as const },
{ href: '/admin/rbac', label: 'Роли', icon: ShieldCheck, permission: 'canManageRoles' as const, superAdminOnly: true },
{ href: '/admin/settings', label: 'Настройки', icon: Settings2, permission: 'canManageSettings' as const }
{
href: '/admin/users',
label: 'Пользователи',
icon: Users,
permissions: ['canViewUsers', 'canManageUsers'] as const
},
{
href: '/admin/oauth',
label: 'OAuth',
icon: Boxes,
permissions: ['canViewOAuth', 'canManageOAuth'] as const
},
{
href: '/admin/rbac',
label: 'Роли',
icon: ShieldCheck,
permissions: ['canManageRoles'] as const,
superAdminOnly: true
},
{
href: '/admin/settings',
label: 'Настройки',
icon: Settings2,
permissions: ['canManageSettings'] as const
}
];
export function AdminNav({ active, user }: { active: string; user: PublicUser }) {
const visible = links.filter((link) => {
if (link.superAdminOnly && !user.canManageRoles) return false;
return Boolean(user[link.permission]) || (link.altPermission ? Boolean(user[link.altPermission]) : false) || user.isSuperAdmin;
return link.permissions.some((permission) => Boolean(user[permission])) || user.isSuperAdmin;
});
return (

View File

@@ -30,7 +30,7 @@ export function AdminShell({ active, children }: { active: string; children: Rea
}
return (
<IdShell active="/admin/users" wide>
<IdShell active={active} wide>
<div className="mb-6 flex flex-wrap items-start justify-between gap-4">
<div>
<div className="mb-2 flex items-center gap-2">

View File

@@ -4,6 +4,7 @@ import Link from 'next/link';
import { FileText, Heart, Home, LockKeyhole, LogOut, ShieldCheck, UserRound } from 'lucide-react';
import { BrandLogo } from '@/components/id/brand-logo';
import { cn } from '@/lib/utils';
import { getAdminLandingPath } from '@/lib/admin-access';
import { useAuth } from './auth-provider';
const baseItems = [
@@ -17,7 +18,7 @@ const baseItems = [
export function Sidebar({ active }: { active: string }) {
const { logout, user } = useAuth();
const items = user?.canAccessAdmin
? [...baseItems, { href: '/admin/users', label: 'Админка', icon: ShieldCheck }]
? [...baseItems, { href: getAdminLandingPath(user), label: 'Админка', icon: ShieldCheck }]
: baseItems;
return (

View File

@@ -15,6 +15,7 @@ import {
import { AdminBadge } from '@/components/id/admin-badge';
import { useAuth } from '@/components/id/auth-provider';
import { useAvatarUrl } from '@/hooks/use-avatar-url';
import { getAdminLandingPath } from '@/lib/admin-access';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
@@ -94,11 +95,11 @@ export function UserMenu({ className }: { className?: string }) {
))}
{user.canAccessAdmin ? (
<Link href="/admin/users" className="mt-1 flex items-center gap-3 rounded-[18px] px-3 py-3 transition hover:bg-[#f4f5f8]">
<Link href={getAdminLandingPath(user)} className="mt-1 flex items-center gap-3 rounded-[18px] px-3 py-3 transition hover:bg-[#f4f5f8]">
<ShieldCheck className="h-5 w-5 shrink-0 text-[#667085]" />
<div className="min-w-0 flex-1 text-left">
<div className="font-medium">Админ-панель</div>
<div className="text-xs text-[#667085]">Пользователи, OAuth и настройки</div>
<div className="text-xs text-[#667085]">OAuth, пользователи и настройки</div>
</div>
<ChevronRight className="h-4 w-4 text-[#a8adbc]" />
</Link>

View File

@@ -0,0 +1,41 @@
import { PublicUser } from '@/lib/api';
export const ROLE_LABELS: Record<string, string> = {
admin: 'Администратор',
moderator: 'Модератор',
manager: 'Менеджер',
'super-admin': 'Супер-админ'
};
export function getPrimaryRoleLabel(user: PublicUser): string {
if (user.isSuperAdmin) return ROLE_LABELS['super-admin'];
const slugs = user.roles ?? [];
if (slugs.includes('admin')) return ROLE_LABELS.admin;
for (const slug of slugs) {
if (ROLE_LABELS[slug]) return ROLE_LABELS[slug];
}
return slugs[0] ?? 'Админ';
}
export function getAdminLandingPath(user: PublicUser): string {
if (user.canViewUsers || user.canManageUsers) return '/admin/users';
if (user.canViewOAuth || user.canManageOAuth) return '/admin/oauth';
if (user.canManageSettings) return '/admin/settings';
if (user.canManageRoles) return '/admin/rbac';
return '/admin/oauth';
}
export function canAccessAdminSection(user: PublicUser, section: 'users' | 'oauth' | 'settings' | 'rbac') {
switch (section) {
case 'users':
return Boolean(user.canViewUsers || user.canManageUsers);
case 'oauth':
return Boolean(user.canViewOAuth || user.canManageOAuth);
case 'settings':
return Boolean(user.canManageSettings);
case 'rbac':
return Boolean(user.canManageRoles);
default:
return false;
}
}

View File

@@ -70,8 +70,11 @@ export interface PublicUser {
permissions?: string[];
canAccessAdmin?: boolean;
canManageRoles?: boolean;
canViewOAuth?: boolean;
canManageOAuth?: boolean;
canManageAllOAuth?: boolean;
canManageUsers?: boolean;
canManageAllUsers?: boolean;
canManageSettings?: boolean;
canViewUsers?: boolean;
canViewUserDocuments?: boolean;
@@ -121,6 +124,9 @@ export interface OAuthClient {
isActive: boolean;
type: string;
clientSecret?: string;
createdById?: string | null;
createdByDisplayName?: string | null;
canManage?: boolean;
}
export interface AuthTokens {

View File

@@ -75,6 +75,7 @@ model User {
chatMessages ChatMessage[]
chatPollVotes ChatPollVote[]
totpSecret UserTotpSecret?
createdOAuthClients OAuthClient[] @relation("OAuthClientCreator")
}
model UserTotpSecret {
@@ -226,10 +227,14 @@ model OAuthClient {
redirectUris String[]
scopes OAuthClientScope[]
isActive Boolean @default(true)
createdById String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdBy User? @relation("OAuthClientCreator", fields: [createdById], references: [id], onDelete: SetNull)
consents OAuthConsent[]
authCodes OAuthAuthorizationCode[]
@@index([createdById])
}
model OAuthAuthorizationCode {

View File

@@ -6,13 +6,20 @@ export interface UserAccessContext {
permissions: string[];
canAccessAdmin: boolean;
canManageRoles: boolean;
canViewOAuth: boolean;
canManageOAuth: boolean;
canManageAllOAuth: boolean;
canManageUsers: boolean;
canManageAllUsers: boolean;
canViewUsers: boolean;
canManageSettings: boolean;
canViewUserDocuments: boolean;
}
function hasAnyPermission(permissions: string[], ...slugs: string[]) {
return slugs.some((slug) => permissions.includes(slug));
}
@Injectable()
export class AccessService {
constructor(private readonly prisma: PrismaService) {}
@@ -21,11 +28,27 @@ export class AccessService {
if (isSuperAdmin) {
return {
roles: ['super-admin'],
permissions: ['admin.access', 'oauth.manage', 'users.manage', 'users.read', 'settings.manage', 'rbac.manage', 'documents.view_others'],
permissions: [
'admin.access',
'oauth.view',
'oauth.view.all',
'oauth.manage',
'oauth.manage.all',
'users.view',
'users.view.all',
'users.manage',
'users.manage.all',
'settings.manage',
'rbac.manage',
'documents.view_others'
],
canAccessAdmin: true,
canManageRoles: true,
canViewOAuth: true,
canManageOAuth: true,
canManageAllOAuth: true,
canManageUsers: true,
canManageAllUsers: true,
canViewUsers: true,
canManageSettings: true,
canViewUserDocuments: true
@@ -48,19 +71,39 @@ export class AccessService {
const roles = links.map((link) => link.role.slug);
const permissions = [...new Set(links.flatMap((link) => link.role.permissions.map((item) => item.permission.slug)))];
const canViewOAuth = hasAnyPermission(permissions, 'oauth.view', 'oauth.view.all', 'oauth.manage', 'oauth.manage.all');
const canManageOAuth = hasAnyPermission(permissions, 'oauth.manage', 'oauth.manage.all');
const canManageAllOAuth = permissions.includes('oauth.manage.all');
const canViewUsers = hasAnyPermission(permissions, 'users.view', 'users.view.all', 'users.manage', 'users.manage.all', 'users.read');
const canManageUsers = hasAnyPermission(permissions, 'users.manage', 'users.manage.all');
const canManageAllUsers = permissions.includes('users.manage.all');
return {
roles,
permissions,
canAccessAdmin: permissions.includes('admin.access'),
canManageRoles: false,
canManageOAuth: permissions.includes('oauth.manage'),
canManageUsers: permissions.includes('users.manage'),
canViewUsers: permissions.includes('users.manage') || permissions.includes('users.read'),
canViewOAuth,
canManageOAuth,
canManageAllOAuth,
canManageUsers,
canManageAllUsers,
canViewUsers,
canManageSettings: permissions.includes('settings.manage'),
canViewUserDocuments: permissions.includes('documents.view_others')
};
}
canManageOAuthClient(
access: UserAccessContext,
actorUserId: string,
client: { createdById: string | null }
) {
if (access.canManageAllOAuth) return true;
if (access.canManageOAuth && client.createdById === actorUserId) return true;
return false;
}
async assertSuperAdmin(actorUserId: string) {
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
if (!actor?.isSuperAdmin) {

View File

@@ -4,9 +4,15 @@ import { RbacService } from './rbac.service';
const PERMISSIONS = [
{ slug: 'admin.access', name: 'Доступ к админ-панели', description: 'Позволяет открывать раздел администрирования' },
{ slug: 'oauth.manage', name: 'Управление OAuth-приложениями', description: 'Создание и редактирование OAuth2-клиентов' },
{ slug: 'oauth.view', name: 'Просмотр OAuth-приложений', description: 'Просмотр списка OAuth2-клиентов' },
{ slug: 'oauth.view.all', name: 'Просмотр всех OAuth-приложений', description: 'Просмотр OAuth2-клиентов, созданных другими пользователями' },
{ slug: 'oauth.manage', name: 'Управление своими OAuth-приложениями', description: 'Создание и редактирование собственных OAuth2-клиентов' },
{ slug: 'oauth.manage.all', name: 'Управление всеми OAuth-приложениями', description: 'Создание и редактирование любых OAuth2-клиентов' },
{ slug: 'users.view', name: 'Просмотр пользователей', description: 'Чтение списка пользователей без изменений' },
{ slug: 'users.view.all', name: 'Просмотр всех пользователей', description: 'Просмотр полного списка пользователей системы' },
{ slug: 'users.manage', name: 'Управление пользователями', description: 'Редактирование, блокировка и сброс паролей' },
{ slug: 'users.read', name: росмотр пользователей', description: 'Чтение списка пользователей без изменений' },
{ 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: 'documents.view_others', name: 'Просмотр документов пользователей', description: 'Просмотр документов и фото других пользователей' }
@@ -17,19 +23,19 @@ const ROLES = [
slug: 'admin',
name: 'Администратор',
description: 'Полный доступ к админ-панели без назначения ролей',
permissions: ['admin.access', 'oauth.manage', 'users.manage', 'settings.manage']
permissions: ['admin.access', 'oauth.manage.all', 'oauth.view.all', 'users.manage.all', 'users.view.all', 'settings.manage']
},
{
slug: 'moderator',
name: 'Модератор',
description: 'Просмотр пользователей и базовый доступ к админке',
permissions: ['admin.access', 'users.read']
permissions: ['admin.access', 'users.view', 'users.view.all']
},
{
slug: 'manager',
name: 'Менеджер',
description: 'Управление OAuth-приложениями',
permissions: ['admin.access', 'oauth.manage']
permissions: ['admin.access', 'oauth.manage', 'oauth.view']
}
] as const;

View File

@@ -177,17 +177,20 @@ export class AuthGrpcController {
}
@GrpcMethod('RbacService', 'ListOAuthClients')
async listOAuthClients() {
const clients = await this.rbac.listOAuthClients();
async listOAuthClients(command: { actorUserId: string }) {
const clients = await this.rbac.listOAuthClients(command.actorUserId);
return {
clients: clients.map((client) => ({
id: client.id,
name: client.name,
clientId: client.clientId,
redirectUris: client.redirectUris,
scopes: client.scopes.map((link) => link.scope.slug),
scopes: client.scopes,
isActive: client.isActive,
type: client.type
type: client.type,
createdById: client.createdById ?? undefined,
createdByDisplayName: client.createdByDisplayName ?? undefined,
canManage: client.canManage
}))
};
}

View File

@@ -735,8 +735,11 @@ export class AuthService {
permissions: access.permissions,
canAccessAdmin: access.canAccessAdmin,
canManageRoles: access.canManageRoles,
canViewOAuth: access.canViewOAuth,
canManageOAuth: access.canManageOAuth,
canManageAllOAuth: access.canManageAllOAuth,
canManageUsers: access.canManageUsers,
canManageAllUsers: access.canManageAllUsers,
canManageSettings: access.canManageSettings,
canViewUsers: access.canViewUsers,
canViewUserDocuments: access.canViewUserDocuments

View File

@@ -43,8 +43,11 @@ export interface PublicUser {
permissions?: string[];
canAccessAdmin?: boolean;
canManageRoles?: boolean;
canViewOAuth?: boolean;
canManageOAuth?: boolean;
canManageAllOAuth?: boolean;
canManageUsers?: boolean;
canManageAllUsers?: boolean;
canManageSettings?: boolean;
canViewUsers?: boolean;
canViewUserDocuments?: boolean;

View File

@@ -2,7 +2,20 @@ import { BadRequestException, ForbiddenException, Injectable, NotFoundException
import { randomBytes } from 'node:crypto';
import { OAuthClientType } from '../generated/prisma/client';
import { PrismaService } from '../infra/prisma.service';
import { AccessService } from './access.service';
import { AccessService, UserAccessContext } from './access.service';
export interface OAuthClientListItem {
id: string;
name: string;
clientId: string;
redirectUris: string[];
scopes: string[];
isActive: boolean;
type: OAuthClientType;
createdById?: string | null;
createdByDisplayName?: string | null;
canManage: boolean;
}
@Injectable()
export class RbacService {
@@ -79,7 +92,7 @@ export class RbacService {
}
async createOAuthClient(actorUserId: string, data: { name: string; redirectUris: string[]; scopes: string[]; type?: OAuthClientType }) {
await this.assertOAuthPermission(actorUserId);
await this.assertCanCreateOAuth(actorUserId);
if (!data.redirectUris.length) {
throw new BadRequestException('Укажите хотя бы один redirect URI');
}
@@ -95,13 +108,14 @@ export class RbacService {
clientSecret,
redirectUris: data.redirectUris,
type: data.type ?? OAuthClientType.CONFIDENTIAL,
createdById: actorUserId,
scopes: {
create: data.scopes.map((slug) => ({
scope: { connect: { slug } }
}))
}
},
include: { scopes: { include: { scope: true } } }
include: { scopes: { include: { scope: true } }, createdBy: true }
});
return { client, clientSecret };
@@ -112,7 +126,6 @@ export class RbacService {
clientId: string,
data: { name?: string; redirectUris?: string[]; scopes?: string[]; isActive?: boolean }
) {
await this.assertOAuthPermission(actorUserId);
const existing = await this.prisma.oAuthClient.findUnique({
where: { clientId },
include: { scopes: true }
@@ -120,6 +133,7 @@ export class RbacService {
if (!existing) {
throw new NotFoundException('OAuth-приложение не найдено');
}
await this.assertCanManageOAuthClient(actorUserId, existing);
if (data.redirectUris && !data.redirectUris.length) {
throw new BadRequestException('Укажите хотя бы один redirect URI');
@@ -143,18 +157,18 @@ export class RbacService {
redirectUris: data.redirectUris,
isActive: data.isActive
},
include: { scopes: { include: { scope: true } } }
include: { scopes: { include: { scope: true } }, createdBy: true }
});
return { client: updated, clientSecret: undefined as string | undefined };
}
async rotateOAuthSecret(actorUserId: string, clientId: string) {
await this.assertOAuthPermission(actorUserId);
const existing = await this.prisma.oAuthClient.findUnique({ where: { clientId } });
if (!existing) {
throw new NotFoundException('OAuth-приложение не найдено');
}
await this.assertCanManageOAuthClient(actorUserId, existing);
if (existing.type === OAuthClientType.PUBLIC) {
throw new BadRequestException('У публичного клиента нет client secret');
}
@@ -168,24 +182,72 @@ export class RbacService {
return { clientId, clientSecret };
}
async listOAuthClients() {
return this.prisma.oAuthClient.findMany({
orderBy: { createdAt: 'desc' },
include: { scopes: { include: { scope: true } } }
});
async listOAuthClients(actorUserId: string): Promise<OAuthClientListItem[]> {
const { access } = await this.getActorAccess(actorUserId);
if (!access.canViewOAuth) {
throw new ForbiddenException('Недостаточно прав для просмотра OAuth-приложений');
}
private async assertOAuthPermission(actorUserId: string) {
const clients = await this.prisma.oAuthClient.findMany({
orderBy: { createdAt: 'desc' },
include: { scopes: { include: { scope: true } }, createdBy: true }
});
return clients.map((client) => this.toOAuthClientListItem(client, actorUserId, access));
}
private toOAuthClientListItem(
client: {
id: string;
name: string;
clientId: string;
redirectUris: string[];
isActive: boolean;
type: OAuthClientType;
createdById: string | null;
createdBy?: { displayName: string } | null;
scopes: Array<{ scope: { slug: string } }>;
},
actorUserId: string,
access: UserAccessContext
): OAuthClientListItem {
return {
id: client.id,
name: client.name,
clientId: client.clientId,
redirectUris: client.redirectUris,
scopes: client.scopes.map((link) => link.scope.slug),
isActive: client.isActive,
type: client.type,
createdById: client.createdById,
createdByDisplayName: client.createdBy?.displayName ?? null,
canManage: this.access.canManageOAuthClient(access, actorUserId, client)
};
}
private async getActorAccess(actorUserId: string) {
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
if (!actor) {
throw new NotFoundException('Пользователь не найден');
}
const access = await this.access.getUserAccess(actor.id, actor.isSuperAdmin);
return { actor, access };
}
private async assertCanCreateOAuth(actorUserId: string) {
const { access } = await this.getActorAccess(actorUserId);
if (!access.canManageOAuth) {
throw new ForbiddenException('Недостаточно прав для управления OAuth-приложениями');
}
}
private async assertCanManageOAuthClient(actorUserId: string, client: { createdById: string | null }) {
const { access } = await this.getActorAccess(actorUserId);
if (!this.access.canManageOAuthClient(access, actorUserId, client)) {
throw new ForbiddenException('Недостаточно прав для изменения этого OAuth-приложения');
}
}
private async getUserRoleSlugs(userId: string) {
const links = await this.prisma.userRole.findMany({
where: { userId },

View File

@@ -185,6 +185,9 @@ message PublicUser {
bool canViewUsers = 19;
bool canViewUserDocuments = 20;
bool hasPassword = 21;
bool canViewOAuth = 22;
bool canManageAllOAuth = 23;
bool canManageAllUsers = 24;
}
message AuthTokens {

View File

@@ -6,7 +6,7 @@ service RbacService {
rpc ListRoles (Empty) returns (ListRolesResponse);
rpc ListPermissions (Empty) returns (ListPermissionsResponse);
rpc ListOAuthScopes (Empty) returns (ListOAuthScopesResponse);
rpc ListOAuthClients (Empty) returns (ListOAuthClientsResponse);
rpc ListOAuthClients (ListOAuthClientsRequest) returns (ListOAuthClientsResponse);
rpc CreateRole (CreateRoleRequest) returns (Role);
rpc AssignUserRole (AssignUserRoleRequest) returns (AssignUserRoleResponse);
rpc RemoveUserRole (RemoveUserRoleRequest) returns (Empty);
@@ -47,6 +47,9 @@ message OAuthClient {
repeated string scopes = 5;
bool isActive = 6;
string type = 7;
optional string createdById = 8;
optional string createdByDisplayName = 9;
bool canManage = 10;
}
message OAuthClientDetail {
@@ -58,6 +61,9 @@ message OAuthClientDetail {
bool isActive = 6;
string type = 7;
optional string clientSecret = 8;
optional string createdById = 9;
optional string createdByDisplayName = 10;
bool canManage = 11;
}
message ListRolesResponse {
@@ -76,6 +82,10 @@ message ListOAuthClientsResponse {
repeated OAuthClient clients = 1;
}
message ListOAuthClientsRequest {
string actorUserId = 1;
}
message CreateRoleRequest {
string actorUserId = 1;
string slug = 2;