update oauth
This commit is contained in:
@@ -4,7 +4,7 @@ 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 { 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')
|
@ApiTags('RBAC и OAuth')
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@@ -39,15 +39,15 @@ export class RbacController {
|
|||||||
@Get('oauth-scopes')
|
@Get('oauth-scopes')
|
||||||
@ApiOperation({ summary: 'OAuth scopes', description: 'Возвращает доступные scopes для OAuth-приложений.' })
|
@ApiOperation({ summary: 'OAuth scopes', description: 'Возвращает доступные scopes для OAuth-приложений.' })
|
||||||
listOAuthScopes(@CurrentAdmin() admin: AdminRequestUser) {
|
listOAuthScopes(@CurrentAdmin() admin: AdminRequestUser) {
|
||||||
assertAdminPermission(admin, 'canManageOAuth');
|
assertAdminAnyPermission(admin, 'canViewOAuth', 'canManageOAuth');
|
||||||
return this.core.rbac.ListOAuthScopes({});
|
return this.core.rbac.ListOAuthScopes({});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('oauth-clients')
|
@Get('oauth-clients')
|
||||||
@ApiOperation({ summary: 'OAuth приложения', description: 'Возвращает OAuth-клиенты и доступные scopes.' })
|
@ApiOperation({ summary: 'OAuth приложения', description: 'Возвращает OAuth-клиенты и доступные scopes.' })
|
||||||
listOAuthClients(@CurrentAdmin() admin: AdminRequestUser) {
|
listOAuthClients(@CurrentAdmin() admin: AdminRequestUser) {
|
||||||
assertAdminPermission(admin, 'canManageOAuth');
|
assertAdminPermission(admin, 'canViewOAuth');
|
||||||
return this.core.rbac.ListOAuthClients({});
|
return this.core.rbac.ListOAuthClients({ actorUserId: admin.id });
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('roles')
|
@Post('roles')
|
||||||
|
|||||||
@@ -9,8 +9,11 @@ export interface AdminRequestUser {
|
|||||||
isSuperAdmin: boolean;
|
isSuperAdmin: boolean;
|
||||||
canAccessAdmin: boolean;
|
canAccessAdmin: boolean;
|
||||||
canManageRoles: boolean;
|
canManageRoles: boolean;
|
||||||
|
canViewOAuth: boolean;
|
||||||
canManageOAuth: boolean;
|
canManageOAuth: boolean;
|
||||||
|
canManageAllOAuth: boolean;
|
||||||
canManageUsers: boolean;
|
canManageUsers: boolean;
|
||||||
|
canManageAllUsers: boolean;
|
||||||
canViewUsers: boolean;
|
canViewUsers: boolean;
|
||||||
canManageSettings: boolean;
|
canManageSettings: boolean;
|
||||||
roles: string[];
|
roles: string[];
|
||||||
@@ -48,8 +51,11 @@ export class AdminGuard implements CanActivate {
|
|||||||
isSuperAdmin: profile.isSuperAdmin,
|
isSuperAdmin: profile.isSuperAdmin,
|
||||||
canAccessAdmin: Boolean(profile.canAccessAdmin),
|
canAccessAdmin: Boolean(profile.canAccessAdmin),
|
||||||
canManageRoles: Boolean(profile.canManageRoles),
|
canManageRoles: Boolean(profile.canManageRoles),
|
||||||
|
canViewOAuth: Boolean(profile.canViewOAuth),
|
||||||
canManageOAuth: Boolean(profile.canManageOAuth),
|
canManageOAuth: Boolean(profile.canManageOAuth),
|
||||||
|
canManageAllOAuth: Boolean(profile.canManageAllOAuth),
|
||||||
canManageUsers: Boolean(profile.canManageUsers),
|
canManageUsers: Boolean(profile.canManageUsers),
|
||||||
|
canManageAllUsers: Boolean(profile.canManageAllUsers),
|
||||||
canManageSettings: Boolean(profile.canManageSettings),
|
canManageSettings: Boolean(profile.canManageSettings),
|
||||||
canViewUsers: Boolean(profile.canViewUsers),
|
canViewUsers: Boolean(profile.canViewUsers),
|
||||||
roles: profile.roles ?? [],
|
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]) {
|
if (!user?.[permission]) {
|
||||||
throw new ForbiddenException('Недостаточно прав для выполнения действия');
|
throw new ForbiddenException('Недостаточно прав для выполнения действия');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function assertAdminAnyPermission(user: AdminRequestUser | undefined, ...permissions: AdminPermissionKey[]) {
|
||||||
|
if (!user || !permissions.some((permission) => user[permission])) {
|
||||||
|
throw new ForbiddenException('Недостаточно прав для выполнения действия');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from 'react';
|
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 { 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';
|
||||||
@@ -10,9 +11,11 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
|||||||
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 { OAuthClient, OAuthScope, apiFetch } from '@/lib/api';
|
import { OAuthClient, OAuthScope, apiFetch } from '@/lib/api';
|
||||||
|
import { getAdminLandingPath } from '@/lib/admin-access';
|
||||||
|
|
||||||
export default function AdminOAuthPage() {
|
export default function AdminOAuthPage() {
|
||||||
const { token } = useAuth();
|
const router = useRouter();
|
||||||
|
const { token, user } = useAuth();
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
const [clients, setClients] = useState<OAuthClient[]>([]);
|
const [clients, setClients] = useState<OAuthClient[]>([]);
|
||||||
const [scopes, setScopes] = useState<OAuthScope[]>([]);
|
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 [form, setForm] = useState({ name: '', redirectUris: '', type: 'CONFIDENTIAL', selectedScopes: ['openid', 'profile', 'email'] as string[] });
|
||||||
|
|
||||||
const loadData = useCallback(async () => {
|
const loadData = useCallback(async () => {
|
||||||
if (!token) return;
|
if (!token || !user?.canViewOAuth) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const [clientsResponse, scopesResponse] = await Promise.all([
|
const clientsResponse = await apiFetch<{ clients: OAuthClient[] }>('/admin/rbac/oauth-clients', {}, token);
|
||||||
apiFetch<{ clients: OAuthClient[] }>('/admin/rbac/oauth-clients', {}, token),
|
|
||||||
apiFetch<{ scopes: OAuthScope[] }>('/admin/rbac/oauth-scopes', {}, token)
|
|
||||||
]);
|
|
||||||
setClients(clientsResponse.clients ?? []);
|
setClients(clientsResponse.clients ?? []);
|
||||||
|
if (user.canManageOAuth) {
|
||||||
|
const scopesResponse = await apiFetch<{ scopes: OAuthScope[] }>('/admin/rbac/oauth-scopes', {}, token);
|
||||||
setScopes(scopesResponse.scopes ?? []);
|
setScopes(scopesResponse.scopes ?? []);
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showToast(error instanceof Error ? error.message : 'Не удалось загрузить OAuth-приложения');
|
showToast(error instanceof Error ? error.message : 'Не удалось загрузить OAuth-приложения');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [showToast, token]);
|
}, [showToast, token, user?.canManageOAuth, user?.canViewOAuth]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!user) return;
|
||||||
|
if (!user.canViewOAuth && !user.canManageOAuth) {
|
||||||
|
router.replace(getAdminLandingPath(user));
|
||||||
|
return;
|
||||||
|
}
|
||||||
void loadData();
|
void loadData();
|
||||||
}, [loadData]);
|
}, [loadData, router, user]);
|
||||||
|
|
||||||
async function handleCreate() {
|
async function handleCreate() {
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
@@ -116,7 +124,7 @@ export default function AdminOAuthPage() {
|
|||||||
<h2 className="text-2xl font-medium">OAuth-приложения</h2>
|
<h2 className="text-2xl font-medium">OAuth-приложения</h2>
|
||||||
<p className="text-sm text-[#667085]">Создание клиентов как на oauth.yandex.ru: client_id, secret, redirect URI и scopes</p>
|
<p className="text-sm text-[#667085]">Создание клиентов как на oauth.yandex.ru: client_id, secret, redirect URI и scopes</p>
|
||||||
</div>
|
</div>
|
||||||
<Button onClick={() => setDialogOpen(true)}>
|
<Button onClick={() => setDialogOpen(true)} disabled={!user?.canManageOAuth}>
|
||||||
<Plus className="h-4 w-4" />
|
<Plus className="h-4 w-4" />
|
||||||
Новое приложение
|
Новое приложение
|
||||||
</Button>
|
</Button>
|
||||||
@@ -134,7 +142,17 @@ export default function AdminOAuthPage() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<LockKeyhole className="h-6 w-6" />
|
<LockKeyhole className="h-6 w-6" />
|
||||||
<CardTitle>{client.name}</CardTitle>
|
<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>
|
</CardHeader>
|
||||||
<CardContent className="space-y-3">
|
<CardContent className="space-y-3">
|
||||||
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
|
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
|
||||||
@@ -161,6 +179,7 @@ export default function AdminOAuthPage() {
|
|||||||
</div>
|
</div>
|
||||||
<p>{client.scopes.join(', ')}</p>
|
<p>{client.scopes.join(', ')}</p>
|
||||||
</div>
|
</div>
|
||||||
|
{client.canManage ? (
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{client.type !== 'PUBLIC' ? (
|
{client.type !== 'PUBLIC' ? (
|
||||||
<Button variant="secondary" size="sm" onClick={() => void handleRotateSecret(client.clientId)}>
|
<Button variant="secondary" size="sm" onClick={() => void handleRotateSecret(client.clientId)}>
|
||||||
@@ -172,6 +191,9 @@ export default function AdminOAuthPage() {
|
|||||||
{client.isActive ? 'Отключить' : 'Включить'}
|
{client.isActive ? 'Отключить' : 'Включить'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-xs text-[#667085]">Только просмотр — управление доступно создателю или администратору с полными правами</p>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -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() {
|
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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
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 { Ban, Crown, FileText, KeyRound, Loader2, Search, ShieldPlus, UserCheck, UserCog } from 'lucide-react';
|
||||||
import { UserDocumentsDialog } from '@/components/documents/user-documents-dialog';
|
import { UserDocumentsDialog } from '@/components/documents/user-documents-dialog';
|
||||||
import { AdminShell } from '@/components/id/admin-shell';
|
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 { 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 { AdminRole, AdminUser, apiFetch } from '@/lib/api';
|
||||||
|
import { getAdminLandingPath } from '@/lib/admin-access';
|
||||||
|
|
||||||
const statusLabels: Record<string, string> = {
|
const statusLabels: Record<string, string> = {
|
||||||
ACTIVE: 'Активен',
|
ACTIVE: 'Активен',
|
||||||
@@ -26,6 +28,7 @@ const roleLabels: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function AdminUsersPage() {
|
export default function AdminUsersPage() {
|
||||||
|
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[]>([]);
|
||||||
@@ -52,8 +55,16 @@ export default function AdminUsersPage() {
|
|||||||
}, [search, showToast, token]);
|
}, [search, showToast, token]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!currentUser) return;
|
||||||
|
if (!currentUser.canViewUsers && !currentUser.canManageUsers) {
|
||||||
|
router.replace(getAdminLandingPath(currentUser));
|
||||||
|
}
|
||||||
|
}, [currentUser, router]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!currentUser?.canViewUsers && !currentUser?.canManageUsers) return;
|
||||||
void loadUsers();
|
void loadUsers();
|
||||||
}, [loadUsers]);
|
}, [currentUser?.canManageUsers, currentUser?.canViewUsers, loadUsers]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!token || !currentUser?.canManageRoles) return;
|
if (!token || !currentUser?.canManageRoles) return;
|
||||||
|
|||||||
@@ -3,11 +3,12 @@
|
|||||||
import { ShieldCheck, Sparkles } from 'lucide-react';
|
import { ShieldCheck, Sparkles } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { PublicUser } from '@/lib/api';
|
import { PublicUser } from '@/lib/api';
|
||||||
|
import { getPrimaryRoleLabel } from '@/lib/admin-access';
|
||||||
|
|
||||||
export function AdminBadge({ user, className }: { user: PublicUser; className?: string }) {
|
export function AdminBadge({ user, className }: { user: PublicUser; className?: string }) {
|
||||||
if (!user.isSuperAdmin && !user.canAccessAdmin) return null;
|
if (!user.isSuperAdmin && !user.canAccessAdmin) return null;
|
||||||
|
|
||||||
const label = user.isSuperAdmin ? 'Супер-админ' : user.roles?.includes('admin') ? 'Администратор' : 'Админ';
|
const label = getPrimaryRoleLabel(user);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
|
|||||||
@@ -6,16 +6,37 @@ import { cn } from '@/lib/utils';
|
|||||||
import { PublicUser } from '@/lib/api';
|
import { PublicUser } from '@/lib/api';
|
||||||
|
|
||||||
const links = [
|
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/users',
|
||||||
{ href: '/admin/rbac', label: 'Роли', icon: ShieldCheck, permission: 'canManageRoles' as const, superAdminOnly: true },
|
label: 'Пользователи',
|
||||||
{ href: '/admin/settings', label: 'Настройки', icon: Settings2, permission: 'canManageSettings' as const }
|
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 }) {
|
export function AdminNav({ active, user }: { active: string; user: PublicUser }) {
|
||||||
const visible = links.filter((link) => {
|
const visible = links.filter((link) => {
|
||||||
if (link.superAdminOnly && !user.canManageRoles) return false;
|
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 (
|
return (
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export function AdminShell({ active, children }: { active: string; children: Rea
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<IdShell active="/admin/users" wide>
|
<IdShell active={active} wide>
|
||||||
<div className="mb-6 flex flex-wrap items-start justify-between gap-4">
|
<div className="mb-6 flex flex-wrap items-start justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-2 flex items-center gap-2">
|
<div className="mb-2 flex items-center gap-2">
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import Link from 'next/link';
|
|||||||
import { FileText, Heart, Home, LockKeyhole, LogOut, ShieldCheck, UserRound } from 'lucide-react';
|
import { FileText, Heart, Home, LockKeyhole, LogOut, ShieldCheck, UserRound } from 'lucide-react';
|
||||||
import { BrandLogo } from '@/components/id/brand-logo';
|
import { BrandLogo } from '@/components/id/brand-logo';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { getAdminLandingPath } from '@/lib/admin-access';
|
||||||
import { useAuth } from './auth-provider';
|
import { useAuth } from './auth-provider';
|
||||||
|
|
||||||
const baseItems = [
|
const baseItems = [
|
||||||
@@ -17,7 +18,7 @@ const baseItems = [
|
|||||||
export function Sidebar({ active }: { active: string }) {
|
export function Sidebar({ active }: { active: string }) {
|
||||||
const { logout, user } = useAuth();
|
const { logout, user } = useAuth();
|
||||||
const items = user?.canAccessAdmin
|
const items = user?.canAccessAdmin
|
||||||
? [...baseItems, { href: '/admin/users', label: 'Админка', icon: ShieldCheck }]
|
? [...baseItems, { href: getAdminLandingPath(user), label: 'Админка', icon: ShieldCheck }]
|
||||||
: baseItems;
|
: baseItems;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
import { AdminBadge } from '@/components/id/admin-badge';
|
import { AdminBadge } from '@/components/id/admin-badge';
|
||||||
import { useAuth } from '@/components/id/auth-provider';
|
import { useAuth } from '@/components/id/auth-provider';
|
||||||
import { useAvatarUrl } from '@/hooks/use-avatar-url';
|
import { useAvatarUrl } from '@/hooks/use-avatar-url';
|
||||||
|
import { getAdminLandingPath } from '@/lib/admin-access';
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
@@ -94,11 +95,11 @@ export function UserMenu({ className }: { className?: string }) {
|
|||||||
))}
|
))}
|
||||||
|
|
||||||
{user.canAccessAdmin ? (
|
{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]" />
|
<ShieldCheck className="h-5 w-5 shrink-0 text-[#667085]" />
|
||||||
<div className="min-w-0 flex-1 text-left">
|
<div className="min-w-0 flex-1 text-left">
|
||||||
<div className="font-medium">Админ-панель</div>
|
<div className="font-medium">Админ-панель</div>
|
||||||
<div className="text-xs text-[#667085]">Пользователи, OAuth и настройки</div>
|
<div className="text-xs text-[#667085]">OAuth, пользователи и настройки</div>
|
||||||
</div>
|
</div>
|
||||||
<ChevronRight className="h-4 w-4 text-[#a8adbc]" />
|
<ChevronRight className="h-4 w-4 text-[#a8adbc]" />
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
41
apps/frontend/lib/admin-access.ts
Normal file
41
apps/frontend/lib/admin-access.ts
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -70,8 +70,11 @@ export interface PublicUser {
|
|||||||
permissions?: string[];
|
permissions?: string[];
|
||||||
canAccessAdmin?: boolean;
|
canAccessAdmin?: boolean;
|
||||||
canManageRoles?: boolean;
|
canManageRoles?: boolean;
|
||||||
|
canViewOAuth?: boolean;
|
||||||
canManageOAuth?: boolean;
|
canManageOAuth?: boolean;
|
||||||
|
canManageAllOAuth?: boolean;
|
||||||
canManageUsers?: boolean;
|
canManageUsers?: boolean;
|
||||||
|
canManageAllUsers?: boolean;
|
||||||
canManageSettings?: boolean;
|
canManageSettings?: boolean;
|
||||||
canViewUsers?: boolean;
|
canViewUsers?: boolean;
|
||||||
canViewUserDocuments?: boolean;
|
canViewUserDocuments?: boolean;
|
||||||
@@ -121,6 +124,9 @@ export interface OAuthClient {
|
|||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
type: string;
|
type: string;
|
||||||
clientSecret?: string;
|
clientSecret?: string;
|
||||||
|
createdById?: string | null;
|
||||||
|
createdByDisplayName?: string | null;
|
||||||
|
canManage?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthTokens {
|
export interface AuthTokens {
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ model User {
|
|||||||
chatMessages ChatMessage[]
|
chatMessages ChatMessage[]
|
||||||
chatPollVotes ChatPollVote[]
|
chatPollVotes ChatPollVote[]
|
||||||
totpSecret UserTotpSecret?
|
totpSecret UserTotpSecret?
|
||||||
|
createdOAuthClients OAuthClient[] @relation("OAuthClientCreator")
|
||||||
}
|
}
|
||||||
|
|
||||||
model UserTotpSecret {
|
model UserTotpSecret {
|
||||||
@@ -226,10 +227,14 @@ model OAuthClient {
|
|||||||
redirectUris String[]
|
redirectUris String[]
|
||||||
scopes OAuthClientScope[]
|
scopes OAuthClientScope[]
|
||||||
isActive Boolean @default(true)
|
isActive Boolean @default(true)
|
||||||
|
createdById String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
createdBy User? @relation("OAuthClientCreator", fields: [createdById], references: [id], onDelete: SetNull)
|
||||||
consents OAuthConsent[]
|
consents OAuthConsent[]
|
||||||
authCodes OAuthAuthorizationCode[]
|
authCodes OAuthAuthorizationCode[]
|
||||||
|
|
||||||
|
@@index([createdById])
|
||||||
}
|
}
|
||||||
|
|
||||||
model OAuthAuthorizationCode {
|
model OAuthAuthorizationCode {
|
||||||
|
|||||||
@@ -6,13 +6,20 @@ export interface UserAccessContext {
|
|||||||
permissions: string[];
|
permissions: string[];
|
||||||
canAccessAdmin: boolean;
|
canAccessAdmin: boolean;
|
||||||
canManageRoles: boolean;
|
canManageRoles: boolean;
|
||||||
|
canViewOAuth: boolean;
|
||||||
canManageOAuth: boolean;
|
canManageOAuth: boolean;
|
||||||
|
canManageAllOAuth: boolean;
|
||||||
canManageUsers: boolean;
|
canManageUsers: boolean;
|
||||||
|
canManageAllUsers: boolean;
|
||||||
canViewUsers: boolean;
|
canViewUsers: boolean;
|
||||||
canManageSettings: boolean;
|
canManageSettings: boolean;
|
||||||
canViewUserDocuments: boolean;
|
canViewUserDocuments: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function hasAnyPermission(permissions: string[], ...slugs: string[]) {
|
||||||
|
return slugs.some((slug) => permissions.includes(slug));
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AccessService {
|
export class AccessService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
@@ -21,11 +28,27 @@ export class AccessService {
|
|||||||
if (isSuperAdmin) {
|
if (isSuperAdmin) {
|
||||||
return {
|
return {
|
||||||
roles: ['super-admin'],
|
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,
|
canAccessAdmin: true,
|
||||||
canManageRoles: true,
|
canManageRoles: true,
|
||||||
|
canViewOAuth: true,
|
||||||
canManageOAuth: true,
|
canManageOAuth: true,
|
||||||
|
canManageAllOAuth: true,
|
||||||
canManageUsers: true,
|
canManageUsers: true,
|
||||||
|
canManageAllUsers: true,
|
||||||
canViewUsers: true,
|
canViewUsers: true,
|
||||||
canManageSettings: true,
|
canManageSettings: true,
|
||||||
canViewUserDocuments: true
|
canViewUserDocuments: true
|
||||||
@@ -48,19 +71,39 @@ export class AccessService {
|
|||||||
const roles = links.map((link) => link.role.slug);
|
const roles = links.map((link) => link.role.slug);
|
||||||
const permissions = [...new Set(links.flatMap((link) => link.role.permissions.map((item) => item.permission.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 {
|
return {
|
||||||
roles,
|
roles,
|
||||||
permissions,
|
permissions,
|
||||||
canAccessAdmin: permissions.includes('admin.access'),
|
canAccessAdmin: permissions.includes('admin.access'),
|
||||||
canManageRoles: false,
|
canManageRoles: false,
|
||||||
canManageOAuth: permissions.includes('oauth.manage'),
|
canViewOAuth,
|
||||||
canManageUsers: permissions.includes('users.manage'),
|
canManageOAuth,
|
||||||
canViewUsers: permissions.includes('users.manage') || permissions.includes('users.read'),
|
canManageAllOAuth,
|
||||||
|
canManageUsers,
|
||||||
|
canManageAllUsers,
|
||||||
|
canViewUsers,
|
||||||
canManageSettings: permissions.includes('settings.manage'),
|
canManageSettings: permissions.includes('settings.manage'),
|
||||||
canViewUserDocuments: permissions.includes('documents.view_others')
|
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) {
|
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) {
|
||||||
|
|||||||
@@ -4,9 +4,15 @@ import { RbacService } from './rbac.service';
|
|||||||
|
|
||||||
const PERMISSIONS = [
|
const PERMISSIONS = [
|
||||||
{ slug: 'admin.access', name: 'Доступ к админ-панели', description: 'Позволяет открывать раздел администрирования' },
|
{ 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.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: '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: 'Просмотр документов и фото других пользователей' }
|
||||||
@@ -17,19 +23,19 @@ const ROLES = [
|
|||||||
slug: 'admin',
|
slug: 'admin',
|
||||||
name: 'Администратор',
|
name: 'Администратор',
|
||||||
description: 'Полный доступ к админ-панели без назначения ролей',
|
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',
|
slug: 'moderator',
|
||||||
name: 'Модератор',
|
name: 'Модератор',
|
||||||
description: 'Просмотр пользователей и базовый доступ к админке',
|
description: 'Просмотр пользователей и базовый доступ к админке',
|
||||||
permissions: ['admin.access', 'users.read']
|
permissions: ['admin.access', 'users.view', 'users.view.all']
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
slug: 'manager',
|
slug: 'manager',
|
||||||
name: 'Менеджер',
|
name: 'Менеджер',
|
||||||
description: 'Управление OAuth-приложениями',
|
description: 'Управление OAuth-приложениями',
|
||||||
permissions: ['admin.access', 'oauth.manage']
|
permissions: ['admin.access', 'oauth.manage', 'oauth.view']
|
||||||
}
|
}
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
|||||||
@@ -177,17 +177,20 @@ export class AuthGrpcController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GrpcMethod('RbacService', 'ListOAuthClients')
|
@GrpcMethod('RbacService', 'ListOAuthClients')
|
||||||
async listOAuthClients() {
|
async listOAuthClients(command: { actorUserId: string }) {
|
||||||
const clients = await this.rbac.listOAuthClients();
|
const clients = await this.rbac.listOAuthClients(command.actorUserId);
|
||||||
return {
|
return {
|
||||||
clients: clients.map((client) => ({
|
clients: clients.map((client) => ({
|
||||||
id: client.id,
|
id: client.id,
|
||||||
name: client.name,
|
name: client.name,
|
||||||
clientId: client.clientId,
|
clientId: client.clientId,
|
||||||
redirectUris: client.redirectUris,
|
redirectUris: client.redirectUris,
|
||||||
scopes: client.scopes.map((link) => link.scope.slug),
|
scopes: client.scopes,
|
||||||
isActive: client.isActive,
|
isActive: client.isActive,
|
||||||
type: client.type
|
type: client.type,
|
||||||
|
createdById: client.createdById ?? undefined,
|
||||||
|
createdByDisplayName: client.createdByDisplayName ?? undefined,
|
||||||
|
canManage: client.canManage
|
||||||
}))
|
}))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -735,8 +735,11 @@ export class AuthService {
|
|||||||
permissions: access.permissions,
|
permissions: access.permissions,
|
||||||
canAccessAdmin: access.canAccessAdmin,
|
canAccessAdmin: access.canAccessAdmin,
|
||||||
canManageRoles: access.canManageRoles,
|
canManageRoles: access.canManageRoles,
|
||||||
|
canViewOAuth: access.canViewOAuth,
|
||||||
canManageOAuth: access.canManageOAuth,
|
canManageOAuth: access.canManageOAuth,
|
||||||
|
canManageAllOAuth: access.canManageAllOAuth,
|
||||||
canManageUsers: access.canManageUsers,
|
canManageUsers: access.canManageUsers,
|
||||||
|
canManageAllUsers: access.canManageAllUsers,
|
||||||
canManageSettings: access.canManageSettings,
|
canManageSettings: access.canManageSettings,
|
||||||
canViewUsers: access.canViewUsers,
|
canViewUsers: access.canViewUsers,
|
||||||
canViewUserDocuments: access.canViewUserDocuments
|
canViewUserDocuments: access.canViewUserDocuments
|
||||||
|
|||||||
@@ -43,8 +43,11 @@ export interface PublicUser {
|
|||||||
permissions?: string[];
|
permissions?: string[];
|
||||||
canAccessAdmin?: boolean;
|
canAccessAdmin?: boolean;
|
||||||
canManageRoles?: boolean;
|
canManageRoles?: boolean;
|
||||||
|
canViewOAuth?: boolean;
|
||||||
canManageOAuth?: boolean;
|
canManageOAuth?: boolean;
|
||||||
|
canManageAllOAuth?: boolean;
|
||||||
canManageUsers?: boolean;
|
canManageUsers?: boolean;
|
||||||
|
canManageAllUsers?: boolean;
|
||||||
canManageSettings?: boolean;
|
canManageSettings?: boolean;
|
||||||
canViewUsers?: boolean;
|
canViewUsers?: boolean;
|
||||||
canViewUserDocuments?: boolean;
|
canViewUserDocuments?: boolean;
|
||||||
|
|||||||
@@ -2,7 +2,20 @@ import { BadRequestException, ForbiddenException, Injectable, NotFoundException
|
|||||||
import { randomBytes } from 'node:crypto';
|
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 } 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()
|
@Injectable()
|
||||||
export class RbacService {
|
export class RbacService {
|
||||||
@@ -79,7 +92,7 @@ export class RbacService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createOAuthClient(actorUserId: string, data: { name: string; redirectUris: string[]; scopes: string[]; type?: OAuthClientType }) {
|
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) {
|
if (!data.redirectUris.length) {
|
||||||
throw new BadRequestException('Укажите хотя бы один redirect URI');
|
throw new BadRequestException('Укажите хотя бы один redirect URI');
|
||||||
}
|
}
|
||||||
@@ -95,13 +108,14 @@ export class RbacService {
|
|||||||
clientSecret,
|
clientSecret,
|
||||||
redirectUris: data.redirectUris,
|
redirectUris: data.redirectUris,
|
||||||
type: data.type ?? OAuthClientType.CONFIDENTIAL,
|
type: data.type ?? OAuthClientType.CONFIDENTIAL,
|
||||||
|
createdById: actorUserId,
|
||||||
scopes: {
|
scopes: {
|
||||||
create: data.scopes.map((slug) => ({
|
create: data.scopes.map((slug) => ({
|
||||||
scope: { connect: { slug } }
|
scope: { connect: { slug } }
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
include: { scopes: { include: { scope: true } } }
|
include: { scopes: { include: { scope: true } }, createdBy: true }
|
||||||
});
|
});
|
||||||
|
|
||||||
return { client, clientSecret };
|
return { client, clientSecret };
|
||||||
@@ -112,7 +126,6 @@ export class RbacService {
|
|||||||
clientId: string,
|
clientId: string,
|
||||||
data: { name?: string; redirectUris?: string[]; scopes?: string[]; isActive?: boolean }
|
data: { name?: string; redirectUris?: string[]; scopes?: string[]; isActive?: boolean }
|
||||||
) {
|
) {
|
||||||
await this.assertOAuthPermission(actorUserId);
|
|
||||||
const existing = await this.prisma.oAuthClient.findUnique({
|
const existing = await this.prisma.oAuthClient.findUnique({
|
||||||
where: { clientId },
|
where: { clientId },
|
||||||
include: { scopes: true }
|
include: { scopes: true }
|
||||||
@@ -120,6 +133,7 @@ export class RbacService {
|
|||||||
if (!existing) {
|
if (!existing) {
|
||||||
throw new NotFoundException('OAuth-приложение не найдено');
|
throw new NotFoundException('OAuth-приложение не найдено');
|
||||||
}
|
}
|
||||||
|
await this.assertCanManageOAuthClient(actorUserId, existing);
|
||||||
|
|
||||||
if (data.redirectUris && !data.redirectUris.length) {
|
if (data.redirectUris && !data.redirectUris.length) {
|
||||||
throw new BadRequestException('Укажите хотя бы один redirect URI');
|
throw new BadRequestException('Укажите хотя бы один redirect URI');
|
||||||
@@ -143,18 +157,18 @@ export class RbacService {
|
|||||||
redirectUris: data.redirectUris,
|
redirectUris: data.redirectUris,
|
||||||
isActive: data.isActive
|
isActive: data.isActive
|
||||||
},
|
},
|
||||||
include: { scopes: { include: { scope: true } } }
|
include: { scopes: { include: { scope: true } }, createdBy: true }
|
||||||
});
|
});
|
||||||
|
|
||||||
return { client: updated, clientSecret: undefined as string | undefined };
|
return { client: updated, clientSecret: undefined as string | undefined };
|
||||||
}
|
}
|
||||||
|
|
||||||
async rotateOAuthSecret(actorUserId: string, clientId: string) {
|
async rotateOAuthSecret(actorUserId: string, clientId: string) {
|
||||||
await this.assertOAuthPermission(actorUserId);
|
|
||||||
const existing = await this.prisma.oAuthClient.findUnique({ where: { clientId } });
|
const existing = await this.prisma.oAuthClient.findUnique({ where: { clientId } });
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
throw new NotFoundException('OAuth-приложение не найдено');
|
throw new NotFoundException('OAuth-приложение не найдено');
|
||||||
}
|
}
|
||||||
|
await this.assertCanManageOAuthClient(actorUserId, existing);
|
||||||
if (existing.type === OAuthClientType.PUBLIC) {
|
if (existing.type === OAuthClientType.PUBLIC) {
|
||||||
throw new BadRequestException('У публичного клиента нет client secret');
|
throw new BadRequestException('У публичного клиента нет client secret');
|
||||||
}
|
}
|
||||||
@@ -168,24 +182,72 @@ export class RbacService {
|
|||||||
return { clientId, clientSecret };
|
return { clientId, clientSecret };
|
||||||
}
|
}
|
||||||
|
|
||||||
async listOAuthClients() {
|
async listOAuthClients(actorUserId: string): Promise<OAuthClientListItem[]> {
|
||||||
return this.prisma.oAuthClient.findMany({
|
const { access } = await this.getActorAccess(actorUserId);
|
||||||
orderBy: { createdAt: 'desc' },
|
if (!access.canViewOAuth) {
|
||||||
include: { scopes: { include: { scope: true } } }
|
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 } });
|
const actor = await this.prisma.user.findUnique({ where: { id: actorUserId } });
|
||||||
if (!actor) {
|
if (!actor) {
|
||||||
throw new NotFoundException('Пользователь не найден');
|
throw new NotFoundException('Пользователь не найден');
|
||||||
}
|
}
|
||||||
const access = await this.access.getUserAccess(actor.id, actor.isSuperAdmin);
|
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) {
|
if (!access.canManageOAuth) {
|
||||||
throw new ForbiddenException('Недостаточно прав для управления OAuth-приложениями');
|
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) {
|
private async getUserRoleSlugs(userId: string) {
|
||||||
const links = await this.prisma.userRole.findMany({
|
const links = await this.prisma.userRole.findMany({
|
||||||
where: { userId },
|
where: { userId },
|
||||||
|
|||||||
@@ -185,6 +185,9 @@ message PublicUser {
|
|||||||
bool canViewUsers = 19;
|
bool canViewUsers = 19;
|
||||||
bool canViewUserDocuments = 20;
|
bool canViewUserDocuments = 20;
|
||||||
bool hasPassword = 21;
|
bool hasPassword = 21;
|
||||||
|
bool canViewOAuth = 22;
|
||||||
|
bool canManageAllOAuth = 23;
|
||||||
|
bool canManageAllUsers = 24;
|
||||||
}
|
}
|
||||||
|
|
||||||
message AuthTokens {
|
message AuthTokens {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ service RbacService {
|
|||||||
rpc ListRoles (Empty) returns (ListRolesResponse);
|
rpc ListRoles (Empty) returns (ListRolesResponse);
|
||||||
rpc ListPermissions (Empty) returns (ListPermissionsResponse);
|
rpc ListPermissions (Empty) returns (ListPermissionsResponse);
|
||||||
rpc ListOAuthScopes (Empty) returns (ListOAuthScopesResponse);
|
rpc ListOAuthScopes (Empty) returns (ListOAuthScopesResponse);
|
||||||
rpc ListOAuthClients (Empty) returns (ListOAuthClientsResponse);
|
rpc ListOAuthClients (ListOAuthClientsRequest) returns (ListOAuthClientsResponse);
|
||||||
rpc CreateRole (CreateRoleRequest) returns (Role);
|
rpc CreateRole (CreateRoleRequest) returns (Role);
|
||||||
rpc AssignUserRole (AssignUserRoleRequest) returns (AssignUserRoleResponse);
|
rpc AssignUserRole (AssignUserRoleRequest) returns (AssignUserRoleResponse);
|
||||||
rpc RemoveUserRole (RemoveUserRoleRequest) returns (Empty);
|
rpc RemoveUserRole (RemoveUserRoleRequest) returns (Empty);
|
||||||
@@ -47,6 +47,9 @@ message OAuthClient {
|
|||||||
repeated string scopes = 5;
|
repeated string scopes = 5;
|
||||||
bool isActive = 6;
|
bool isActive = 6;
|
||||||
string type = 7;
|
string type = 7;
|
||||||
|
optional string createdById = 8;
|
||||||
|
optional string createdByDisplayName = 9;
|
||||||
|
bool canManage = 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
message OAuthClientDetail {
|
message OAuthClientDetail {
|
||||||
@@ -58,6 +61,9 @@ message OAuthClientDetail {
|
|||||||
bool isActive = 6;
|
bool isActive = 6;
|
||||||
string type = 7;
|
string type = 7;
|
||||||
optional string clientSecret = 8;
|
optional string clientSecret = 8;
|
||||||
|
optional string createdById = 9;
|
||||||
|
optional string createdByDisplayName = 10;
|
||||||
|
bool canManage = 11;
|
||||||
}
|
}
|
||||||
|
|
||||||
message ListRolesResponse {
|
message ListRolesResponse {
|
||||||
@@ -76,6 +82,10 @@ message ListOAuthClientsResponse {
|
|||||||
repeated OAuthClient clients = 1;
|
repeated OAuthClient clients = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message ListOAuthClientsRequest {
|
||||||
|
string actorUserId = 1;
|
||||||
|
}
|
||||||
|
|
||||||
message CreateRoleRequest {
|
message CreateRoleRequest {
|
||||||
string actorUserId = 1;
|
string actorUserId = 1;
|
||||||
string slug = 2;
|
string slug = 2;
|
||||||
|
|||||||
Reference in New Issue
Block a user