Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Joshenlim/fe 4466 audit logs update organization logs as well (#50935)

Joshen Lime3fec137fe74
diff --git a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogs.tsx b/apps/studio/components/interfaces/Account/AuditLogs.tsx
similarity index 87%
rename from apps/studio/components/interfaces/Account/AuditLogs/AuditLogs.tsx
rename to apps/studio/components/interfaces/Account/AuditLogs.tsx
index 5d11147e225..03c69a3d0e2 100644
--- a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogs.tsx
+++ b/apps/studio/components/interfaces/Account/AuditLogs.tsx
@@ -13,12 +13,12 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import { cn, ResizablePanel, ResizablePanelGroup } from 'ui'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
-import { LogsDatePicker } from '../../Settings/Logs/Logs.DatePickers'
-import { AuditLogDetailsPanel } from './AuditLogDetailsPanel'
-import { getAuditLogColumns } from './AuditLogs.columns'
-import { filterByProjects } from './AuditLogs.utils'
-import { AuditLogsSelectionHeader } from './AuditLogsSelectionHeader'
-import { AuditLogsTable } from './AuditLogsTable'
+import { LogsDatePicker } from '../Settings/Logs/Logs.DatePickers'
+import { AuditLogDetailsPanel } from '@/components/interfaces/AuditLogs/AuditLogDetailsPanel'
+import { getAuditLogColumns } from '@/components/interfaces/AuditLogs/AuditLogs.columns'
+import { filterByProjects } from '@/components/interfaces/AuditLogs/AuditLogs.utils'
+import { AuditLogsSelectionHeader } from '@/components/interfaces/AuditLogs/AuditLogsSelectionHeader'
+import { AuditLogsTable } from '@/components/interfaces/AuditLogs/AuditLogsTable'
import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'
import { AlertError } from '@/components/ui/AlertError'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
@@ -82,8 +82,11 @@ export const AuditLogs = () => {
}
)
- const logs = data?.result ?? []
- const filteredLogs = filterByProjects(logs, filters.projects)
+ const logs = useMemo(() => data?.result ?? [], [data?.result])
+ const filteredLogs = useMemo(
+ () => filterByProjects(logs, filters.projects),
+ [logs, filters.projects]
+ )
const lastSelectedRowId = useRef<string | null>(null)
const columns = useMemo(
@@ -218,22 +221,18 @@ export const AuditLogs = () => {
{isSuccess && (
<>
{logs.length === 0 ? (
- <div
- className={cn(
- CONTENT_PADDING,
- 'bg-surface-100 border rounded-sm p-4 flex items-center justify-between'
- )}
- >
- <p className="prose text-sm">You do not have any audit logs available yet</p>
+ <div className={CONTENT_PADDING}>
+ <div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">
+ <p className="prose text-sm">You do not have any audit logs available yet</p>
+ </div>
</div>
) : logs.length > 0 && filteredLogs.length === 0 ? (
- <div
- className={cn(
- CONTENT_PADDING,
- 'bg-surface-100 border rounded-sm p-4 flex items-center justify-between'
- )}
- >
- <p className="prose text-sm">No audit logs found based on the filters applied</p>
+ <div className={CONTENT_PADDING}>
+ <div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">
+ <p className="prose text-sm">
+ No audit logs found based on the filters applied
+ </p>
+ </div>
</div>
) : (
<div className="border-y overflow-hidden flex-1 min-h-0">
diff --git a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogDetailsPanel.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogDetailsPanel.tsx
similarity index 100%
rename from apps/studio/components/interfaces/Account/AuditLogs/AuditLogDetailsPanel.tsx
rename to apps/studio/components/interfaces/AuditLogs/AuditLogDetailsPanel.tsx
diff --git a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogOverview.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogOverview.tsx
similarity index 100%
rename from apps/studio/components/interfaces/Account/AuditLogs/AuditLogOverview.tsx
rename to apps/studio/components/interfaces/AuditLogs/AuditLogOverview.tsx
diff --git a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogs.columns.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogs.columns.tsx
similarity index 84%
rename from apps/studio/components/interfaces/Account/AuditLogs/AuditLogs.columns.tsx
rename to apps/studio/components/interfaces/AuditLogs/AuditLogs.columns.tsx
index 21d009cd953..8a06935ae1c 100644
--- a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogs.columns.tsx
+++ b/apps/studio/components/interfaces/AuditLogs/AuditLogs.columns.tsx
@@ -1,4 +1,4 @@
-import type { ColumnDef } from '@tanstack/react-table'
+import type { CellContext, ColumnDef } from '@tanstack/react-table'
import dayjs from 'dayjs'
import { Box, Boxes } from 'lucide-react'
import type { RefObject } from 'react'
@@ -18,6 +18,7 @@ import { getShiftClickRowSelection } from '@/lib/shift-click-selection'
interface AuditLogColumnsOptions {
projects: { ref?: string; name: string }[]
organizations: { slug?: string; name: string }[]
+ members?: { gotrue_id?: string; username?: string }[]
lastSelectedRowId: RefObject<string | null>
isLoadingProjects: boolean
isLoadingOrganizations: boolean
@@ -26,6 +27,7 @@ interface AuditLogColumnsOptions {
export function getAuditLogColumns({
projects,
organizations,
+ members,
lastSelectedRowId,
isLoadingProjects,
isLoadingOrganizations,
@@ -99,6 +101,35 @@ export function getAuditLogColumns({
headerClassName: 'w-[155px] min-w-[155px] pl-3',
},
},
+ ...(members
+ ? [
+ {
+ id: 'actor',
+ header: 'Actor',
+ accessorFn: (log: AuditLog) => log.actor.user_id ?? log.actor.email,
+ cell: ({ row }: CellContext<AuditLog, unknown>) => {
+ const log = row.original
+ const member = members.find((m) => m.gotrue_id === log.actor.user_id)
+ const name = member?.username || log.actor.email
+
+ if (!name) return <span className="text-foreground-light text-xs">-</span>
+
+ return (
+ <p className="truncate text-foreground-light" title={name}>
+ {name}
+ </p>
+ )
+ },
+ size: 160,
+ minSize: 160,
+ maxSize: 160,
+ meta: {
+ cellClassName: 'w-[160px] min-w-[160px]',
+ headerClassName: 'w-[160px] min-w-[160px]',
+ },
+ } satisfies ColumnDef<AuditLog>,
+ ]
+ : []),
{
id: 'target_type',
header: '',
@@ -163,12 +194,12 @@ export function getAuditLogColumns({
</p>
)
},
- size: 120,
- minSize: 120,
- maxSize: 120,
+ size: 130,
+ minSize: 130,
+ maxSize: 130,
meta: {
- cellClassName: 'w-[120px] min-w-[120px]',
- headerClassName: 'w-[120px] min-w-[120px]',
+ cellClassName: 'w-[130px] min-w-[130px]',
+ headerClassName: 'w-[130px] min-w-[130px]',
},
},
{
diff --git a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogs.utils.ts b/apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts
similarity index 100%
rename from apps/studio/components/interfaces/Account/AuditLogs/AuditLogs.utils.ts
rename to apps/studio/components/interfaces/AuditLogs/AuditLogs.utils.ts
diff --git a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogsSelectionHeader.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogsSelectionHeader.tsx
similarity index 100%
rename from apps/studio/components/interfaces/Account/AuditLogs/AuditLogsSelectionHeader.tsx
rename to apps/studio/components/interfaces/AuditLogs/AuditLogsSelectionHeader.tsx
diff --git a/apps/studio/components/interfaces/Account/AuditLogs/AuditLogsTable.tsx b/apps/studio/components/interfaces/AuditLogs/AuditLogsTable.tsx
similarity index 100%
rename from apps/studio/components/interfaces/Account/AuditLogs/AuditLogsTable.tsx
rename to apps/studio/components/interfaces/AuditLogs/AuditLogsTable.tsx
diff --git a/apps/studio/components/interfaces/AuditLogs/LogDetailsPanel.tsx b/apps/studio/components/interfaces/AuditLogs/LogDetailsPanel.tsx
deleted file mode 100644
index 4dbe508ee01..00000000000
--- a/apps/studio/components/interfaces/AuditLogs/LogDetailsPanel.tsx
+++ /dev/null
@@ -1,154 +0,0 @@
-import dayjs from 'dayjs'
-import { Input, SidePanel, TextArea } from 'ui'
-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-
-import {
- FormSection,
- FormSectionContent,
- FormSectionLabel,
-} from '@/components/ui/Forms/FormSection'
-import {
- TIMESTAMP_MICROS_PER_MS,
- type AuditLog,
-} from '@/data/organizations/organization-audit-logs-query'
-
-interface LogDetailsPanelProps {
- selectedLog?: AuditLog
- onClose: () => void
-}
-
-export const LogDetailsPanel = ({ selectedLog, onClose }: LogDetailsPanelProps) => {
- const timestamp = selectedLog
- ? dayjs(selectedLog.timestamp / TIMESTAMP_MICROS_PER_MS).format('DD MMM YYYY, HH:mm:ss')
- : ''
- const timestampWithTz = selectedLog
- ? dayjs(selectedLog.timestamp / TIMESTAMP_MICROS_PER_MS).format('DD MMM YYYY, HH:mm:ss (ZZ)')
- : ''
-
- return (
- <SidePanel
- size="large"
- header={selectedLog ? `"${selectedLog.action.name}" on ${timestamp}` : ''}
- visible={selectedLog !== undefined}
- onCancel={onClose}
- cancelText="Close"
- >
- <FormSection header={<FormSectionLabel>General</FormSectionLabel>}>
- <FormSectionContent loading={false}>
- <FormItemLayout label="Occurred at" description={timestampWithTz} isReactForm={false}>
- <Input
- readOnly
- size="small"
- value={
- selectedLog
- ? dayjs(selectedLog.timestamp / TIMESTAMP_MICROS_PER_MS).toISOString()
- : ''
- }
- />
- </FormItemLayout>
- <FormItemLayout label="Request ID" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.request_id ?? ''} />
- </FormItemLayout>
- {selectedLog?.organization_slug && (
- <FormItemLayout label="Organization" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog.organization_slug} />
- </FormItemLayout>
- )}
- {selectedLog?.project_ref && (
- <FormItemLayout label="Project ref" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog.project_ref} />
- </FormItemLayout>
- )}
- </FormSectionContent>
- </FormSection>
-
- <SidePanel.Separator />
-
- <FormSection header={<FormSectionLabel>Actor</FormSectionLabel>}>
- <FormSectionContent loading={false}>
- <FormItemLayout label="Token type" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.token_type ?? ''} />
- </FormItemLayout>
- {selectedLog?.actor.email && (
- <FormItemLayout label="Email" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.email ?? ''} />
- </FormItemLayout>
- )}
- {selectedLog?.actor.user_id && (
- <FormItemLayout label="User ID" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.user_id ?? ''} />
- </FormItemLayout>
- )}
- {selectedLog?.actor.ip && (
- <FormItemLayout label="IP address" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.ip ?? ''} />
- </FormItemLayout>
- )}
- {selectedLog?.actor.oauth_app_name && (
- <FormItemLayout label="OAuth app" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.oauth_app_name ?? ''} />
- </FormItemLayout>
- )}
- {selectedLog?.actor.app_name && (
- <FormItemLayout label="App" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.app_name ?? ''} />
- </FormItemLayout>
- )}
- {selectedLog?.actor.partner && (
- <FormItemLayout label="Partner" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.partner ?? ''} />
- </FormItemLayout>
- )}
- {selectedLog?.actor.partner_installation_id && (
- <FormItemLayout label="Partner installation ID" isReactForm={false}>
- <Input
- readOnly
- size="small"
- value={selectedLog?.actor.partner_installation_id ?? ''}
- />
- </FormItemLayout>
- )}
- {selectedLog?.actor.partner_user_email && (
- <FormItemLayout label="Partner user email" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.partner_user_email ?? ''} />
- </FormItemLayout>
- )}
- {selectedLog?.actor.partner_user_id && (
- <FormItemLayout label="Partner user ID" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.actor.partner_user_id ?? ''} />
- </FormItemLayout>
- )}
- </FormSectionContent>
- </FormSection>
-
- <SidePanel.Separator />
-
- <FormSection header={<FormSectionLabel>Action</FormSectionLabel>}>
- <FormSectionContent loading={false}>
- <FormItemLayout label="Name" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.action.name ?? ''} />
- </FormItemLayout>
- <FormItemLayout label="Method" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.action.method ?? ''} />
- </FormItemLayout>
- <FormItemLayout label="Route" isReactForm={false}>
- <Input readOnly size="small" value={selectedLog?.action.route ?? ''} />
- </FormItemLayout>
- <FormItemLayout label="Status" isReactForm={false}>
- <Input readOnly size="small" value={String(selectedLog?.action.status ?? '')} />
- </FormItemLayout>
- {selectedLog?.action.metadata && (
- <FormItemLayout label="Metadata" isReactForm={false}>
- <TextArea
- readOnly
- rows={5}
- className="font-mono input-xs"
- value={JSON.stringify(selectedLog.action.metadata, null, 2)}
- />
- </FormItemLayout>
- )}
- </FormSectionContent>
- </FormSection>
- </SidePanel>
- )
-}
diff --git a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
index 858c8a1aabc..7ed2d4f1a5f 100644
--- a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
+++ b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
@@ -1,56 +1,63 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { keepPreviousData } from '@tanstack/react-query'
+import {
+ getCoreRowModel,
+ getSortedRowModel,
+ useReactTable,
+ type RowSelectionState,
+ type SortingState,
+} from '@tanstack/react-table'
import { useDebounce } from '@uidotdev/usehooks'
import { useParams } from 'common'
import dayjs from 'dayjs'
-import { ArrowDown, ArrowUp, RefreshCw, User } from 'lucide-react'
-import Image from 'next/legacy/image'
-import { useEffect, useMemo, useState } from 'react'
-import { Alert, AlertDescription, AlertTitle, Button, WarningIcon } from 'ui'
+import { RefreshCw } from 'lucide-react'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ cn,
+ ResizablePanel,
+ ResizablePanelGroup,
+ WarningIcon,
+} from 'ui'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
-import {
- filterByProjects,
- filterByUsers,
- formatPartnerIfExists,
- sortAuditLogs,
-} from './AuditLogs.utils'
-import { LogDetailsPanel } from '@/components/interfaces/AuditLogs/LogDetailsPanel'
+import { filterByUsers } from './AuditLogs.utils'
+import { AuditLogDetailsPanel } from '@/components/interfaces/AuditLogs/AuditLogDetailsPanel'
+import { getAuditLogColumns } from '@/components/interfaces/AuditLogs/AuditLogs.columns'
+import { filterByProjects } from '@/components/interfaces/AuditLogs/AuditLogs.utils'
+import { AuditLogsSelectionHeader } from '@/components/interfaces/AuditLogs/AuditLogsSelectionHeader'
+import { AuditLogsTable } from '@/components/interfaces/AuditLogs/AuditLogsTable'
import { LogsDatePicker } from '@/components/interfaces/Settings/Logs/Logs.DatePickers'
import { ScaffoldContainer, ScaffoldSection } from '@/components/layouts/Scaffold'
-import Table from '@/components/to-be-cleaned/Table'
import { AlertError } from '@/components/ui/AlertError'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { FilterPopover } from '@/components/ui/FilterPopover'
import { NoPermission } from '@/components/ui/NoPermission'
import { UpgradeToPro } from '@/components/ui/UpgradeToPro'
-import { useOrganizationRolesV2Query } from '@/data/organization-members/organization-roles-query'
import {
AuditLog,
- TIMESTAMP_MICROS_PER_MS,
useOrganizationAuditLogsQuery,
} from '@/data/organizations/organization-audit-logs-query'
import { useOrganizationMembersQuery } from '@/data/organizations/organization-members-query'
-import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
import { useOrgProjectsInfiniteQuery } from '@/data/projects/org-projects-infinite-query'
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
+const CONTENT_PADDING = 'w-full px-6 xl:px-10'
const logsUpgradeError = 'upgrade to Team or Enterprise Plan to access audit logs.'
-// [Joshen considerations]
-// - Maybe fix the height of the table to the remaining height of the viewport, so that the search input is always visible
-// - We'll need pagination as well if the audit logs get too large, but that needs to be implemented on the API side first if possible
-// - I've hidden time input in the date picker for now cause the time support in the component is a bit iffy, need to investigate
-// - Maybe a rule to follow from here is just everytime we call dayjs, use UTC(), one TZ to rule them all
-
export const AuditLogs = () => {
const { slug } = useParams()
const currentTime = dayjs().utc().set('millisecond', 0)
- const [dateSortDesc, setDateSortDesc] = useState(true)
+ const [search, setSearch] = useState('')
+ const debouncedSearch = useDebounce(search, 500)
+
const [dateRange, setDateRange] = useState({
from: currentTime.subtract(1, 'day').toISOString(),
to: currentTime.toISOString(),
@@ -61,9 +68,6 @@ export const AuditLogs = () => {
projects: [], // project_ref[]
})
- const [search, setSearch] = useState('')
- const debouncedSearch = useDebounce(search, 500)
-
const { can: canReadAuditLogs, isLoading: isLoadingPermissions } = useAsyncCheckPermissions(
PermissionAction.READ,
'notifications'
@@ -90,6 +94,8 @@ export const AuditLogs = () => {
{
enabled: canReadAuditLogs,
retry: false,
+ placeholderData: (previousData, previousQuery) =>
+ previousQuery?.queryKey[1] === slug ? previousData : undefined,
refetchOnWindowFocus: (query) => {
return !query.state.error?.message.endsWith(logsUpgradeError)
},
@@ -102,8 +108,8 @@ export const AuditLogs = () => {
const {
data: projectsData,
- isLoading: isLoadingProjects,
- isFetching,
+ isPending: isLoadingProjects,
+ isFetching: isFetchingProjects,
isFetchingNextPage,
hasNextPage,
fetchNextPage,
@@ -111,22 +117,54 @@ export const AuditLogs = () => {
{ slug, search: search.length === 0 ? search : debouncedSearch },
{ placeholderData: keepPreviousData, enabled: showFilters }
)
- const { data: organizations } = useOrganizationsQuery({
- enabled: showFilters,
- })
- const { data: members } = useOrganizationMembersQuery({ slug }, { enabled: showFilters })
- const { data: rolesData } = useOrganizationRolesV2Query({ slug }, { enabled: showFilters })
+ const projects = useMemo(
+ () => projectsData?.pages.flatMap((page) => page.projects) ?? [],
+ [projectsData?.pages]
+ )
+
+ const { data: selectedOrganization, isLoading: isLoadingOrganizations } =
+ useSelectedOrganizationQuery({ enabled: showFilters })
+ const organizations = useMemo(
+ () => (selectedOrganization ? [selectedOrganization] : []),
+ [selectedOrganization]
+ )
+ const { data: members } = useOrganizationMembersQuery({ slug }, { enabled: showFilters })
const activeMembers = (members ?? []).filter((x) => !x.invited_at)
- const roles = [...(rolesData?.org_scoped_roles ?? []), ...(rolesData?.project_scoped_roles ?? [])]
- const projects =
- useMemo(() => projectsData?.pages.flatMap((page) => page.projects), [projectsData?.pages]) || []
- const logs = data?.result ?? []
- const sortedLogs = filterByProjects(
- filterByUsers(sortAuditLogs(logs, dateSortDesc), filters.users),
- filters.projects
+ const logs = useMemo(() => data?.result ?? [], [data?.result])
+ const filteredLogs = useMemo(
+ () => filterByProjects(filterByUsers(logs, filters.users), filters.projects),
+ [logs, filters.users, filters.projects]
+ )
+
+ const lastSelectedRowId = useRef<string | null>(null)
+ const columns = useMemo(
+ () =>
+ getAuditLogColumns({
+ projects,
+ organizations,
+ members,
+ lastSelectedRowId,
+ isLoadingProjects,
+ isLoadingOrganizations,
+ }),
+ [projects, organizations, members, isLoadingProjects, isLoadingOrganizations]
)
+ const [sorting, setSorting] = useState<SortingState>([{ id: 'date', desc: true }])
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const table = useReactTable({
+ data: filteredLogs,
+ columns,
+ state: { sorting, rowSelection },
+ enableMultiRowSelection: true,
+ getRowId: (row) => row.request_id,
+ onSortingChange: setSorting,
+ onRowSelectionChange: setRowSelection,
+ getCoreRowModel: getCoreRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ })
const shouldShowLoadingState =
(isLoading && fetchStatus !== 'idle') || isLoadingPermissions || isLoadingEntitlements
@@ -135,10 +173,15 @@ export const AuditLogs = () => {
enabled: !isLoading && !isRefetching && canReadAuditLogs,
})
+ useEffect(() => {
+ setRowSelection({})
+ lastSelectedRowId.current = null
+ }, [filters.users, filters.projects])
+
// This feature depends on the subscription tier of the user.
// The API limits the logs to maximum of 62 days and 5 minutes so when the page is
// viewed for more than 5 minutes, the call parameters needs to be updated. This also works with
- // higher tiers.The user will see a loading shimmer.
+ // higher tiers. The user will see a loading shimmer.
useEffect(() => {
const duration = dayjs(dateRange.from).diff(dayjs(dateRange.to))
const interval = setInterval(() => {
@@ -169,99 +212,102 @@ export const AuditLogs = () => {
}
return (
- <>
- <ScaffoldContainer className="px-6 xl:px-10">
- <ScaffoldSection isFullWidth>
- <div className="space-y-4 flex flex-col">
- {showFilters && (
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-2">
- <p className="text-xs prose">Filter by</p>
- <FilterPopover
- name="Users"
- options={activeMembers}
- labelKey="username"
- valueKey="gotrue_id"
- activeOptions={filters.users}
- onSaveFilters={(values) => setFilters({ ...filters, users: values })}
- />
- <FilterPopover
- name="Projects"
- options={projects}
- labelKey="name"
- valueKey="ref"
- activeOptions={filters.projects}
- onSaveFilters={(values) => setFilters({ ...filters, projects: values })}
- search={search}
- setSearch={setSearch}
- hasNextPage={hasNextPage}
- isLoading={isLoadingProjects}
- isFetching={isFetching}
- isFetchingNextPage={isFetchingNextPage}
- fetchNextPage={fetchNextPage}
- />
- <LogsDatePicker
- hideWarnings
- value={dateRange}
- onSubmit={(value) => setDateRange(value)}
- helpers={[
- {
- text: 'Last 1 hour',
- calcFrom: () => dayjs().subtract(1, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 3 hours',
- calcFrom: () => dayjs().subtract(3, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
-
- {
- text: 'Last 6 hours',
- calcFrom: () => dayjs().subtract(6, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 12 hours',
- calcFrom: () => dayjs().subtract(12, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 24 hours',
- calcFrom: () => dayjs().subtract(1, 'day').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- ]}
- />
- {isSuccess && (
- <>
- <div className="h-[20px] border-r border-strong ml-4! mr-2!" />
- <p className="prose text-xs">Viewing {sortedLogs.length} logs in total</p>
- </>
- )}
- </div>
- <Button
- disabled={isLoading || isRefetching}
- icon={<RefreshCw className={isRefetching ? 'animate-spin' : ''} />}
- onClick={() => refetch()}
- >
- {isRefetching ? 'Refreshing' : 'Refresh'}
- </Button>
+ <ScaffoldContainer size="full" className="px-0 h-full flex flex-col">
+ <ScaffoldSection isFullWidth className="pt-6! pb-0! flex-1 min-h-0">
+ <div className="space-y-4 flex flex-col h-full min-h-0">
+ {showFilters && (
+ <div
+ className={cn(
+ CONTENT_PADDING,
+ 'flex flex-col md:flex-row md:items-center justify-between'
+ )}
+ >
+ <div className="flex items-center space-x-2">
+ <p className="text-xs prose">Filter by</p>
+ <FilterPopover
+ name="Users"
+ options={activeMembers}
+ labelKey="username"
+ valueKey="gotrue_id"
+ activeOptions={filters.users}
+ onSaveFilters={(values) => setFilters({ ...filters, users: values })}
+ />
+ <FilterPopover
+ name="Projects"
+ options={projects}
+ labelKey="name"
+ valueKey="ref"
+ activeOptions={filters.projects}
+ onSaveFilters={(values) => setFilters({ ...filters, projects: values })}
+ search={search}
+ setSearch={setSearch}
+ hasNextPage={hasNextPage}
+ isLoading={isLoadingProjects}
+ isFetching={isFetchingProjects}
+ isFetchingNextPage={isFetchingNextPage}
+ fetchNextPage={fetchNextPage}
+ />
+ <LogsDatePicker
+ hideWarnings
+ value={dateRange}
+ onSubmit={(value) => setDateRange(value)}
+ helpers={[
+ {
+ text: 'Last 1 hour',
+ calcFrom: () => dayjs().subtract(1, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ {
+ text: 'Last 3 hours',
+ calcFrom: () => dayjs().subtract(3, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ {
+ text: 'Last 6 hours',
+ calcFrom: () => dayjs().subtract(6, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ {
+ text: 'Last 12 hours',
+ calcFrom: () => dayjs().subtract(12, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ {
+ text: 'Last 24 hours',
+ calcFrom: () => dayjs().subtract(1, 'day').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ ]}
+ />
</div>
- )}
+ <ButtonTooltip
+ disabled={isLoading}
+ loading={isLoading || isRefetching}
+ className="w-7"
+ icon={<RefreshCw />}
+ onClick={() => refetch()}
+ tooltip={{ content: { side: 'bottom', text: 'Refresh logs' } }}
+ />
+ </div>
+ )}
- {shouldShowLoadingState ? (
- <div className="space-y-2">
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- <ShimmeringLoader className="w-1/2" />
- </div>
- ) : !canReadAuditLogs ? (
+ {shouldShowLoadingState && (
+ <div className={cn(CONTENT_PADDING, 'space-y-2')}>
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ )}
+
+ {!shouldShowLoadingState && !canReadAuditLogs && (
+ <div className={CONTENT_PADDING}>
<NoPermission resourceText="view organization audit logs" />
- ) : null}
+ </div>
+ )}
- {isError &&
- (isRangeExceededError ? (
+ {isError && (
+ <div className={CONTENT_PADDING}>
+ {isRangeExceededError ? (
<Alert variant="destructive" title="Date range too large">
<WarningIcon />
<AlertTitle>Date range too large</AlertTitle>
@@ -272,170 +318,62 @@ export const AuditLogs = () => {
</Alert>
) : (
<AlertError error={error} subject="Failed to retrieve audit logs" />
- ))}
+ )}
+ </div>
+ )}
- {isSuccess && (
- <>
- {logs.length === 0 ? (
+ {isSuccess && (
+ <>
+ {logs.length === 0 ? (
+ <div className={CONTENT_PADDING}>
<div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">
<p className="prose text-sm">
Your organization does not have any audit logs available yet
</p>
</div>
- ) : logs.length > 0 && sortedLogs.length === 0 ? (
+ </div>
+ ) : logs.length > 0 && filteredLogs.length === 0 ? (
+ <div className={CONTENT_PADDING}>
<div className="bg-surface-100 border rounded-sm p-4 flex items-center justify-between">
<p className="prose text-sm">
No audit logs found based on the filters applied
</p>
</div>
- ) : (
- <Table
- head={[
- <Table.th key="user" className="py-2">
- User
- </Table.th>,
- <Table.th key="action" className="py-2">
- Action
- </Table.th>,
- <Table.th key="target" className="py-2">
- Target
- </Table.th>,
- <Table.th key="date" className="py-2">
- <div className="flex items-center space-x-2">
- <p>Date</p>
-
- <ButtonTooltip
- variant="text"
- className="px-1"
- icon={
- dateSortDesc ? (
- <ArrowDown strokeWidth={1.5} size={14} />
- ) : (
- <ArrowUp strokeWidth={1.5} size={14} />
- )
- }
- onClick={() => setDateSortDesc(!dateSortDesc)}
- tooltip={{
- content: {
- side: 'bottom',
- text: dateSortDesc ? 'Sort latest first' : 'Sort earliest first',
- },
- }}
- />
- </div>
- </Table.th>,
- <Table.th key="actions" className="py-2"></Table.th>,
- ]}
- body={
- sortedLogs?.map((log) => {
- const user = (members ?? []).find(
- (member) => member.gotrue_id === log.actor.user_id
- )
- const role = roles.find((role) => user?.role_ids?.[0] === role.id)
- const project = projects?.find((p) => p.ref === log.project_ref)
- const organization = organizations?.find(
- (org) => org.slug === log.organization_slug
- )
- const userIcon =
- user === undefined ? (
- <div className="flex h-[30px] w-[30px] items-center justify-center border-2 rounded-full border-strong">
- <p>?</p>
- </div>
- ) : user?.invited_id || user?.username === user?.primary_email ? (
- <div className="flex h-[30px] w-[30px] items-center justify-center border-2 rounded-full border-strong">
- <User size={18} strokeWidth={2} />
- </div>
- ) : (
- <Image
- alt={user?.username}
- src={`https://github.com/${user?.username ?? ''}.png?size=80`}
- width="30"
- height="30"
- className="border rounded-full"
- />
- )
-
- const actorDisplayName =
- user?.username ||
- log.actor.email ||
- formatPartnerIfExists(log.actor.partner, log.actor.partner_user_email) ||
- '-'
-
- return (
- <Table.tr
- key={log.request_id}
- onClick={() => setSelectedLog(log)}
- className="cursor-pointer hover:bg-alternative! transition duration-100"
- >
- <Table.td>
- <div className="flex items-center space-x-4">
- <div>{userIcon}</div>
- <div>
- <p className="text-foreground-light">{actorDisplayName}</p>
- {role && (
- <p className="mt-0.5 text-xs text-foreground-light">
- {role?.name}
- </p>
- )}
- </div>
- </div>
- </Table.td>
- <Table.td className="max-w-[250px]">
- <div className="flex items-center space-x-2">
- <p className="bg-surface-200 rounded-sm px-1 flex items-center justify-center text-xs font-mono border">
- {log.action.status}
- </p>
- <p className="text-foreground-light text-xs font-mono">
- {log.action.method}
- </p>
- <p className="truncate" title={log.action.name}>
- {log.action.name}
- </p>
- </div>
- </Table.td>
- <Table.td>
- {project || organization ? (
- <>
- <p
- className="text-foreground-light max-w-[230px] truncate"
- title={project?.name ?? organization?.name}
- >
- {project ? 'Project: ' : 'Organization: '}
- {project?.name ?? organization?.name}
- </p>
- <p className="text-foreground-light text-xs mt-0.5 truncate">
- {log.project_ref
- ? `Ref: ${log.project_ref}`
- : `Slug: ${log.organization_slug}`}
- </p>
- </>
- ) : (
- <p className="text-foreground-light text-sm">
- {log.project_ref ?? log.organization_slug ?? '-'}
- </p>
- )}
- </Table.td>
- <Table.td>
- {dayjs(log.timestamp / TIMESTAMP_MICROS_PER_MS).format(
- 'DD MMM YYYY, HH:mm:ss'
- )}
- </Table.td>
- <Table.td align="right">
- <Button>View details</Button>
- </Table.td>
- </Table.tr>
- )
- }) ?? []
- }
- />
- )}
- </>
- )}
- </div>
- </ScaffoldSection>
- </ScaffoldContainer>
-
- <LogDetailsPanel selectedLog={selectedLog} onClose={() => setSelectedLog(undefined)} />
- </>
+ </div>
+ ) : (
+ <div className="border-y overflow-hidden flex-1 min-h-0">
+ <ResizablePanelGroup orientation="horizontal" className="h-full">
+ <ResizablePanel
+ defaultSize={100}
+ minSize={30}
+ className="flex flex-col overflow-hidden"
+ >
+ <div className="grow relative overflow-hidden">
+ <AuditLogsSelectionHeader table={table} />
+ <AuditLogsTable
+ table={table}
+ selectedLog={selectedLog}
+ onSelectLog={(log) =>
+ setSelectedLog((prev) =>
+ prev?.request_id === log.request_id ? undefined : log
+ )
+ }
+ />
+ </div>
+ </ResizablePanel>
+ {selectedLog && (
+ <AuditLogDetailsPanel
+ selectedLog={selectedLog}
+ onClose={() => setSelectedLog(undefined)}
+ />
+ )}
+ </ResizablePanelGroup>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </ScaffoldSection>
+ </ScaffoldContainer>
)
}
diff --git a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts
index d69f65a85d3..2dbe7990b95 100644
--- a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts
+++ b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.utils.ts
@@ -3,22 +3,11 @@ import dayjs from 'dayjs'
import { DatePickerToFrom } from '@/components/interfaces/Settings/Logs/Logs.types'
import type { AuditLog } from '@/data/organizations/organization-audit-logs-query'
-export function sortAuditLogs(logs: AuditLog[], descending: boolean): AuditLog[] {
- return [...logs].sort((a, b) =>
- descending ? b.timestamp - a.timestamp : a.timestamp - b.timestamp
- )
-}
-
export function filterByUsers(logs: AuditLog[], userIds: string[]): AuditLog[] {
if (userIds.length === 0) return logs
return logs.filter((log) => userIds.includes(log.actor.user_id ?? ''))
}
-export function filterByProjects(logs: AuditLog[], projectRefs: string[]): AuditLog[] {
- if (projectRefs.length === 0) return logs
- return logs.filter((log) => projectRefs.includes(log.project_ref ?? ''))
-}
-
// [Joshen] Mainly to handle if a single date is selected - currently just for Audit Logs as
// i'm on the fence if this logic should be within the DatePicker component itself
// e.g for Logs.DatePicker which uses this component, the component itself has its own time selection UI
@@ -50,13 +39,3 @@ export const formatSelectedDateRange = (value: DatePickerToFrom) => {
return { from: from.utc().toISOString(), to: to.utc().toISOString() }
}
}
-
-export function formatPartnerIfExists(
- partner: string | undefined,
- partnerEmail: string | undefined
-) {
- if (!partner) return undefined
-
- const capitalized = `${partner[0].toUpperCase()}${partner.slice(1).toLowerCase()}`
- return partnerEmail ? `${partnerEmail} (${capitalized})` : capitalized
-}
diff --git a/apps/studio/data/organizations/organization-audit-logs-query.ts b/apps/studio/data/organizations/organization-audit-logs-query.ts
index e7b2ff688d4..367c971ca6a 100644
--- a/apps/studio/data/organizations/organization-audit-logs-query.ts
+++ b/apps/studio/data/organizations/organization-audit-logs-query.ts
@@ -1,4 +1,5 @@
import { useQuery } from '@tanstack/react-query'
+import { components } from 'api-types'
import { organizationKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
@@ -8,47 +9,15 @@ import type { ResponseError, UseCustomQueryOptions } from '@/types'
// Divide by this constant before passing to dayjs/Date to get a valid date.
export const TIMESTAMP_MICROS_PER_MS = 1000
-export type AuditLog = {
- organization_slug?: string
- project_ref?: string
- request_id: string
- action: {
- name: string
- method: string
- route: string
- status: number
- metadata?: Record<string, unknown>
- }
- actor: {
- token_type: string
- token_hash?: string
- user_id?: string
- email?: string
- oauth_app_id?: string
- oauth_app_name?: string
- app_id?: string
- app_name?: string
- ip?: string
- partner?: string
- partner_installation_id?: string
- partner_user_email?: string
- partner_user_id?: string
- }
- timestamp: number
-}
-
-export type OrganizationAuditLogsResponse = {
- result: AuditLog[]
- retention_period: number
-}
+export type AuditLog = components['schemas']['AuditLogsResponse_Output']['result'][number]
-export type OrganizationAuditLogsVariables = {
+type OrganizationAuditLogsVariables = {
slug?: string
iso_timestamp_start: string
iso_timestamp_end: string
}
-export async function getOrganizationAuditLogs(
+async function getOrganizationAuditLogs(
{ slug, iso_timestamp_start, iso_timestamp_end }: OrganizationAuditLogsVariables,
signal?: AbortSignal
) {
@@ -60,12 +29,11 @@ export async function getOrganizationAuditLogs(
})
if (error) handleError(error)
- // [Joshen] API doesn't generate types for each audit log properly
- return data as unknown as OrganizationAuditLogsResponse
+ return data
}
-export type OrganizationAuditLogsData = Awaited<ReturnType<typeof getOrganizationAuditLogs>>
-export type OrganizationAuditLogsError = ResponseError
+type OrganizationAuditLogsData = Awaited<ReturnType<typeof getOrganizationAuditLogs>>
+type OrganizationAuditLogsError = ResponseError
export const useOrganizationAuditLogsQuery = <TData = OrganizationAuditLogsData>(
vars: OrganizationAuditLogsVariables,
diff --git a/apps/studio/data/projects/org-projects-infinite-query.ts b/apps/studio/data/projects/org-projects-infinite-query.ts
index 5fbcd870f3e..4e15316638b 100644
--- a/apps/studio/data/projects/org-projects-infinite-query.ts
+++ b/apps/studio/data/projects/org-projects-infinite-query.ts
@@ -85,9 +85,9 @@ export const useOrgProjectsInfiniteQuery = <TData = OrgProjectsInfiniteData>(
getNextPageParam(lastPage, pages) {
const page = pages.length
const currentTotalCount = page * limit
- const totalCount = lastPage.pagination.count
+ const totalCount = lastPage.pagination?.count
- if (currentTotalCount >= totalCount) return undefined
+ if (totalCount === undefined || currentTotalCount >= totalCount) return undefined
return page
},
...options,
diff --git a/apps/studio/pages/account/audit.tsx b/apps/studio/pages/account/audit.tsx
index f43e799d2f5..f735a310827 100644
--- a/apps/studio/pages/account/audit.tsx
+++ b/apps/studio/pages/account/audit.tsx
@@ -6,7 +6,7 @@ import {
PageHeaderTitle,
} from 'ui-patterns/PageHeader'
-import { AuditLogs } from '@/components/interfaces/Account/AuditLogs/AuditLogs'
+import { AuditLogs } from '@/components/interfaces/Account/AuditLogs'
import AccountLayout from '@/components/layouts/AccountLayout/AccountLayout'
import { AppLayout } from '@/components/layouts/AppLayout/AppLayout'
import { DefaultLayout } from '@/components/layouts/DefaultLayout'
diff --git a/apps/studio/pages/org/[slug]/audit.tsx b/apps/studio/pages/org/[slug]/audit.tsx
index 72b19a1afc5..228c00a2408 100644
--- a/apps/studio/pages/org/[slug]/audit.tsx
+++ b/apps/studio/pages/org/[slug]/audit.tsx
@@ -21,7 +21,7 @@ const OrgAuditLogs: NextPageWithLayout = () => {
return (
<>
- <PageHeader size="default">
+ <PageHeader size="full">
<PageHeaderMeta>
<PageHeaderSummary>
<PageHeaderTitle>Audit Logs</PageHeaderTitle>
diff --git a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
index b68bb5c1b01..738c9426743 100644
--- a/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
+++ b/apps/studio/tests/components/AuditLogs/AuditLogs.utils.test.ts
@@ -1,11 +1,8 @@
import dayjs from 'dayjs'
import { describe, expect, test } from 'vitest'
-import {
- filterByProjects,
- filterByUsers,
- sortAuditLogs,
-} from '@/components/interfaces/Organization/AuditLogs/AuditLogs.utils'
+import { filterByProjects } from '@/components/interfaces/AuditLogs/AuditLogs.utils'
+import { filterByUsers } from '@/components/interfaces/Organization/AuditLogs/AuditLogs.utils'
import {
TIMESTAMP_MICROS_PER_MS,
type AuditLog,
@@ -55,32 +52,6 @@ describe('timestamp conversion (microseconds → milliseconds)', () => {
})
})
-describe('sortAuditLogs', () => {
- test('sorts descending (newest first)', () => {
- const result = sortAuditLogs([logA, logC, logB], true)
- expect(result.map((l) => l.request_id)).toEqual(['req-c', 'req-b', 'req-a'])
- })
-
- test('sorts ascending (oldest first)', () => {
- const result = sortAuditLogs([logC, logA, logB], false)
- expect(result.map((l) => l.request_id)).toEqual(['req-a', 'req-b', 'req-c'])
- })
-
- test('does not mutate the input array', () => {
- const input = [logC, logA]
- sortAuditLogs(input, true)
- expect(input[0].request_id).toBe('req-c')
- })
-
- test('returns empty array unchanged', () => {
- expect(sortAuditLogs([], true)).toEqual([])
- })
-
- test('handles a single log', () => {
- expect(sortAuditLogs([logA], true)).toEqual([logA])
- })
-})
-
describe('filterByUsers', () => {
test('returns all logs when filter list is empty', () => {
expect(filterByUsers([logA, logB, logC], [])).toEqual([logA, logB, logC])
diff --git a/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts b/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts
index ca3820398e2..86b1a30f501 100644
--- a/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts
+++ b/apps/studio/tests/components/AuditLogs/OrgAuditLogs.utils.test.ts
@@ -1,10 +1,7 @@
import dayjs from 'dayjs'
import { afterEach, describe, expect, test, vi } from 'vitest'
-import {
- formatPartnerIfExists,
- formatSelectedDateRange,
-} from '@/components/interfaces/Organization/AuditLogs/AuditLogs.utils'
+import { formatSelectedDateRange } from '@/components/interfaces/Organization/AuditLogs/AuditLogs.utils'
// Pin "now" to a fixed point so date comparisons are deterministic
const NOW = dayjs('2024-06-15T14:30:00')
@@ -84,25 +81,3 @@ describe('formatSelectedDateRange', () => {
expect(result.to).toMatch(/Z$/)
})
})
-
-describe('formatPartnerIfExists', () => {
- test('capitalizes the partner name', () => {
- expect(formatPartnerIfExists('github', undefined)).toBe('Github')
- })
-
- test('prefixes with the partner email when provided', () => {
- expect(formatPartnerIfExists('github', '[email protected]')).toBe('[email protected] (Github)')
- })
-
- test('normalizes casing regardless of input case', () => {
- expect(formatPartnerIfExists('GITHUB', undefined)).toBe('Github')
- })
-
- test('returns undefined when partner is undefined', () => {
- expect(formatPartnerIfExists(undefined, '[email protected]')).toBeUndefined()
- })
-
- test('returns undefined when partner is an empty string', () => {
- expect(formatPartnerIfExists('', '[email protected]')).toBeUndefined()
- })
-})