update oauth
This commit is contained in:
@@ -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 ?? []);
|
||||
setScopes(scopesResponse.scopes ?? []);
|
||||
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,17 +179,21 @@ export default function AdminOAuthPage() {
|
||||
</div>
|
||||
<p>{client.scopes.join(', ')}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{client.type !== 'PUBLIC' ? (
|
||||
<Button variant="secondary" size="sm" onClick={() => void handleRotateSecret(client.clientId)}>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Новый secret
|
||||
{client.canManage ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{client.type !== 'PUBLIC' ? (
|
||||
<Button variant="secondary" size="sm" onClick={() => void handleRotateSecret(client.clientId)}>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Новый secret
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="secondary" size="sm" onClick={() => void handleToggleActive(client)}>
|
||||
{client.isActive ? 'Отключить' : 'Включить'}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="secondary" size="sm" onClick={() => void handleToggleActive(client)}>
|
||||
{client.isActive ? 'Отключить' : 'Включить'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-[#667085]">Только просмотр — управление доступно создателю или администратору с полными правами</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</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() {
|
||||
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';
|
||||
|
||||
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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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>
|
||||
|
||||
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[];
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user