feat(web): перенести страницы Приложения, Аккаунт, Входы и Изменения на новый дизайн
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
148a778ba1
commit
69b3553f6d
7 files changed
+921
-879
No files matched your search
@@ -0,0 +1,45 @@
|
||||
const DATE = new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit', year: 'numeric' })
|
||||
const SHORT = new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit' })
|
||||
const TIME = new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' })
|
||||
|
||||
function parse(iso: string | null | undefined): Date | null {
|
||||
if (!iso) return null
|
||||
const d = new Date(iso)
|
||||
return Number.isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
/** 12.09.2026 */
|
||||
export function fmtDate(iso: string | null | undefined, empty = '—') {
|
||||
const d = parse(iso)
|
||||
return d ? DATE.format(d) : empty
|
||||
}
|
||||
|
||||
/** «сегодня 09:41», «вчера 22:15», иначе «12.09 09:41». */
|
||||
export function fmtWhen(iso: string | null | undefined, empty = '—', now = Date.now()) {
|
||||
const d = parse(iso)
|
||||
if (!d) return empty
|
||||
const dayMs = 24 * 60 * 60 * 1000
|
||||
const startOfToday = new Date(now)
|
||||
startOfToday.setHours(0, 0, 0, 0)
|
||||
const diff = startOfToday.getTime() - new Date(d).setHours(0, 0, 0, 0)
|
||||
if (diff === 0) return `сегодня ${TIME.format(d)}`
|
||||
if (diff === dayMs) return `вчера ${TIME.format(d)}`
|
||||
return `${SHORT.format(d)} ${TIME.format(d)}`
|
||||
}
|
||||
|
||||
/** Время дня 14:02. */
|
||||
export function fmtTime(iso: string | null | undefined, empty = '—') {
|
||||
const d = parse(iso)
|
||||
return d ? TIME.format(d) : empty
|
||||
}
|
||||
|
||||
/** «5 дн назад», «3 ч назад», «только что». */
|
||||
export function fmtAgo(iso: string | null | undefined, empty = '—', now = Date.now()) {
|
||||
const d = parse(iso)
|
||||
if (!d) return empty
|
||||
const sec = Math.max(0, Math.round((now - d.getTime()) / 1000))
|
||||
if (sec < 60) return 'только что'
|
||||
if (sec < 3600) return `${Math.floor(sec / 60)} мин назад`
|
||||
if (sec < 86400) return `${Math.floor(sec / 3600)} ч назад`
|
||||
return `${Math.floor(sec / 86400)} дн назад`
|
||||
}
|
||||
@@ -16,4 +16,3 @@ export { UserAuditSheet } from './user-audit-sheet'
|
||||
export { CreateUserSheet } from './create-user-sheet'
|
||||
export { CreateOidcClientSheet } from './create-oidc-client-sheet'
|
||||
export { AdminUsersGrid, type AdminUsersGridProps } from './admin-users-grid'
|
||||
export { PasskeySettingsPanel } from './passkey-settings-panel'
|
||||
@@ -1,213 +0,0 @@
|
||||
/**
|
||||
* Passkey management — DNA settings-16 / settings-2 / settings-10.
|
||||
* Preview: https://reui.io/preview/base/settings-16 · https://reui.io/preview/base/settings-2 · https://reui.io/preview/base/settings-10
|
||||
* Docs: https://reui.io/docs/components/base/frame
|
||||
*/
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { FingerprintIcon, PlusIcon, Trash2Icon } from 'lucide-react'
|
||||
import {
|
||||
startRegistration,
|
||||
browserSupportsWebAuthn,
|
||||
} from '@simplewebauthn/browser'
|
||||
import type { PublicKeyCredentialCreationOptionsJSON } from '@simplewebauthn/browser'
|
||||
import type { PasskeyCredential } from '@authportal/shared'
|
||||
import {
|
||||
Frame,
|
||||
FrameDescription,
|
||||
FrameHeader,
|
||||
FramePanel,
|
||||
FrameTitle,
|
||||
} from '@/components/reui/frame'
|
||||
import { Badge } from '@/components/reui/badge'
|
||||
import { Button } from '@authportal/ui/components/button'
|
||||
import {
|
||||
Item,
|
||||
ItemActions,
|
||||
ItemContent,
|
||||
ItemDescription,
|
||||
ItemMedia,
|
||||
ItemTitle,
|
||||
} from '@authportal/ui/components/item'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@authportal/ui/components/alert-dialog'
|
||||
import { Skeleton } from '@authportal/ui/components/skeleton'
|
||||
import { toast } from 'sonner'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import {
|
||||
deletePasskey,
|
||||
passkeysQueryKey,
|
||||
passkeysQueryOptions,
|
||||
webauthnRegister,
|
||||
webauthnRegisterOptions,
|
||||
} from '@/queries/webauthn'
|
||||
|
||||
function formatWhen(iso: string | null) {
|
||||
if (!iso) return 'ещё не использовался'
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return '—'
|
||||
return new Intl.DateTimeFormat('ru-RU', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(date)
|
||||
}
|
||||
|
||||
export function PasskeySettingsPanel() {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: passkeys = [], isLoading } = useQuery(passkeysQueryOptions)
|
||||
const [pendingDelete, setPendingDelete] = useState<PasskeyCredential | null>(
|
||||
null,
|
||||
)
|
||||
const supported = browserSupportsWebAuthn()
|
||||
|
||||
const registerMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const { challenge_id, options } = await webauthnRegisterOptions()
|
||||
const attResp = await startRegistration({
|
||||
optionsJSON:
|
||||
options as unknown as PublicKeyCredentialCreationOptionsJSON,
|
||||
})
|
||||
return webauthnRegister(challenge_id, attResp)
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: passkeysQueryKey })
|
||||
toast.success('Passkey добавлен')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof ApiError ? err.message : 'Не удалось добавить passkey',
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deletePasskey(id),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: passkeysQueryKey })
|
||||
toast.success('Passkey удалён')
|
||||
setPendingDelete(null)
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof ApiError ? err.message : 'Не удалось удалить passkey',
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<Frame className="w-full">
|
||||
<FrameHeader className="flex-row items-start justify-between gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<FrameTitle>Passkeys</FrameTitle>
|
||||
<FrameDescription>
|
||||
Вход без пароля: Windows Hello, Face ID, ключ безопасности
|
||||
</FrameDescription>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={!supported || registerMutation.isPending}
|
||||
onClick={() => registerMutation.mutate()}
|
||||
>
|
||||
<PlusIcon aria-hidden="true" />
|
||||
{registerMutation.isPending ? 'Ожидание…' : 'Добавить passkey'}
|
||||
</Button>
|
||||
</FrameHeader>
|
||||
<FramePanel className="flex flex-col gap-2">
|
||||
{!supported ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Этот браузер не поддерживает WebAuthn.
|
||||
</p>
|
||||
) : null}
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Skeleton className="h-16 w-full rounded-xl" />
|
||||
<Skeleton className="h-16 w-full rounded-xl" />
|
||||
</div>
|
||||
) : passkeys.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Ключи не зарегистрированы. Добавьте passkey, чтобы входить без
|
||||
пароля.
|
||||
</p>
|
||||
) : (
|
||||
passkeys.map((item) => (
|
||||
<Item key={item.id} variant="outline" className="items-start">
|
||||
<ItemMedia variant="icon">
|
||||
<FingerprintIcon className="size-4" aria-hidden="true" />
|
||||
</ItemMedia>
|
||||
<ItemContent>
|
||||
<ItemTitle className="flex flex-wrap items-center gap-2">
|
||||
{item.name}
|
||||
{item.device_type === 'multiDevice' ? (
|
||||
<Badge variant="info-outline" size="sm">
|
||||
Синхронизируется
|
||||
</Badge>
|
||||
) : null}
|
||||
</ItemTitle>
|
||||
<ItemDescription>
|
||||
Добавлен {formatWhen(item.created_at)} · вход{' '}
|
||||
{formatWhen(item.last_used_at)}
|
||||
</ItemDescription>
|
||||
</ItemContent>
|
||||
<ItemActions>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
aria-label={`Удалить ${item.name}`}
|
||||
onClick={() => setPendingDelete(item)}
|
||||
>
|
||||
<Trash2Icon aria-hidden="true" />
|
||||
Удалить
|
||||
</Button>
|
||||
</ItemActions>
|
||||
</Item>
|
||||
))
|
||||
)}
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
|
||||
<AlertDialog
|
||||
open={Boolean(pendingDelete)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPendingDelete(null)
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent size="sm">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Удалить passkey?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{pendingDelete
|
||||
? `«${pendingDelete.name}» больше нельзя будет использовать для входа.`
|
||||
: null}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => {
|
||||
if (pendingDelete) deleteMutation.mutate(pendingDelete.id)
|
||||
}}
|
||||
>
|
||||
Удалить
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,25 +1,280 @@
|
||||
/**
|
||||
* Account security — passkeys.
|
||||
* Preview: https://reui.io/preview/base/settings-10 · https://reui.io/preview/base/settings-16
|
||||
*/
|
||||
import { useMemo, useState } from 'react'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { PageShell } from '@/components/page-shell'
|
||||
import { PasskeySettingsPanel } from '@/components/reui-kit/passkey-settings-panel'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { ClockIcon, FingerprintIcon, LayoutGridIcon, ShieldIcon, TrashIcon } from 'lucide-react'
|
||||
import { browserSupportsWebAuthn, startRegistration } from '@simplewebauthn/browser'
|
||||
import type { PublicKeyCredentialCreationOptionsJSON } from '@simplewebauthn/browser'
|
||||
import { toast } from 'sonner'
|
||||
import type { PasskeyCredential } from '@authportal/shared'
|
||||
import { ExplainBanner } from '@/components/portal/explain-banner'
|
||||
import { KvFrame, KvList, PageHead, PageTab, PageTabsList, PortalSheet, SignalAlert, StatusBadge, TypedConfirm } from '@/components/portal/bits'
|
||||
import { fmtDate, fmtWhen } from '@/components/portal/format'
|
||||
import { kpi } from '@/components/portal/kpi'
|
||||
import { KpiStrip } from '@/components/portal/kpi-strip'
|
||||
import { SectionGrid, TwoLineCell, type GridColumn } from '@/components/portal/section-grid'
|
||||
import { Button } from '@authportal/ui/components/button'
|
||||
import { Field, FieldDescription, FieldLabel } from '@authportal/ui/components/field'
|
||||
import { Input } from '@authportal/ui/components/input'
|
||||
import { Skeleton } from '@authportal/ui/components/skeleton'
|
||||
import { Tabs, TabsContent } from '@authportal/ui/components/tabs'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
import { meQueryOptions } from '@/queries/auth'
|
||||
import {
|
||||
deletePasskey,
|
||||
passkeysQueryKey,
|
||||
passkeysQueryOptions,
|
||||
renamePasskey,
|
||||
webauthnRegister,
|
||||
webauthnRegisterOptions,
|
||||
} from '@/queries/webauthn'
|
||||
|
||||
export const Route = createFileRoute('/_auth/account')({
|
||||
component: AccountPage,
|
||||
})
|
||||
|
||||
const STALE_DAYS = 60
|
||||
|
||||
type Row = PasskeyCredential & { tone: 'ok' | 'wn'; status: string }
|
||||
|
||||
function toRow(k: PasskeyCredential, now: number): Row {
|
||||
const last = new Date(k.last_used_at ?? k.created_at).getTime()
|
||||
const stale = now - last > STALE_DAYS * 24 * 60 * 60 * 1000
|
||||
return { ...k, tone: stale ? 'wn' : 'ok', status: stale ? 'Давно не использовался' : 'Активен' }
|
||||
}
|
||||
|
||||
function kindOf(k: PasskeyCredential) {
|
||||
return k.device_type === 'multiDevice' ? 'Синхронизируемый' : k.device_type === 'singleDevice' ? 'Ключ устройства' : 'Passkey'
|
||||
}
|
||||
|
||||
function AccountPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: me } = useQuery(meQueryOptions)
|
||||
const { data: passkeys = [], isLoading, isError, refetch, dataUpdatedAt } = useQuery(passkeysQueryOptions)
|
||||
const supported = browserSupportsWebAuthn()
|
||||
|
||||
const [addOpen, setAddOpen] = useState(false)
|
||||
const [newName, setNewName] = useState('')
|
||||
const [selected, setSelected] = useState<Row | null>(null)
|
||||
const [renameValue, setRenameValue] = useState('')
|
||||
const [deleting, setDeleting] = useState<Row | null>(null)
|
||||
|
||||
const rows = useMemo(() => passkeys.map((k) => toRow(k, dataUpdatedAt || Date.parse(k.created_at))), [passkeys, dataUpdatedAt])
|
||||
const lastUsed = rows.map((r) => r.last_used_at).filter((x): x is string => Boolean(x)).sort().at(-1) ?? null
|
||||
|
||||
const registerMutation = useMutation({
|
||||
mutationFn: async (name: string) => {
|
||||
const { challenge_id, options } = await webauthnRegisterOptions()
|
||||
const att = await startRegistration({ optionsJSON: options as unknown as PublicKeyCredentialCreationOptionsJSON })
|
||||
return webauthnRegister(challenge_id, att, name.trim() || undefined)
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: passkeysQueryKey })
|
||||
setAddOpen(false)
|
||||
setNewName('')
|
||||
toast.success('Passkey добавлен')
|
||||
},
|
||||
onError: (err) => toast.error(err instanceof ApiError ? err.message : 'Не удалось добавить passkey'),
|
||||
})
|
||||
|
||||
const renameMutation = useMutation({
|
||||
mutationFn: ({ id, name }: { id: string; name: string }) => renamePasskey(id, name),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: passkeysQueryKey })
|
||||
setSelected(null)
|
||||
toast.success('Название сохранено')
|
||||
},
|
||||
onError: (err) => toast.error(err instanceof ApiError ? err.message : 'Не удалось переименовать passkey'),
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => deletePasskey(id),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: passkeysQueryKey })
|
||||
setDeleting(null)
|
||||
toast.success('Passkey удалён')
|
||||
},
|
||||
onError: (err) => toast.error(err instanceof ApiError ? err.message : 'Не удалось удалить passkey'),
|
||||
})
|
||||
|
||||
const columns = useMemo<GridColumn<Row>[]>(
|
||||
() => [
|
||||
{ id: 'name', title: 'Passkey', size: 280, sortValue: (r) => r.name, cell: (r) => <TwoLineCell dot={r.tone} title={r.name} sub={kindOf(r)} /> },
|
||||
{ id: 'status', title: 'Статус', size: 210, cell: (r) => <StatusBadge tone={r.tone}>{r.status}</StatusBadge> },
|
||||
{ id: 'added', title: 'Добавлен', size: 120, sortValue: (r) => r.created_at, cell: (r) => <span className="font-mono text-[12.5px]">{fmtDate(r.created_at)}</span> },
|
||||
{ id: 'last', title: 'Последний вход', size: 180, sortValue: (r) => r.last_used_at ?? '', cell: (r) => <span className="font-mono text-[12.5px]">{r.last_used_at ? fmtWhen(r.last_used_at) : 'ещё не использовался'}</span> },
|
||||
],
|
||||
[],
|
||||
)
|
||||
|
||||
const open = (r: Row) => {
|
||||
setSelected(r)
|
||||
setRenameValue(r.name)
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Безопасность</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Passkey как альтернатива паролю. Пароль остаётся запасным входом.
|
||||
</p>
|
||||
</div>
|
||||
<PasskeySettingsPanel />
|
||||
</PageShell>
|
||||
<>
|
||||
<PageHead
|
||||
title="Безопасность"
|
||||
sub="Passkey как альтернатива паролю · пароль остаётся запасным входом"
|
||||
actions={
|
||||
<Button disabled={!supported} onClick={() => setAddOpen(true)}>
|
||||
Добавить passkey
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{!supported ? (
|
||||
<SignalAlert tone="wn" title="Браузер не поддерживает passkeys.">
|
||||
Откройте портал по HTTPS в современном браузере. Вход по паролю остаётся доступным.
|
||||
</SignalAlert>
|
||||
) : null}
|
||||
{supported && !isLoading && rows.length <= 1 ? (
|
||||
<ExplainBanner
|
||||
tone="wn"
|
||||
title={rows.length === 0 ? 'Passkey не добавлен.' : 'Один passkey — единственная копия.'}
|
||||
text={
|
||||
rows.length === 0
|
||||
? 'Сейчас вход возможен только по паролю. Добавьте passkey, чтобы входить отпечатком, Face ID или ключом безопасности.'
|
||||
: 'Если устройство будет потеряно, вход возможен только по паролю. Добавьте второй ключ на другом устройстве или ключ безопасности.'
|
||||
}
|
||||
>
|
||||
Совет: держите два ключа на разных устройствах, например платформенный и ключ безопасности.
|
||||
</ExplainBanner>
|
||||
) : null}
|
||||
<KpiStrip
|
||||
aria-label="Показатели"
|
||||
items={[
|
||||
kpi('keys', 'Passkeys', String(rows.length), { icon: FingerprintIcon, tone: rows.length ? 'ok' : 'wn', badge: rows.length ? 'активны' : 'не добавлены' }),
|
||||
kpi('last', 'Последний вход', lastUsed ? fmtWhen(lastUsed) : '—', { icon: ClockIcon, badge: 'по passkey' }),
|
||||
kpi('apps', 'Приложений', String(me?.apps.length ?? 0), { icon: LayoutGridIcon, badge: 'доступно вам' }),
|
||||
kpi('role', 'Роль', me?.is_admin ? 'Админ' : 'Пользователь', { icon: ShieldIcon, badge: me?.is_admin ? 'is_admin' : 'по правам' }),
|
||||
]}
|
||||
/>
|
||||
<Tabs defaultValue="keys" className="min-w-0">
|
||||
<PageTabsList>
|
||||
<PageTab value="keys" label="Passkeys" count={rows.length} />
|
||||
<PageTab value="acc" label="Учётная запись" />
|
||||
</PageTabsList>
|
||||
<TabsContent value="keys" className="flex min-w-0 flex-col gap-4">
|
||||
{isLoading ? (
|
||||
<Skeleton className="h-64 w-full rounded-xl" />
|
||||
) : isError ? (
|
||||
<div role="alert" className="border-destructive/40 bg-destructive/10 flex flex-wrap items-center justify-between gap-3 rounded-xl border px-4 py-3 text-sm">
|
||||
<span>Не удалось загрузить passkeys. Повторите запрос.</span>
|
||||
<Button variant="outline" onClick={() => void refetch()}>
|
||||
Повторить
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<SectionGrid
|
||||
title="Мои passkeys"
|
||||
description="Вход без пароля: отпечаток, Face ID, PIN или ключ безопасности · удаление необратимо"
|
||||
rows={rows}
|
||||
columns={columns}
|
||||
getRowId={(r) => r.id}
|
||||
searchText={(r) => `${r.name} ${kindOf(r)}`}
|
||||
selectable={false}
|
||||
views={[
|
||||
{ label: 'Все', match: () => true },
|
||||
{ label: 'Давно не используются', match: (r) => r.tone === 'wn' },
|
||||
]}
|
||||
rowMenu={(r) => ({ onOpen: () => open(r), onDelete: () => setDeleting(r) })}
|
||||
onRowClick={open}
|
||||
emptyMessage="Ключи не зарегистрированы. Добавьте passkey, чтобы входить без пароля."
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="acc">
|
||||
<KvFrame
|
||||
title={me?.email ?? '—'}
|
||||
description="Данные учётной записи"
|
||||
items={[
|
||||
{ label: 'Имя', value: me?.name ?? '—' },
|
||||
{ label: 'Роль', value: me?.is_admin ? 'Администратор' : 'Пользователь' },
|
||||
{ label: 'Приложений', value: String(me?.apps.length ?? 0) },
|
||||
{ label: 'Двухфакторная защита', value: rows.length ? `Passkey ×${rows.length}` : 'Не настроена' },
|
||||
]}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<PortalSheet
|
||||
open={addOpen}
|
||||
onOpenChange={setAddOpen}
|
||||
title="Добавить passkey"
|
||||
description="Браузер предложит создать ключ для этого портала"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setAddOpen(false)}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button disabled={registerMutation.isPending} onClick={() => registerMutation.mutate(newName)}>
|
||||
{registerMutation.isPending ? 'Ожидание…' : 'Создать ключ'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="pk-name">Название ключа</FieldLabel>
|
||||
<Input id="pk-name" value={newName} placeholder="Рабочий ноутбук" onChange={(e) => setNewName(e.target.value)} />
|
||||
<FieldDescription>Чтобы отличать устройства в списке</FieldDescription>
|
||||
</Field>
|
||||
<SignalAlert tone="in" title="Что произойдёт дальше">
|
||||
Откроется системный диалог: подтвердите отпечатком, Face ID, PIN или ключом безопасности. Закрытый ключ не покидает устройство.
|
||||
</SignalAlert>
|
||||
</PortalSheet>
|
||||
|
||||
<PortalSheet
|
||||
open={selected !== null}
|
||||
onOpenChange={(o) => !o && setSelected(null)}
|
||||
title="Passkey"
|
||||
description="Название и сведения о ключе"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="mr-auto"
|
||||
onClick={() => {
|
||||
setDeleting(selected)
|
||||
setSelected(null)
|
||||
}}
|
||||
>
|
||||
<TrashIcon aria-hidden />
|
||||
Удалить
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSelected(null)}>
|
||||
Закрыть
|
||||
</Button>
|
||||
<Button
|
||||
disabled={renameMutation.isPending || !renameValue.trim() || renameValue.trim() === selected?.name}
|
||||
onClick={() => selected && renameMutation.mutate({ id: selected.id, name: renameValue.trim() })}
|
||||
>
|
||||
Сохранить
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="pk-rename">Название</FieldLabel>
|
||||
<Input id="pk-rename" value={renameValue} onChange={(e) => setRenameValue(e.target.value)} />
|
||||
</Field>
|
||||
<KvList
|
||||
items={[
|
||||
['Тип', selected ? kindOf(selected) : ''],
|
||||
['Добавлен', fmtDate(selected?.created_at)],
|
||||
['Последний вход', selected?.last_used_at ? fmtWhen(selected.last_used_at) : 'ещё не использовался'],
|
||||
]}
|
||||
/>
|
||||
</PortalSheet>
|
||||
|
||||
<TypedConfirm
|
||||
open={deleting !== null}
|
||||
onOpenChange={(o) => !o && setDeleting(null)}
|
||||
title="Удалить passkey?"
|
||||
description={`Ключ «${deleting?.name ?? ''}» будет удалён без возможности восстановления. Войти по нему больше не получится.`}
|
||||
expected="удалить"
|
||||
confirmLabel="Удалить ключ"
|
||||
onConfirm={() => deleting && deleteMutation.mutate(deleting.id)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,105 +1,274 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { HistoryIcon, NetworkIcon, OctagonAlertIcon, UserCogIcon } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type {
|
||||
AuditLogEntry,
|
||||
AuditPurgeResponse,
|
||||
AuditSettings,
|
||||
} from '@authportal/shared'
|
||||
import { PageShell } from '@/components/page-shell'
|
||||
import { AuditLogTimeline } from '@/components/reui-kit/audit-log-timeline'
|
||||
import { AuditRetentionPanel } from '@/components/reui-kit/audit-retention-panel'
|
||||
import { api, ApiError } from '@/lib/api-client'
|
||||
import {
|
||||
auditQueryKey,
|
||||
auditQueryOptions,
|
||||
auditSettingsQueryKey,
|
||||
auditSettingsQueryOptions,
|
||||
} from '@/queries/audit'
|
||||
import { Skeleton } from '@authportal/ui/components/skeleton'
|
||||
import type { AuditLogEntry, AuditPurgeResponse, AuditSettings, AuditSeverity } from '@authportal/shared'
|
||||
import { actionMeta, exportAuditCsv, severityLabel, sourceAppLabel } from '@/components/reui-kit/audit-log-helpers'
|
||||
import { CodeBlock, FormFrame, KvList, PageHead, PageTab, PageTabsList, PortalSheet, SettingRow, StatusBadge, TypedConfirm } from '@/components/portal/bits'
|
||||
import { ActivityFeed } from '@/components/portal/canvas-blocks'
|
||||
import { fmtTime, fmtWhen } from '@/components/portal/format'
|
||||
import { kpi } from '@/components/portal/kpi'
|
||||
import { KpiStrip } from '@/components/portal/kpi-strip'
|
||||
import { SectionGrid, TwoLineCell, type GridColumn } from '@/components/portal/section-grid'
|
||||
import type { Tone } from '@/components/portal/tone'
|
||||
import { Button } from '@authportal/ui/components/button'
|
||||
import { Input } from '@authportal/ui/components/input'
|
||||
import { Skeleton } from '@authportal/ui/components/skeleton'
|
||||
import { Tabs, TabsContent } from '@authportal/ui/components/tabs'
|
||||
import { api, ApiError } from '@/lib/api-client'
|
||||
import { auditQueryKey, auditQueryOptions, auditSettingsQueryKey, auditSettingsQueryOptions } from '@/queries/audit'
|
||||
|
||||
export const Route = createFileRoute('/_auth/admin/audit')({
|
||||
component: AdminAuditPage,
|
||||
})
|
||||
|
||||
const SEVERITY_TONE: Record<AuditSeverity, Tone> = { info: 'ok', warning: 'wn', critical: 'er' }
|
||||
|
||||
type Row = {
|
||||
id: string
|
||||
action: string
|
||||
summary: string
|
||||
tone: Tone
|
||||
label: string
|
||||
source: string
|
||||
who: string
|
||||
ip: string
|
||||
when: string
|
||||
entry: AuditLogEntry
|
||||
}
|
||||
|
||||
function AdminAuditPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const {
|
||||
data: entries = [],
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = useQuery(auditQueryOptions({ kind: 'changes', limit: 500 }))
|
||||
const [tab, setTab] = useState('feed')
|
||||
const [entry, setEntry] = useState<Row | null>(null)
|
||||
const [purgeOpen, setPurgeOpen] = useState(false)
|
||||
const [daysDraft, setDaysDraft] = useState<string | null>(null)
|
||||
|
||||
const entriesQ = useQuery(auditQueryOptions({ kind: 'changes', limit: 500 }))
|
||||
const { data: settings } = useQuery(auditSettingsQueryOptions)
|
||||
const retention = settings?.retention_days ?? 90
|
||||
const entries = useMemo(() => entriesQ.data ?? [], [entriesQ.data])
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (retention_days: number) =>
|
||||
api.put<AuditSettings>('/api/v1/admin/audit/settings', {
|
||||
retention_days,
|
||||
}),
|
||||
mutationFn: (retention_days: number) => api.put<AuditSettings>('/api/v1/admin/audit/settings', { retention_days }),
|
||||
onSuccess: async (data) => {
|
||||
await queryClient.invalidateQueries({ queryKey: auditSettingsQueryKey })
|
||||
await queryClient.invalidateQueries({ queryKey: auditQueryKey })
|
||||
setDaysDraft(null)
|
||||
toast.success(`Срок хранения: ${data.retention_days} дн.`)
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof ApiError ? err.message : 'Не удалось сохранить',
|
||||
)
|
||||
},
|
||||
onError: (err) => toast.error(err instanceof ApiError ? err.message : 'Не удалось сохранить'),
|
||||
})
|
||||
|
||||
const purgeMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
api.post<AuditPurgeResponse>('/api/v1/admin/audit/purge'),
|
||||
mutationFn: () => api.post<AuditPurgeResponse>('/api/v1/admin/audit/purge'),
|
||||
onSuccess: async (data) => {
|
||||
await queryClient.invalidateQueries({ queryKey: auditQueryKey })
|
||||
setPurgeOpen(false)
|
||||
toast.success(`Удалено записей: ${data.deleted}`)
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof ApiError ? err.message : 'Ошибка очистки')
|
||||
},
|
||||
onError: (err) => toast.error(err instanceof ApiError ? err.message : 'Ошибка очистки'),
|
||||
})
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<div className="flex flex-col gap-6">
|
||||
<AuditRetentionPanel
|
||||
retentionDays={settings?.retention_days ?? 90}
|
||||
saving={saveMutation.isPending}
|
||||
purging={purgeMutation.isPending}
|
||||
onSave={(days) => saveMutation.mutate(days)}
|
||||
onPurge={() => purgeMutation.mutate()}
|
||||
/>
|
||||
const rows = useMemo<Row[]>(
|
||||
() =>
|
||||
entries.map((e) => ({
|
||||
id: e.id,
|
||||
action: e.action,
|
||||
summary: e.summary,
|
||||
tone: SEVERITY_TONE[e.severity],
|
||||
label: severityLabel[e.severity],
|
||||
source: sourceAppLabel(e.source_app),
|
||||
who: e.actor_email?.split('@')[0] ?? 'system',
|
||||
ip: e.ip ?? '—',
|
||||
when: fmtWhen(e.created_at),
|
||||
entry: e,
|
||||
})),
|
||||
[entries],
|
||||
)
|
||||
|
||||
{error ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-destructive text-sm">
|
||||
{error instanceof ApiError ? error.message : 'Ошибка загрузки'}
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-fit"
|
||||
onClick={() => refetch()}
|
||||
>
|
||||
Повторить
|
||||
const feed = useMemo(
|
||||
() =>
|
||||
rows.slice(0, 5).map((r) => ({
|
||||
t: fmtTime(r.entry.created_at),
|
||||
title: actionMeta(r.action).label,
|
||||
text: `${r.summary} · ${r.who} · ${r.source}`,
|
||||
label: r.label,
|
||||
tone: r.tone,
|
||||
})),
|
||||
[rows],
|
||||
)
|
||||
|
||||
const columns = useMemo<GridColumn<Row>[]>(
|
||||
() => [
|
||||
{ id: 'action', title: 'Событие', size: 340, sortValue: (r) => r.action, cell: (r) => <TwoLineCell dot={r.tone} title={<span className="font-mono text-[13px]">{r.action}</span>} sub={r.summary} /> },
|
||||
{ id: 'status', title: 'Статус', size: 120, cell: (r) => <StatusBadge tone={r.tone}>{r.label}</StatusBadge> },
|
||||
{ id: 'src', title: 'Источник', size: 160, sortValue: (r) => r.source, cell: (r) => <span className="font-mono text-[12.5px] whitespace-nowrap">{r.source}</span> },
|
||||
{ id: 'who', title: 'Кто', size: 120, cell: (r) => <span className="font-mono text-[12.5px] whitespace-nowrap">{r.who}</span> },
|
||||
{ id: 'ip', title: 'IP', size: 140, cell: (r) => <span className="font-mono text-[12.5px] whitespace-nowrap">{r.ip}</span> },
|
||||
{ id: 'when', title: 'Когда', size: 150, sortValue: (r) => r.entry.created_at, cell: (r) => <span className="font-mono text-[12.5px] whitespace-nowrap">{r.when}</span> },
|
||||
],
|
||||
[],
|
||||
)
|
||||
|
||||
const stats = {
|
||||
all: entries.length,
|
||||
access: entries.filter((e) => e.action === 'user.access_update').length,
|
||||
critical: entries.filter((e) => e.severity === 'critical').length,
|
||||
sources: new Set(entries.map((e) => e.source_app)).size,
|
||||
}
|
||||
|
||||
const daysValue = daysDraft ?? String(retention)
|
||||
const parsedDays = Number.parseInt(daysValue, 10)
|
||||
const daysValid = Number.isFinite(parsedDays) && parsedDays >= 7 && parsedDays <= 3650
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHead
|
||||
title="Изменения"
|
||||
sub="Журнал действий администраторов и приложений · портал, EvoFirewall, EvoBGP, MikrotikManager и другие через ingest"
|
||||
actions={
|
||||
<>
|
||||
<Button variant="outline" disabled={rows.length === 0} onClick={() => exportAuditCsv(entries)}>
|
||||
Экспорт CSV
|
||||
</Button>
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-16 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<AuditLogTimeline
|
||||
entries={entries as AuditLogEntry[]}
|
||||
totalCount={entries.length}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</PageShell>
|
||||
<Button variant="outline" onClick={() => setPurgeOpen(true)}>
|
||||
Очистить старые записи…
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
{entriesQ.isError ? (
|
||||
<div role="alert" className="border-destructive/40 bg-destructive/10 flex flex-wrap items-center justify-between gap-3 rounded-xl border px-4 py-3 text-sm">
|
||||
<span>{entriesQ.error instanceof ApiError ? entriesQ.error.message : 'Не удалось загрузить журнал. Повторите запрос.'}</span>
|
||||
<Button variant="outline" onClick={() => void entriesQ.refetch()}>
|
||||
Повторить
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<KpiStrip
|
||||
aria-label="Показатели"
|
||||
items={[
|
||||
kpi('all', 'Событий', String(stats.all), { icon: HistoryIcon, badge: 'в выборке' }),
|
||||
kpi('acc', 'Изменений прав', String(stats.access), { icon: UserCogIcon, tone: 'ok', badge: 'user.access_update' }),
|
||||
kpi('crit', 'Критичных', String(stats.critical), { icon: OctagonAlertIcon, tone: stats.critical ? 'er' : 'neutral', badge: 'critical' }),
|
||||
kpi('src', 'Источников', String(stats.sources), { icon: NetworkIcon, badge: 'портал и приложения' }),
|
||||
]}
|
||||
/>
|
||||
<Tabs value={tab} onValueChange={setTab} className="min-w-0">
|
||||
<PageTabsList>
|
||||
<PageTab value="feed" label="Лента" />
|
||||
<PageTab value="table" label="Таблица" count={rows.length} />
|
||||
<PageTab value="retention" label="Ротация" />
|
||||
</PageTabsList>
|
||||
<TabsContent value="feed" className="min-w-0">
|
||||
{entriesQ.isLoading ? (
|
||||
<Skeleton className="h-64 w-full rounded-xl" />
|
||||
) : (
|
||||
<ActivityFeed
|
||||
title="Лента изменений"
|
||||
description="Последние события · цвет точки — важность"
|
||||
items={feed}
|
||||
action={
|
||||
<Button variant="outline" onClick={() => setTab('table')}>
|
||||
Весь журнал
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="table" className="min-w-0">
|
||||
{entriesQ.isLoading ? (
|
||||
<Skeleton className="h-72 w-full rounded-xl" />
|
||||
) : (
|
||||
<SectionGrid
|
||||
title="Журнал изменений"
|
||||
description="Поиск по событию, пользователю и IP · виды по важности"
|
||||
rows={rows}
|
||||
columns={columns}
|
||||
getRowId={(r) => r.id}
|
||||
searchText={(r) => `${r.action} ${r.summary} ${r.who} ${r.ip}`}
|
||||
selectable={false}
|
||||
views={[
|
||||
{ label: 'Все', match: () => true },
|
||||
{ label: 'Warning и выше', match: (r) => r.tone === 'wn' || r.tone === 'er' },
|
||||
{ label: 'Critical', match: (r) => r.tone === 'er' },
|
||||
]}
|
||||
onRowClick={setEntry}
|
||||
emptyMessage="В журнале нет записей."
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="retention">
|
||||
<FormFrame title="Ротация журнала" description="Сколько хранить записи и как очищать" badge={`${retention} дней`}>
|
||||
<SettingRow title="Срок хранения" description="Записи старше удаляются автоматически каждый час · от 7 до 3650 дней">
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
min={7}
|
||||
max={3650}
|
||||
value={daysValue}
|
||||
onChange={(e) => setDaysDraft(e.target.value)}
|
||||
aria-label="Срок хранения, дней"
|
||||
className="w-28 tabular-nums"
|
||||
/>
|
||||
<Button disabled={!daysValid || saveMutation.isPending || parsedDays === retention} onClick={() => saveMutation.mutate(parsedDays)}>
|
||||
{saveMutation.isPending ? 'Сохранение…' : 'Сохранить'}
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow title="Записей в журнале" description="В выборке изменений">
|
||||
<StatusBadge tone="mu">{String(entries.length)}</StatusBadge>
|
||||
</SettingRow>
|
||||
</FormFrame>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<PortalSheet
|
||||
open={entry !== null}
|
||||
onOpenChange={(o) => !o && setEntry(null)}
|
||||
title="Событие журнала"
|
||||
description="Детали записи"
|
||||
footer={
|
||||
<Button variant="outline" onClick={() => setEntry(null)}>
|
||||
Закрыть
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{entry ? (
|
||||
<>
|
||||
<KvList items={[['Событие', `${entry.action} · ${entry.summary}`]]} />
|
||||
<div>
|
||||
<StatusBadge tone={entry.tone}>{entry.label}</StatusBadge>
|
||||
</div>
|
||||
<KvList
|
||||
items={[
|
||||
['Источник', entry.source],
|
||||
['Кто', `${entry.entry.actor_email ?? 'system'} · ${entry.ip}`],
|
||||
['Когда', fmtWhen(entry.entry.created_at)],
|
||||
]}
|
||||
/>
|
||||
<CodeBlock label="Подробности">
|
||||
{JSON.stringify(
|
||||
{ target_type: entry.entry.target_type, target_id: entry.entry.target_id, details: entry.entry.details },
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</CodeBlock>
|
||||
</>
|
||||
) : null}
|
||||
</PortalSheet>
|
||||
|
||||
<TypedConfirm
|
||||
open={purgeOpen}
|
||||
onOpenChange={setPurgeOpen}
|
||||
title="Очистить старые записи?"
|
||||
description={`Будут безвозвратно удалены записи старше ${retention} дней. Само действие попадёт в журнал как audit.purge.`}
|
||||
expected="очистить"
|
||||
confirmLabel="Очистить"
|
||||
onConfirm={() => purgeMutation.mutate()}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,542 +1,315 @@
|
||||
/**
|
||||
* Admin logins journal — history DataGrid + active sessions.
|
||||
* Preview: https://reui.io/preview/base/data-grid-filtering-2 · https://reui.io/preview/base/stats-12
|
||||
* Sessions DNA: https://reui.io/preview/base/solution-users-2
|
||||
*/
|
||||
import { useMemo, useState } from 'react'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
type ColumnDef,
|
||||
type PaginationState,
|
||||
type SortingState,
|
||||
useTable,
|
||||
} from '@tanstack/react-table'
|
||||
import { CircleCheckIcon, GlobeIcon, MonitorSmartphoneIcon, ShieldAlertIcon } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { AdminSession, AuditLogEntry } from '@authportal/shared'
|
||||
import {
|
||||
KeyRoundIcon,
|
||||
LogInIcon,
|
||||
ShieldAlertIcon,
|
||||
Trash2Icon,
|
||||
} from 'lucide-react'
|
||||
import { PageShell } from '@/components/page-shell'
|
||||
import { KpiStatGrid } from '@/components/reui-kit/kpi-stat-grid'
|
||||
import {
|
||||
actionMeta,
|
||||
detailString,
|
||||
formatEventTime,
|
||||
matchesRange,
|
||||
sourceAppLabel,
|
||||
type AuditRange,
|
||||
} from '@/components/reui-kit/audit-log-helpers'
|
||||
import { Badge } from '@/components/reui/badge'
|
||||
import { DATA_GRID_RU } from '@/lib/reui-ru'
|
||||
import { DataGrid, dataGridFeatures, type DataGridFeatures } from '@/components/reui/data-grid/data-grid'
|
||||
import { DataGridColumnHeader } from '@/components/reui/data-grid/data-grid-column-header'
|
||||
import { DataGridPagination } from '@/components/reui/data-grid/data-grid-pagination'
|
||||
import { DataGridScrollArea } from '@/components/reui/data-grid/data-grid-scroll-area'
|
||||
import { DataGridTable } from '@/components/reui/data-grid/data-grid-table'
|
||||
import {
|
||||
Frame,
|
||||
FrameFooter,
|
||||
FrameHeader,
|
||||
FramePanel,
|
||||
FrameTitle,
|
||||
} from '@/components/reui/frame'
|
||||
import { auditQueryOptions } from '@/queries/audit'
|
||||
import {
|
||||
sessionsListQueryKey,
|
||||
sessionsQueryOptions,
|
||||
} from '@/queries/sessions'
|
||||
import { api, ApiError } from '@/lib/api-client'
|
||||
import { actionMeta, detailString, exportAuditCsv, matchesRange, sourceAppLabel, type AuditRange } from '@/components/reui-kit/audit-log-helpers'
|
||||
import { ExplainBanner } from '@/components/portal/explain-banner'
|
||||
import { CodeBlock, KvList, PageHead, PageTab, PageTabsList, PortalSheet, Segmented, StatusBadge } from '@/components/portal/bits'
|
||||
import { fmtWhen } from '@/components/portal/format'
|
||||
import { kpi } from '@/components/portal/kpi'
|
||||
import { KpiStrip } from '@/components/portal/kpi-strip'
|
||||
import { SectionGrid, TwoLineCell, type GridColumn } from '@/components/portal/section-grid'
|
||||
import type { Tone } from '@/components/portal/tone'
|
||||
import { Button } from '@authportal/ui/components/button'
|
||||
import { Skeleton } from '@authportal/ui/components/skeleton'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@authportal/ui/components/tabs'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@authportal/ui/components/select'
|
||||
import { RANGE_OPTIONS } from '@/components/reui-kit/audit-log-helpers'
|
||||
import { Tabs, TabsContent } from '@authportal/ui/components/tabs'
|
||||
import { api, ApiError } from '@/lib/api-client'
|
||||
import { auditQueryOptions } from '@/queries/audit'
|
||||
import { sessionsListQueryKey, sessionsQueryOptions } from '@/queries/sessions'
|
||||
|
||||
export const Route = createFileRoute('/_auth/admin/logins')({
|
||||
component: AdminLoginsPage,
|
||||
})
|
||||
|
||||
type ResultFilter = 'all' | 'success' | 'failed'
|
||||
const PERIODS: Array<{ label: string; value: AuditRange }> = [
|
||||
{ label: '24 ч', value: '24h' },
|
||||
{ label: '7 д', value: '7d' },
|
||||
{ label: '30 д', value: '30d' },
|
||||
{ label: '90 д', value: '90d' },
|
||||
]
|
||||
|
||||
function resultVariant(action: string) {
|
||||
if (action === 'auth.login_failed') return 'warning-outline' as const
|
||||
if (action === 'auth.sso_handoff') return 'info-outline' as const
|
||||
return 'success-outline' as const
|
||||
type LoginRow = {
|
||||
id: string
|
||||
login: string
|
||||
client: string
|
||||
tone: Tone
|
||||
status: string
|
||||
time: string
|
||||
ip: string
|
||||
app: string
|
||||
reason: string
|
||||
entry: AuditLogEntry
|
||||
}
|
||||
|
||||
type SessionRow = {
|
||||
id: string
|
||||
user: string
|
||||
note: string
|
||||
ipClient: string
|
||||
created: string
|
||||
expires: string
|
||||
}
|
||||
|
||||
const FAILED = 'auth.login_failed'
|
||||
const isOk = (a: string) => a === 'auth.login' || a === 'auth.sso_handoff'
|
||||
|
||||
function toneOf(action: string): Tone {
|
||||
if (action === FAILED) return 'er'
|
||||
if (action === 'auth.sso_handoff') return 'in'
|
||||
if (action === 'auth.logout') return 'wn'
|
||||
return 'ok'
|
||||
}
|
||||
|
||||
function shortUa(ua: string | null | undefined) {
|
||||
if (!ua) return '—'
|
||||
const m = /(Edg|Chrome|Firefox|Safari)\/(\d+)/.exec(ua)
|
||||
const os = /Windows|Mac OS X|Linux|iPhone|Android/.exec(ua)?.[0]?.replace('Mac OS X', 'macOS')
|
||||
return [m ? `${m[1] === 'Edg' ? 'Edge' : m[1]} ${m[2]}` : ua.slice(0, 24), os].filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
function AdminLoginsPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const [tab, setTab] = useState<'history' | 'sessions'>('history')
|
||||
const [resultFilter, setResultFilter] = useState<ResultFilter>('all')
|
||||
const [range, setRange] = useState<AuditRange>('7d')
|
||||
const [pagination, setPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: 20,
|
||||
})
|
||||
const [sorting, setSorting] = useState<SortingState>([
|
||||
{ id: 'created_at', desc: true },
|
||||
])
|
||||
const navigate = useNavigate()
|
||||
const [range, setRange] = useState(0)
|
||||
const [event, setEvent] = useState<LoginRow | null>(null)
|
||||
|
||||
const {
|
||||
data: entries = [],
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = useQuery(auditQueryOptions({ kind: 'logins', limit: 500 }))
|
||||
const entriesQ = useQuery(auditQueryOptions({ kind: 'logins', limit: 500 }))
|
||||
const sessionsQ = useQuery(sessionsQueryOptions())
|
||||
const entries = useMemo(() => entriesQ.data ?? [], [entriesQ.data])
|
||||
const sessions = useMemo(() => sessionsQ.data ?? [], [sessionsQ.data])
|
||||
const period = PERIODS[range]!.value
|
||||
|
||||
const {
|
||||
data: sessions = [],
|
||||
isLoading: sessionsLoading,
|
||||
error: sessionsError,
|
||||
refetch: refetchSessions,
|
||||
} = useQuery(sessionsQueryOptions())
|
||||
|
||||
const revokeMutation = useMutation({
|
||||
const revoke = useMutation({
|
||||
mutationFn: (id: string) => api.delete(`/api/v1/admin/sessions/${id}`),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: sessionsListQueryKey() })
|
||||
toast.success('Сессия отозвана')
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof ApiError ? err.message : 'Не удалось отозвать сессию',
|
||||
)
|
||||
toast.success('Сессия завершена')
|
||||
},
|
||||
onError: (err) => toast.error(err instanceof ApiError ? err.message : 'Не удалось завершить сессию'),
|
||||
})
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
return entries.filter((e) => {
|
||||
if (!matchesRange(e, range)) return false
|
||||
if (resultFilter === 'success') {
|
||||
return e.action === 'auth.login' || e.action === 'auth.sso_handoff'
|
||||
}
|
||||
if (resultFilter === 'failed') return e.action === 'auth.login_failed'
|
||||
return true
|
||||
})
|
||||
}, [entries, range, resultFilter])
|
||||
const rows = useMemo<LoginRow[]>(
|
||||
() =>
|
||||
entries
|
||||
.filter((e) => matchesRange(e, period))
|
||||
.map((e) => ({
|
||||
id: e.id,
|
||||
login: e.actor_email ?? '—',
|
||||
client: shortUa(detailString(e.details, 'user_agent')),
|
||||
tone: toneOf(e.action),
|
||||
status: actionMeta(e.action).label,
|
||||
time: fmtWhen(e.created_at),
|
||||
ip: e.ip ?? '—',
|
||||
app: sourceAppLabel(detailString(e.details, 'target_app') ?? e.source_app),
|
||||
reason: detailString(e.details, 'reason') ?? '—',
|
||||
entry: e,
|
||||
})),
|
||||
[entries, period],
|
||||
)
|
||||
|
||||
const kpi = useMemo(() => {
|
||||
const sessionRows = useMemo<SessionRow[]>(
|
||||
() =>
|
||||
sessions.map((s: AdminSession) => ({
|
||||
id: s.id,
|
||||
user: s.email,
|
||||
note: s.name,
|
||||
ipClient: `${s.ip ?? '—'} · ${shortUa(s.user_agent)}`,
|
||||
created: fmtWhen(s.created_at),
|
||||
expires: fmtWhen(s.expires_at),
|
||||
})),
|
||||
[sessions],
|
||||
)
|
||||
|
||||
const stats = useMemo(() => {
|
||||
const day = entries.filter((e) => matchesRange(e, '24h'))
|
||||
const ok = day.filter(
|
||||
(e) => e.action === 'auth.login' || e.action === 'auth.sso_handoff',
|
||||
).length
|
||||
const fail = day.filter((e) => e.action === 'auth.login_failed').length
|
||||
const ips = new Set(
|
||||
day.map((e) => e.ip).filter((ip): ip is string => Boolean(ip)),
|
||||
)
|
||||
return { ok, fail, ips: ips.size, sessions: sessions.length }
|
||||
}, [entries, sessions.length])
|
||||
return {
|
||||
ok: day.filter((e) => isOk(e.action)).length,
|
||||
fail: day.filter((e) => e.action === FAILED).length,
|
||||
ips: new Set(day.map((e) => e.ip).filter(Boolean)).size,
|
||||
users: new Set(sessions.map((s) => s.user_id)).size,
|
||||
}
|
||||
}, [entries, sessions])
|
||||
|
||||
const historyColumns = useMemo<ColumnDef<DataGridFeatures, AuditLogEntry>[]>(
|
||||
// Серия неудач: 5 и больше с одного IP за последние 10 минут (по времени самой свежей записи журнала).
|
||||
const burst = useMemo(() => {
|
||||
const latest = entries.reduce((m, e) => Math.max(m, new Date(e.created_at).getTime()), 0)
|
||||
const byIp = new Map<string, AuditLogEntry[]>()
|
||||
for (const e of entries) {
|
||||
if (e.action !== FAILED || !e.ip) continue
|
||||
if (latest - new Date(e.created_at).getTime() > 10 * 60 * 1000) continue
|
||||
byIp.set(e.ip, [...(byIp.get(e.ip) ?? []), e])
|
||||
}
|
||||
const top = [...byIp.entries()].sort((a, b) => b[1].length - a[1].length)[0]
|
||||
return top && top[1].length >= 5 ? { ip: top[0], n: top[1].length, login: top[1][0]!.actor_email ?? '—' } : null
|
||||
}, [entries])
|
||||
|
||||
const loginCols = useMemo<GridColumn<LoginRow>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Время" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm tabular-nums">
|
||||
{formatEventTime(row.original.created_at)}
|
||||
</span>
|
||||
),
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: 'result',
|
||||
accessorFn: (r) => r.action,
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Результат" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={resultVariant(row.original.action)} size="sm">
|
||||
{actionMeta(row.original.action).label}
|
||||
</Badge>
|
||||
),
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
accessorKey: 'actor_email',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Логин" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="truncate text-sm font-medium">
|
||||
{row.original.actor_email ?? '—'}
|
||||
</span>
|
||||
),
|
||||
size: 200,
|
||||
},
|
||||
{
|
||||
accessorKey: 'ip',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="IP" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="font-mono text-xs tabular-nums">
|
||||
{row.original.ip ?? '—'}
|
||||
</span>
|
||||
),
|
||||
size: 130,
|
||||
},
|
||||
{
|
||||
id: 'ua',
|
||||
accessorFn: (r) => detailString(r.details, 'user_agent') ?? '',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="User-Agent" column={column} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const ua = detailString(row.original.details, 'user_agent')
|
||||
return (
|
||||
<span className="text-muted-foreground line-clamp-1 max-w-[220px] text-xs" title={ua ?? undefined}>
|
||||
{ua ?? '—'}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
size: 220,
|
||||
},
|
||||
{
|
||||
id: 'app',
|
||||
accessorFn: (r) =>
|
||||
detailString(r.details, 'target_app') ?? r.source_app,
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Приложение" column={column} />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const app =
|
||||
detailString(row.original.details, 'target_app') ??
|
||||
row.original.source_app
|
||||
return (
|
||||
<Badge variant="outline" size="sm">
|
||||
{sourceAppLabel(app)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
size: 120,
|
||||
},
|
||||
{
|
||||
id: 'reason',
|
||||
accessorFn: (r) => detailString(r.details, 'reason') ?? '',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Причина" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm">
|
||||
{detailString(row.original.details, 'reason') ?? '—'}
|
||||
</span>
|
||||
),
|
||||
size: 120,
|
||||
},
|
||||
{ id: 'login', title: 'Логин', size: 260, sortValue: (r) => r.login, cell: (r) => <TwoLineCell dot={r.tone} title={r.login} sub={r.client} /> },
|
||||
{ id: 'status', title: 'Статус', size: 130, cell: (r) => <StatusBadge tone={r.tone}>{r.status}</StatusBadge> },
|
||||
{ id: 'time', title: 'Время', size: 150, sortValue: (r) => r.entry.created_at, cell: (r) => <span className="font-mono text-[12.5px] whitespace-nowrap">{r.time}</span> },
|
||||
{ id: 'ip', title: 'IP', size: 150, sortValue: (r) => r.ip, cell: (r) => <span className="font-mono text-[12.5px]">{r.ip}</span> },
|
||||
{ id: 'app', title: 'Приложение', size: 160, cell: (r) => <span className="font-mono text-[12.5px]">{r.app}</span> },
|
||||
{ id: 'reason', title: 'Причина', size: 200, cell: (r) => <span className="font-mono text-[12.5px]">{r.reason}</span> },
|
||||
],
|
||||
[],
|
||||
)
|
||||
|
||||
const historyTable = useTable({
|
||||
features: dataGridFeatures,
|
||||
data: filtered,
|
||||
columns: historyColumns,
|
||||
state: { pagination, sorting },
|
||||
onPaginationChange: setPagination,
|
||||
onSortingChange: setSorting,
|
||||
})
|
||||
|
||||
const sessionColumns = useMemo<ColumnDef<DataGridFeatures, AdminSession>[]>(
|
||||
const sessionCols = useMemo<GridColumn<SessionRow>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: 'email',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Пользователь" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<span className="truncate text-sm font-medium">
|
||||
{row.original.name}
|
||||
</span>
|
||||
<span className="text-muted-foreground truncate text-xs">
|
||||
{row.original.email}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
size: 200,
|
||||
},
|
||||
{
|
||||
accessorKey: 'ip',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="IP" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="font-mono text-xs tabular-nums">
|
||||
{row.original.ip ?? '—'}
|
||||
</span>
|
||||
),
|
||||
size: 130,
|
||||
},
|
||||
{
|
||||
accessorKey: 'user_agent',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="User-Agent" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span
|
||||
className="text-muted-foreground line-clamp-1 max-w-[240px] text-xs"
|
||||
title={row.original.user_agent ?? undefined}
|
||||
>
|
||||
{row.original.user_agent ?? '—'}
|
||||
</span>
|
||||
),
|
||||
size: 240,
|
||||
},
|
||||
{
|
||||
accessorKey: 'created_at',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Создана" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm tabular-nums">
|
||||
{formatEventTime(row.original.created_at)}
|
||||
</span>
|
||||
),
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
accessorKey: 'expires_at',
|
||||
header: ({ column }) => (
|
||||
<DataGridColumnHeader title="Истекает" column={column} />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm tabular-nums">
|
||||
{formatEventTime(row.original.expires_at)}
|
||||
</span>
|
||||
),
|
||||
size: 140,
|
||||
},
|
||||
{
|
||||
id: 'actions',
|
||||
header: '',
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={revokeMutation.isPending}
|
||||
onClick={() => revokeMutation.mutate(row.original.id)}
|
||||
>
|
||||
<Trash2Icon aria-hidden="true" />
|
||||
Отозвать
|
||||
</Button>
|
||||
),
|
||||
size: 120,
|
||||
},
|
||||
{ id: 'user', title: 'Пользователь', size: 260, sortValue: (r) => r.user, cell: (r) => <TwoLineCell dot="ok" title={r.user} sub={r.note} /> },
|
||||
{ id: 'status', title: 'Статус', size: 110, cell: () => <StatusBadge tone="ok">Активна</StatusBadge> },
|
||||
{ id: 'ip', title: 'IP · клиент', size: 280, cell: (r) => <span className="font-mono text-[12.5px]">{r.ipClient}</span> },
|
||||
{ id: 'created', title: 'Создана', size: 150, cell: (r) => <span className="font-mono text-[12.5px] whitespace-nowrap">{r.created}</span> },
|
||||
{ id: 'exp', title: 'Истекает', size: 150, cell: (r) => <span className="font-mono text-[12.5px] whitespace-nowrap">{r.expires}</span> },
|
||||
],
|
||||
[revokeMutation],
|
||||
[],
|
||||
)
|
||||
|
||||
const [sessionPagination, setSessionPagination] = useState<PaginationState>({
|
||||
pageIndex: 0,
|
||||
pageSize: 20,
|
||||
})
|
||||
const sessionsTable = useTable({
|
||||
features: dataGridFeatures,
|
||||
data: sessions,
|
||||
columns: sessionColumns,
|
||||
state: { pagination: sessionPagination },
|
||||
onPaginationChange: setSessionPagination,
|
||||
})
|
||||
const loading = entriesQ.isLoading || sessionsQ.isLoading
|
||||
const failedQuery = entriesQ.isError || sessionsQ.isError
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<div className="flex flex-col gap-6">
|
||||
<KpiStatGrid
|
||||
items={[
|
||||
{
|
||||
id: 'ok',
|
||||
label: 'Успешные (24ч)',
|
||||
value: kpi.ok,
|
||||
icon: <LogInIcon />,
|
||||
iconClassName: 'text-success',
|
||||
hint: 'Вход и SSO',
|
||||
},
|
||||
{
|
||||
id: 'fail',
|
||||
label: 'Неудачи (24ч)',
|
||||
value: kpi.fail,
|
||||
icon: <ShieldAlertIcon />,
|
||||
iconClassName: 'text-warning',
|
||||
variant: kpi.fail > 0 ? 'warning' : 'default',
|
||||
},
|
||||
{
|
||||
id: 'ips',
|
||||
label: 'Уникальные IP (24ч)',
|
||||
value: kpi.ips,
|
||||
icon: <KeyRoundIcon />,
|
||||
},
|
||||
{
|
||||
id: 'sessions',
|
||||
label: 'Активные сессии',
|
||||
value: kpi.sessions,
|
||||
icon: <KeyRoundIcon />,
|
||||
onSelect: () => setTab('sessions'),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<Tabs
|
||||
value={tab}
|
||||
onValueChange={(v) => {
|
||||
if (v === 'history' || v === 'sessions') setTab(v)
|
||||
}}
|
||||
>
|
||||
<TabsList
|
||||
variant="line"
|
||||
className="h-10! w-full justify-start gap-6 border-b"
|
||||
<>
|
||||
<PageHead
|
||||
title="Входы"
|
||||
sub="Журнал входов и активные сессии · портал и SSO в приложения"
|
||||
actions={
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={rows.length === 0}
|
||||
onClick={() => {
|
||||
exportAuditCsv(rows.map((r) => r.entry))
|
||||
toast.success(`CSV сформирован: ${rows.length} записей`)
|
||||
}}
|
||||
>
|
||||
<TabsTrigger value="history" className="px-1 text-sm after:-bottom-px!">
|
||||
История
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="sessions" className="px-1 text-sm after:-bottom-px!">
|
||||
Активные сессии
|
||||
<span className="bg-muted text-muted-foreground ms-2 rounded-md px-1.5 text-xs tabular-nums">
|
||||
{sessions.length}
|
||||
</span>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
Экспорт CSV
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{burst ? (
|
||||
<ExplainBanner
|
||||
tone="er"
|
||||
title={`Подозрительная серия неудач: ${burst.login}.`}
|
||||
text={`${burst.n} неудачных входов с ${burst.ip} за 10 минут. Действия: «Показать», отключить пользователя в разделе «Пользователи».`}
|
||||
>
|
||||
{burst.n} неудачных входов с {burst.ip} за 10 минут. Проверьте журнал и при необходимости отключите учётную запись или заблокируйте адрес.
|
||||
</ExplainBanner>
|
||||
) : null}
|
||||
{failedQuery ? (
|
||||
<div role="alert" className="border-destructive/40 bg-destructive/10 flex flex-wrap items-center justify-between gap-3 rounded-xl border px-4 py-3 text-sm">
|
||||
<span>Не удалось загрузить журнал. Повторите запрос.</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
void entriesQ.refetch()
|
||||
void sessionsQ.refetch()
|
||||
}}
|
||||
>
|
||||
Повторить
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<Segmented label="Период" options={PERIODS.map((p) => p.label)} value={range} onChange={setRange} />
|
||||
<KpiStrip
|
||||
aria-label="Показатели"
|
||||
items={[
|
||||
kpi('ok', 'Успешные (24ч)', String(stats.ok), { icon: CircleCheckIcon, tone: 'ok', badge: 'входы и SSO' }),
|
||||
kpi('fail', 'Неудачи (24ч)', String(stats.fail), { icon: ShieldAlertIcon, tone: stats.fail ? 'er' : 'neutral', badge: 'неверный пароль и др.' }),
|
||||
kpi('ip', 'Уникальные IP (24ч)', String(stats.ips), { icon: GlobeIcon, badge: 'по журналу' }),
|
||||
kpi('sess', 'Активные сессии', String(sessions.length), { icon: MonitorSmartphoneIcon, badge: `${stats.users} пользователей` }),
|
||||
]}
|
||||
/>
|
||||
<Tabs defaultValue="hist" className="min-w-0">
|
||||
<PageTabsList>
|
||||
<PageTab value="hist" label="История" count={rows.length} />
|
||||
<PageTab value="sess" label="Активные сессии" count={sessions.length} />
|
||||
</PageTabsList>
|
||||
<TabsContent value="hist" className="flex min-w-0 flex-col gap-4">
|
||||
{loading ? (
|
||||
<Skeleton className="h-72 w-full rounded-xl" />
|
||||
) : (
|
||||
<SectionGrid
|
||||
title="Журнал входов"
|
||||
description="Поиск по логину и IP · виды по результату · период выбирается выше"
|
||||
rows={rows}
|
||||
columns={loginCols}
|
||||
getRowId={(r) => r.id}
|
||||
searchText={(r) => `${r.login} ${r.ip} ${r.app}`}
|
||||
searchPlaceholder="Логин или IP"
|
||||
selectable={false}
|
||||
views={[
|
||||
{ label: 'Все', match: () => true },
|
||||
{ label: 'Успешные', match: (r) => r.tone === 'ok' || r.tone === 'in' },
|
||||
{ label: 'Неудачные', match: (r) => r.tone === 'er' || r.tone === 'wn' },
|
||||
]}
|
||||
onRowClick={setEvent}
|
||||
emptyMessage="За выбранный период входов не было."
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="sess" className="flex min-w-0 flex-col gap-4">
|
||||
{loading ? (
|
||||
<Skeleton className="h-48 w-full rounded-xl" />
|
||||
) : (
|
||||
<SectionGrid
|
||||
title="Активные сессии"
|
||||
description="Токены, действующие сейчас · завершение сессии выкидывает пользователя из портала и приложений"
|
||||
rows={sessionRows}
|
||||
columns={sessionCols}
|
||||
getRowId={(r) => r.id}
|
||||
selectable={false}
|
||||
emptyMessage="Нет активных сессий."
|
||||
rowMenu={(r) => ({ toggleLabel: 'Завершить сессию', onToggle: () => revoke.mutate(r.id) })}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{tab === 'history' ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Tabs
|
||||
value={resultFilter}
|
||||
onValueChange={(v) => {
|
||||
if (v === 'all' || v === 'success' || v === 'failed') {
|
||||
setResultFilter(v)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TabsList variant="line" className="h-auto gap-4 border-0">
|
||||
<TabsTrigger value="all" className="px-0 pb-1 text-sm">
|
||||
Все
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="success" className="px-0 pb-1 text-sm">
|
||||
Успешные
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="failed" className="px-0 pb-1 text-sm">
|
||||
Неудачи
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Select
|
||||
value={range}
|
||||
onValueChange={(value) => {
|
||||
if (value) setRange(value as AuditRange)
|
||||
}}
|
||||
items={[...RANGE_OPTIONS]}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-40">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{RANGE_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-destructive text-sm">
|
||||
{error instanceof ApiError ? error.message : 'Ошибка загрузки'}
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-fit"
|
||||
onClick={() => refetch()}
|
||||
>
|
||||
Повторить
|
||||
</Button>
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
<Skeleton className="h-64 w-full" />
|
||||
) : (
|
||||
<DataGrid
|
||||
i18n={DATA_GRID_RU}
|
||||
table={historyTable}
|
||||
recordCount={filtered.length}
|
||||
tableLayout={{ dense: true }}
|
||||
>
|
||||
<Frame stacked dense>
|
||||
<FrameHeader>
|
||||
<FrameTitle>Журнал входов</FrameTitle>
|
||||
</FrameHeader>
|
||||
<FramePanel className="p-0">
|
||||
<DataGridScrollArea>
|
||||
<DataGridTable />
|
||||
</DataGridScrollArea>
|
||||
<FrameFooter>
|
||||
<DataGridPagination sizes={[10, 20, 30]} />
|
||||
</FrameFooter>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</DataGrid>
|
||||
)}
|
||||
</div>
|
||||
) : sessionsError ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-destructive text-sm">
|
||||
{sessionsError instanceof ApiError
|
||||
? sessionsError.message
|
||||
: 'Ошибка загрузки'}
|
||||
</p>
|
||||
<PortalSheet
|
||||
open={event !== null}
|
||||
onOpenChange={(o) => !o && setEvent(null)}
|
||||
title="Событие входа"
|
||||
description="Детали записи журнала"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setEvent(null)}>
|
||||
Закрыть
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-fit"
|
||||
onClick={() => refetchSessions()}
|
||||
disabled={!event?.entry.actor_user_id}
|
||||
onClick={() => {
|
||||
const id = event?.entry.actor_user_id
|
||||
setEvent(null)
|
||||
if (id) void navigate({ to: '/admin/users/$userId', params: { userId: id } })
|
||||
}}
|
||||
>
|
||||
Повторить
|
||||
Открыть пользователя
|
||||
</Button>
|
||||
</div>
|
||||
) : sessionsLoading ? (
|
||||
<Skeleton className="h-64 w-full" />
|
||||
) : (
|
||||
<DataGrid
|
||||
i18n={DATA_GRID_RU}
|
||||
table={sessionsTable}
|
||||
recordCount={sessions.length}
|
||||
tableLayout={{ dense: true }}
|
||||
>
|
||||
<Frame stacked dense>
|
||||
<FrameHeader>
|
||||
<FrameTitle>Активные сессии</FrameTitle>
|
||||
</FrameHeader>
|
||||
<FramePanel className="p-0">
|
||||
<DataGridScrollArea>
|
||||
<DataGridTable />
|
||||
</DataGridScrollArea>
|
||||
<FrameFooter>
|
||||
<DataGridPagination sizes={[10, 20, 30]} />
|
||||
</FrameFooter>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
</DataGrid>
|
||||
)}
|
||||
</div>
|
||||
</PageShell>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{event ? (
|
||||
<>
|
||||
<div>
|
||||
<StatusBadge tone={event.tone}>{event.status}</StatusBadge>
|
||||
</div>
|
||||
<KvList
|
||||
items={[
|
||||
['Логин', event.login],
|
||||
['IP', event.ip],
|
||||
['Клиент', event.client],
|
||||
['Приложение', event.app],
|
||||
['Причина', event.reason],
|
||||
]}
|
||||
/>
|
||||
<CodeBlock label="Событие">{`action: ${event.entry.action}\nsource_app: ${event.entry.source_app}\nseverity: ${event.entry.severity}\nip: ${event.ip}\nat: ${event.entry.created_at}`}</CodeBlock>
|
||||
</>
|
||||
) : null}
|
||||
</PortalSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,23 +1,24 @@
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
BadgeCheckIcon,
|
||||
CloudIcon,
|
||||
GlobeIcon,
|
||||
KeyRoundIcon,
|
||||
LayoutDashboardIcon,
|
||||
LayoutGridIcon,
|
||||
ServerIcon,
|
||||
ShieldIcon,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { AppAuthMode, AppId } from '@authportal/shared'
|
||||
import { PageShell } from '@/components/page-shell'
|
||||
import { IconTile } from '@/components/reui/icon-tile'
|
||||
import {
|
||||
Frame,
|
||||
FramePanel,
|
||||
} from '@/components/reui/frame'
|
||||
import { QuickActionGrid } from '@/components/reui-kit/quick-action-grid'
|
||||
import { PageHead, PageTab, PageTabsList } from '@/components/portal/bits'
|
||||
import { AppCards, type AppCardItem } from '@/components/portal/canvas-blocks'
|
||||
import { kpi } from '@/components/portal/kpi'
|
||||
import { KpiStrip } from '@/components/portal/kpi-strip'
|
||||
import { Button } from '@authportal/ui/components/button'
|
||||
import { Skeleton } from '@authportal/ui/components/skeleton'
|
||||
import { Tabs, TabsContent } from '@authportal/ui/components/tabs'
|
||||
import { ssoOpenApp } from '@/lib/auth'
|
||||
import { catalogQueryOptions, meQueryOptions } from '@/queries/auth'
|
||||
|
||||
@@ -35,93 +36,106 @@ const APP_ICONS: Record<AppId, typeof CloudIcon> = {
|
||||
mm: LayoutDashboardIcon,
|
||||
}
|
||||
|
||||
async function openApp(
|
||||
_appId: AppId,
|
||||
baseUrl: string,
|
||||
authMode: AppAuthMode = 'jwt',
|
||||
) {
|
||||
async function openApp(baseUrl: string, authMode: AppAuthMode = 'jwt') {
|
||||
try {
|
||||
await ssoOpenApp(baseUrl, authMode)
|
||||
} catch {
|
||||
toast.error('Не удалось выпустить токен', { description: 'Открываем приложение по базовому адресу — войдите в нём отдельно.' })
|
||||
window.location.href = baseUrl.replace(/\/$/, '')
|
||||
}
|
||||
}
|
||||
|
||||
function AppsPage() {
|
||||
const { data: me, isLoading: meLoading } = useQuery(meQueryOptions)
|
||||
const { data: catalog, isLoading: catalogLoading } = useQuery(
|
||||
catalogQueryOptions,
|
||||
)
|
||||
const isLoading = meLoading || catalogLoading
|
||||
const allowed = new Set(me?.apps ?? [])
|
||||
const apps = (catalog?.apps ?? []).filter((app) => allowed.has(app.id))
|
||||
const { data: catalog, isLoading: catalogLoading, isError, refetch } = useQuery(catalogQueryOptions)
|
||||
|
||||
if (meLoading || catalogLoading) {
|
||||
return (
|
||||
<>
|
||||
<PageHead title="Приложения" sub="Открыть приложение с текущей сессией · SSO handoff без повторного ввода пароля" />
|
||||
<Skeleton className="h-24 w-full rounded-xl" />
|
||||
<Skeleton className="h-64 w-full rounded-xl" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const all = catalog?.apps ?? []
|
||||
const allowedIds = new Set(me?.apps ?? [])
|
||||
const allowed = all.filter((a) => allowedIds.has(a.id))
|
||||
const denied = all.filter((a) => !allowedIds.has(a.id))
|
||||
const modeOf = (a: (typeof all)[number]): AppAuthMode => a.authMode ?? (a.id === 'dns' ? 'oidc' : 'jwt')
|
||||
|
||||
const toCard = (app: (typeof all)[number], open: boolean): AppCardItem => {
|
||||
const Icon = APP_ICONS[app.id] ?? LayoutGridIcon
|
||||
const meta = `${app.url.replace(/^https?:\/\//, '')} · ${modeOf(app) === 'oidc' ? 'OIDC' : 'JWT'}`
|
||||
return {
|
||||
id: app.id,
|
||||
title: app.title,
|
||||
desc: app.description,
|
||||
badge: open ? 'Открыть' : 'Нет доступа',
|
||||
badgeVariant: open ? 'info-light' : 'outline',
|
||||
meta,
|
||||
icon: <Icon />,
|
||||
onSelect: () =>
|
||||
open
|
||||
? void openApp(app.url, modeOf(app))
|
||||
: toast.warning(`Нет доступа к ${app.title}`, { description: 'Запросите права у администратора.' }),
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell>
|
||||
<div className="flex flex-wrap items-end justify-between gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Приложения</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Открыть приложение с текущей сессией (SSO handoff).
|
||||
</p>
|
||||
</div>
|
||||
{me?.is_admin ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
render={<Link to="/admin/apps" />}
|
||||
nativeButton={false}
|
||||
>
|
||||
Ссылки приложений
|
||||
<>
|
||||
<PageHead
|
||||
title="Приложения"
|
||||
sub="Открыть приложение с текущей сессией · SSO handoff без повторного ввода пароля"
|
||||
actions={
|
||||
me?.is_admin ? (
|
||||
<Button variant="outline" render={<Link to="/admin/apps" />} nativeButton={false}>
|
||||
Ссылки приложений
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
{isError ? (
|
||||
<div role="alert" className="border-destructive/40 bg-destructive/10 flex flex-wrap items-center justify-between gap-3 rounded-xl border px-4 py-3 text-sm">
|
||||
<span>Не удалось загрузить каталог приложений. Повторите запрос.</span>
|
||||
<Button variant="outline" onClick={() => void refetch()}>
|
||||
Повторить
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-24 w-full rounded-xl" />
|
||||
))}
|
||||
</div>
|
||||
) : apps.length === 0 ? (
|
||||
<Frame dense className="w-full">
|
||||
<FramePanel className="flex flex-col items-start gap-3 py-10">
|
||||
<IconTile
|
||||
variant="elevated"
|
||||
aria-hidden="true"
|
||||
className="size-10.5 text-muted-foreground"
|
||||
>
|
||||
<LayoutGridIcon />
|
||||
</IconTile>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="font-medium">Нет доступных приложений</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Обратитесь к администратору, чтобы получить доступ.
|
||||
</p>
|
||||
) : null}
|
||||
<KpiStrip
|
||||
aria-label="Показатели"
|
||||
items={[
|
||||
kpi('avail', 'Доступно приложений', String(allowed.length), { icon: LayoutGridIcon, tone: 'ok', badge: `из ${all.length}` }),
|
||||
kpi('jwt', 'JWT SSO', String(allowed.filter((a) => modeOf(a) === 'jwt').length), { icon: KeyRoundIcon, badge: 'fragment-токен' }),
|
||||
kpi('oidc', 'OIDC', String(allowed.filter((a) => modeOf(a) === 'oidc').length), { icon: BadgeCheckIcon, badge: 'внешние RP' }),
|
||||
kpi('role', 'Роль', me?.is_admin ? 'Админ' : 'Пользователь', { icon: ShieldIcon, badge: me?.is_admin ? 'is_admin' : 'доступ по правам' }),
|
||||
]}
|
||||
/>
|
||||
<Tabs defaultValue="all" className="min-w-0">
|
||||
<PageTabsList>
|
||||
<PageTab value="all" label="Доступные" count={allowed.length} />
|
||||
<PageTab value="no" label="Без доступа" count={denied.length} />
|
||||
</PageTabsList>
|
||||
<TabsContent value="all" className="min-w-0">
|
||||
{allowed.length === 0 ? (
|
||||
<div className="text-muted-foreground flex flex-col gap-1 rounded-xl border border-dashed px-4 py-10 text-sm">
|
||||
<b className="text-foreground font-medium">Нет доступных приложений</b>
|
||||
Обратитесь к администратору, чтобы получить доступ.
|
||||
</div>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
) : (
|
||||
<QuickActionGrid
|
||||
title=""
|
||||
actions={apps.map((app) => {
|
||||
const Icon = APP_ICONS[app.id] ?? LayoutGridIcon
|
||||
return {
|
||||
id: app.id,
|
||||
title: app.title,
|
||||
description: app.description,
|
||||
badgeLabel: 'Открыть',
|
||||
icon: <Icon />,
|
||||
onSelect: () =>
|
||||
void openApp(
|
||||
app.id,
|
||||
app.url,
|
||||
app.authMode ?? (app.id === 'dns' ? 'oidc' : 'jwt'),
|
||||
),
|
||||
}
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
</PageShell>
|
||||
) : (
|
||||
<AppCards
|
||||
title="Мои приложения"
|
||||
description="Клик открывает приложение в новой вкладке · портал заново выпускает токен с актуальными правами"
|
||||
items={allowed.map((a) => toCard(a, true))}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="no" className="min-w-0">
|
||||
<AppCards title="Недоступные приложения" description="Права не выданы · запросите у администратора" items={denied.map((a) => toCard(a, false))} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user