update oauth

This commit is contained in:
lendry
2026-06-25 14:40:05 +03:00
parent 1796008a28
commit 6c63343fc7
19 changed files with 623 additions and 200 deletions

View File

@@ -1,9 +1,10 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Copy, KeyRound, Loader2, LockKeyhole, Plus, RefreshCw, UserRound } from 'lucide-react';
import { Copy, ExternalLink, Loader2, LockKeyhole, Plus, UserRound } from 'lucide-react';
import { AdminShell } from '@/components/id/admin-shell';
import { OAuthClientDetailDialog } from '@/components/id/oauth-client-detail-dialog';
import { useAuth } from '@/components/id/auth-provider';
import { useToast } from '@/components/id/toast-provider';
import { Button } from '@/components/ui/button';
@@ -12,6 +13,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
import { Input } from '@/components/ui/input';
import { OAuthClient, OAuthScope, apiFetch } from '@/lib/api';
import { getAdminLandingPath } from '@/lib/admin-access';
import { buildAuthorizeUrl, buildOAuthEndpoints, resolveOAuthApiBase } from '@/lib/oauth-url';
export default function AdminOAuthPage() {
const router = useRouter();
@@ -22,9 +24,23 @@ export default function AdminOAuthPage() {
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [selectedClient, setSelectedClient] = useState<OAuthClient | null>(null);
const [secretDialog, setSecretDialog] = useState<{ clientId: string; clientSecret: string } | null>(null);
const [oauthApiBase, setOauthApiBase] = useState('http://localhost:3000');
const [form, setForm] = useState({ name: '', redirectUris: '', type: 'CONFIDENTIAL', selectedScopes: ['openid', 'profile', 'email'] as string[] });
const oauthEndpoints = useMemo(() => buildOAuthEndpoints(oauthApiBase), [oauthApiBase]);
const loadPublicSettings = useCallback(async () => {
try {
const response = await apiFetch<{ settings: Array<{ key: string; value: string }> }>('/settings/public');
const settings = Object.fromEntries((response.settings ?? []).map((item) => [item.key, item.value]));
setOauthApiBase(resolveOAuthApiBase(settings));
} catch {
// оставляем fallback
}
}, []);
const loadData = useCallback(async () => {
if (!token || !user?.canViewOAuth) return;
setLoading(true);
@@ -42,6 +58,10 @@ export default function AdminOAuthPage() {
}
}, [showToast, token, user?.canManageOAuth, user?.canViewOAuth]);
useEffect(() => {
void loadPublicSettings();
}, [loadPublicSettings]);
useEffect(() => {
if (!user) return;
if (!user.canViewOAuth && !user.canManageOAuth) {
@@ -106,6 +126,7 @@ export default function AdminOAuthPage() {
body: JSON.stringify({ isActive: !client.isActive })
}, token);
showToast(client.isActive ? 'Приложение отключено' : 'Приложение включено');
setSelectedClient((current) => (current?.id === client.id ? { ...client, isActive: !client.isActive } : current));
await loadData();
} catch (error) {
showToast(error instanceof Error ? error.message : 'Не удалось обновить приложение');
@@ -122,7 +143,14 @@ export default function AdminOAuthPage() {
<div className="mb-6 flex items-center justify-between gap-4">
<div>
<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]">
Issuer: <code className="rounded bg-[#f4f5f8] px-1.5 py-0.5 text-xs">{oauthEndpoints.issuer}</code>
{' · '}
<a href={oauthEndpoints.openIdConfigurationUrl} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-[#1d4ed8] hover:underline">
OpenID Configuration
<ExternalLink className="h-3.5 w-3.5" />
</a>
</p>
</div>
<Button onClick={() => setDialogOpen(true)} disabled={!user?.canManageOAuth}>
<Plus className="h-4 w-4" />
@@ -137,70 +165,56 @@ export default function AdminOAuthPage() {
</div>
) : (
<div className="grid gap-4 md:grid-cols-2">
{clients.map((client) => (
<Card key={client.id} className={client.isActive ? '' : 'opacity-70'}>
<CardHeader>
<LockKeyhole className="h-6 w-6" />
<CardTitle>{client.name}</CardTitle>
<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">
<div className="mb-2 flex items-center justify-between gap-2">
<span className="font-medium">Client ID</span>
<Button variant="ghost" size="icon" aria-label="Скопировать client id" onClick={() => copyText(client.clientId, 'Client ID')}>
<Copy className="h-4 w-4" />
</Button>
</div>
<code className="break-all text-xs">{client.clientId}</code>
</div>
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
<div className="mb-2 font-medium">Redirect URI</div>
{client.redirectUris.map((uri) => (
<div key={uri} className="break-all text-xs text-[#667085]">
{uri}
</div>
))}
</div>
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
<div className="mb-2 flex items-center gap-2 font-medium">
<KeyRound className="h-4 w-4" />
Scopes
</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)}>
<RefreshCw className="h-4 w-4" />
Новый secret
</Button>
{clients.map((client) => {
const authorizePreview = buildAuthorizeUrl(oauthEndpoints.issuer, {
clientId: client.clientId,
redirectUri: client.redirectUris[0] ?? 'https://app.example.com/oauth/callback',
scope: client.scopes.join(' ')
});
return (
<Card
key={client.id}
className={`cursor-pointer transition hover:shadow-md ${client.isActive ? '' : 'opacity-70'}`}
onClick={() => setSelectedClient(client)}
>
<CardHeader>
<LockKeyhole className="h-6 w-6" />
<CardTitle>{client.name}</CardTitle>
<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>
) : null}
<Button variant="secondary" size="sm" onClick={() => void handleToggleActive(client)}>
{client.isActive ? 'Отключить' : 'Включить'}
</Button>
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="rounded-2xl bg-[#f4f5f8] p-4 text-sm">
<div className="mb-1 font-medium">Authorization URL</div>
<code className="line-clamp-2 break-all text-xs text-[#667085]">{authorizePreview}</code>
</div>
) : (
<p className="text-xs text-[#667085]">Только просмотр управление доступно создателю или администратору с полными правами</p>
)}
</CardContent>
</Card>
))}
<p className="text-xs text-[#667085]">Нажмите на карточку все endpoints и данные для интеграции</p>
</CardContent>
</Card>
);
})}
{!clients.length ? <p className="text-[#667085]">OAuth-приложения ещё не созданы</p> : null}
</div>
)}
<OAuthClientDetailDialog
client={selectedClient}
endpoints={oauthEndpoints}
open={Boolean(selectedClient)}
onOpenChange={(open) => !open && setSelectedClient(null)}
onCopy={copyText}
onRotateSecret={(clientId) => void handleRotateSecret(clientId)}
onToggleActive={(client) => void handleToggleActive(client)}
/>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>