update oauth
This commit is contained in:
@@ -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>
|
||||
|
||||
134
apps/frontend/components/id/oauth-client-detail-dialog.tsx
Normal file
134
apps/frontend/components/id/oauth-client-detail-dialog.tsx
Normal file
@@ -0,0 +1,134 @@
|
||||
'use client';
|
||||
|
||||
import { Copy, ExternalLink, KeyRound, RefreshCw } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { OAuthClient } from '@/lib/api';
|
||||
import { OAuthEndpoints, buildAuthorizeUrl } from '@/lib/oauth-url';
|
||||
|
||||
function CopyRow({ label, value, onCopy }: { label: string; value: string; onCopy: (value: string, label: string) => void }) {
|
||||
return (
|
||||
<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">{label}</span>
|
||||
<Button variant="ghost" size="icon" aria-label={`Скопировать ${label}`} onClick={() => onCopy(value, label)}>
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<code className="block break-all text-xs">{value}</code>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function OAuthClientDetailDialog({
|
||||
client,
|
||||
endpoints,
|
||||
open,
|
||||
onOpenChange,
|
||||
onCopy,
|
||||
onRotateSecret,
|
||||
onToggleActive
|
||||
}: {
|
||||
client: OAuthClient | null;
|
||||
endpoints: OAuthEndpoints;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCopy: (value: string, label: string) => void;
|
||||
onRotateSecret: (clientId: string) => void;
|
||||
onToggleActive: (client: OAuthClient) => void;
|
||||
}) {
|
||||
if (!client) return null;
|
||||
|
||||
const primaryRedirect = client.redirectUris[0] ?? 'https://app.example.com/oauth/callback';
|
||||
const scope = client.scopes.join(' ');
|
||||
const sampleAuthorizeUrl = buildAuthorizeUrl(endpoints.issuer, {
|
||||
clientId: client.clientId,
|
||||
redirectUri: primaryRedirect,
|
||||
scope
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{client.name}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 text-sm">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<span className="rounded-full bg-[#eef4ff] px-3 py-1 text-xs font-medium text-[#1d4ed8]">
|
||||
{client.type === 'PUBLIC' ? 'Public' : 'Confidential'}
|
||||
</span>
|
||||
<span className={`rounded-full px-3 py-1 text-xs font-medium ${client.isActive ? 'bg-emerald-50 text-emerald-700' : 'bg-zinc-100 text-zinc-600'}`}>
|
||||
{client.isActive ? 'Активно' : 'Отключено'}
|
||||
</span>
|
||||
{client.createdByDisplayName ? (
|
||||
<span className="rounded-full bg-zinc-100 px-3 py-1 text-xs text-zinc-600">Создал: {client.createdByDisplayName}</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<section className="space-y-3">
|
||||
<h3 className="font-medium">Данные клиента</h3>
|
||||
<CopyRow label="Client ID" value={client.clientId} onCopy={onCopy} />
|
||||
{client.type !== 'PUBLIC' ? (
|
||||
<p className="text-xs text-[#667085]">
|
||||
Client Secret выдаётся один раз при создании или после «Новый secret». Храните только на backend.
|
||||
</p>
|
||||
) : null}
|
||||
<CopyRow label="Redirect URI" value={client.redirectUris.join('\n')} onCopy={onCopy} />
|
||||
<CopyRow label="Scopes" value={scope} onCopy={onCopy} />
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<h3 className="font-medium">Подключение OAuth 2.0 / OpenID Connect</h3>
|
||||
<p className="text-xs text-[#667085]">
|
||||
Issuer и endpoints берутся из настройки <strong>PUBLIC_API_URL</strong> в админке. В стороннем сервисе укажите issuer = базовый URL API, не authorization endpoint.
|
||||
</p>
|
||||
<CopyRow label="Issuer (PUBLIC_API_URL)" value={endpoints.issuer} onCopy={onCopy} />
|
||||
<CopyRow label="Authorization endpoint" value={endpoints.authorizationEndpoint} onCopy={onCopy} />
|
||||
<CopyRow label="Token endpoint" value={endpoints.tokenEndpoint} onCopy={onCopy} />
|
||||
<CopyRow label="UserInfo endpoint" value={endpoints.userInfoEndpoint} onCopy={onCopy} />
|
||||
<CopyRow label="OIDC Discovery" value={endpoints.openIdConfigurationUrl} onCopy={onCopy} />
|
||||
<CopyRow label="Пример authorize URL" value={sampleAuthorizeUrl} onCopy={onCopy} />
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-[#eceef4] p-4">
|
||||
<div className="mb-2 flex items-center gap-2 font-medium">
|
||||
<KeyRound className="h-4 w-4" />
|
||||
Быстрый старт
|
||||
</div>
|
||||
<ol className="list-decimal space-y-1 pl-5 text-xs text-[#667085]">
|
||||
<li>Авторизуйте пользователя в IdP и получите userId.</li>
|
||||
<li>Перенаправьте на authorization endpoint с clientId, redirectUri, scope, userId.</li>
|
||||
<li>На backend обменяйте code через POST /oauth/token с client_secret.</li>
|
||||
<li>Запросите профиль через GET /oauth/userinfo с access token.</li>
|
||||
</ol>
|
||||
<a
|
||||
href={endpoints.openIdConfigurationUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="mt-2 inline-flex items-center gap-1 text-xs text-[#1d4ed8] hover:underline"
|
||||
>
|
||||
Открыть OpenID Configuration
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</a>
|
||||
</section>
|
||||
|
||||
{client.canManage ? (
|
||||
<div className="flex flex-wrap gap-2 border-t border-[#eceef4] pt-4">
|
||||
{client.type !== 'PUBLIC' ? (
|
||||
<Button variant="secondary" size="sm" onClick={() => onRotateSecret(client.clientId)}>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Новый secret
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="secondary" size="sm" onClick={() => onToggleActive(client)}>
|
||||
{client.isActive ? 'Отключить' : 'Включить'}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
56
apps/frontend/lib/oauth-url.ts
Normal file
56
apps/frontend/lib/oauth-url.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
export function normalizeBaseUrl(url: string) {
|
||||
return url.trim().replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export function resolveOAuthApiBase(settings: Record<string, string>, fallback = 'http://localhost:3000') {
|
||||
const publicApi = settings.PUBLIC_API_URL?.trim();
|
||||
if (publicApi) {
|
||||
return normalizeBaseUrl(publicApi);
|
||||
}
|
||||
|
||||
const domain = settings.PROJECT_DOMAIN?.trim();
|
||||
if (domain) {
|
||||
if (domain.startsWith('http://') || domain.startsWith('https://')) {
|
||||
return normalizeBaseUrl(domain);
|
||||
}
|
||||
return `https://${domain.replace(/^\/+/, '')}`;
|
||||
}
|
||||
|
||||
return normalizeBaseUrl(fallback);
|
||||
}
|
||||
|
||||
export interface OAuthEndpoints {
|
||||
issuer: string;
|
||||
authorizationEndpoint: string;
|
||||
tokenEndpoint: string;
|
||||
userInfoEndpoint: string;
|
||||
openIdConfigurationUrl: string;
|
||||
jwksUrl: string;
|
||||
}
|
||||
|
||||
export function buildOAuthEndpoints(apiBase: string): OAuthEndpoints {
|
||||
const base = normalizeBaseUrl(apiBase);
|
||||
return {
|
||||
issuer: base,
|
||||
authorizationEndpoint: `${base}/oauth/authorize`,
|
||||
tokenEndpoint: `${base}/oauth/token`,
|
||||
userInfoEndpoint: `${base}/oauth/userinfo`,
|
||||
openIdConfigurationUrl: `${base}/.well-known/openid-configuration`,
|
||||
jwksUrl: `${base}/.well-known/jwks.json`
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAuthorizeUrl(
|
||||
apiBase: string,
|
||||
params: { clientId: string; redirectUri: string; scope: string; userId?: string; state?: string }
|
||||
) {
|
||||
const url = new URL(`${normalizeBaseUrl(apiBase)}/oauth/authorize`);
|
||||
url.searchParams.set('clientId', params.clientId);
|
||||
url.searchParams.set('redirectUri', params.redirectUri);
|
||||
url.searchParams.set('scope', params.scope);
|
||||
url.searchParams.set('userId', params.userId ?? 'USER_ID_AFTER_LOGIN');
|
||||
if (params.state) {
|
||||
url.searchParams.set('state', params.state);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
@@ -24,7 +24,14 @@ export const SYSTEM_SETTING_GROUPS: Record<string, string> = {
|
||||
export const SYSTEM_SETTING_CATALOG: SystemSettingMeta[] = [
|
||||
{ key: 'PROJECT_NAME', label: 'Название проекта', group: 'general', type: 'text', hint: 'Отображается в меню, заголовке и боковой панели' },
|
||||
{ key: 'PROJECT_TAGLINE', label: 'Слоган проекта', group: 'general', type: 'text' },
|
||||
{ key: 'PROJECT_DOMAIN', label: 'Домен IdP', group: 'general', type: 'text' },
|
||||
{ key: 'PROJECT_DOMAIN', label: 'Домен IdP', group: 'general', type: 'text', hint: 'Домен без пути, например sso.example.ru' },
|
||||
{
|
||||
key: 'PUBLIC_API_URL',
|
||||
label: 'URL API (OAuth issuer)',
|
||||
group: 'general',
|
||||
type: 'text',
|
||||
hint: 'Базовый URL API для OAuth/OIDC. Пример: https://sso.example.ru/idp-api или https://api.example.ru'
|
||||
},
|
||||
{ key: 'PIN_LOCK_TIMEOUT_MINUTES', label: 'Таймаут блокировки PIN', group: 'pin', type: 'number', unit: 'мин' },
|
||||
{ key: 'PIN_DELETE_GRACE_MINUTES', label: 'Задержка удаления PIN', group: 'pin', type: 'number', unit: 'мин', hint: 'Сколько ждать после запроса удаления PIN-кода' },
|
||||
{ key: 'PIN_REQUIRE_ON_DELETE', label: 'Требовать PIN при удалении', group: 'pin', type: 'boolean' },
|
||||
|
||||
@@ -19,6 +19,14 @@ const nextConfig: NextConfig = {
|
||||
{
|
||||
source: '/idp-api/:path*',
|
||||
destination: `${internalApiUrl}/:path*`
|
||||
},
|
||||
{
|
||||
source: '/oauth/:path*',
|
||||
destination: `${internalApiUrl}/oauth/:path*`
|
||||
},
|
||||
{
|
||||
source: '/.well-known/:path*',
|
||||
destination: `${internalApiUrl}/.well-known/:path*`
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user