Skip to content

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

Implement audit logs

Joshen Lim52c71256c585
diff --git a/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx b/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
new file mode 100644
index 00000000000..ecb23296b69
--- /dev/null
+++ b/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
@@ -0,0 +1,148 @@
+import dayjs from 'dayjs'
+import Image from 'next/image'
+import { useState } from 'react'
+
+import { useParams } from 'common'
+import Table from 'components/to-be-cleaned/Table'
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+import {
+ OrganizationAuditLog,
+ useOrganizationAuditLogsQuery,
+} from 'data/organizations/organization-audit-logs-query'
+import { useOrganizationDetailQuery } from 'data/organizations/organization-detail-query'
+import { useOrganizationRolesQuery } from 'data/organizations/organization-roles-query'
+import { useOrganizationsQuery } from 'data/organizations/organizations-query'
+import { useProjectsQuery } from 'data/projects/projects-query'
+import { IconSearch, IconUser, Input } from 'ui'
+import LogDetailsPanel from './LogDetailsPanel'
+
+// [Joshen considerations]
+// - Maybe fix the height of the table to the remaining height of the viewport, so that the search input is always visible
+
+const AuditLogs = () => {
+ const { slug } = useParams()
+ const currentTime = dayjs()
+ const [selectedLog, setSelectedLog] = useState<OrganizationAuditLog>()
+
+ const { data: projects } = useProjectsQuery()
+ const { data: organizations } = useOrganizationsQuery()
+ const { data: detailData } = useOrganizationDetailQuery({ slug })
+ const { data: rolesData } = useOrganizationRolesQuery({ slug })
+ const {
+ data: logs,
+ isLoading,
+ isSuccess,
+ isError,
+ } = useOrganizationAuditLogsQuery({
+ slug,
+ iso_timestamp_start: currentTime.subtract(1, 'day').toISOString(),
+ iso_timestamp_end: currentTime.toISOString(),
+ })
+
+ const members = detailData?.members ?? []
+ const roles = rolesData?.roles ?? []
+ const sortedLogs = logs?.sort(
+ (a, b) => Number(new Date(b.timestamp)) - Number(new Date(a.timestamp))
+ )
+
+ return (
+ <>
+ <div className="space-y-4 flex flex-col">
+ {isLoading && (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ )}
+
+ {isSuccess && (
+ <>
+ <div className="flex items-center">
+ <Input
+ size="tiny"
+ className="w-80"
+ icon={<IconSearch size={14} strokeWidth={1.5} />}
+ placeholder="Search audit logs"
+ />
+ </div>
+ <Table
+ head={[
+ <Table.th key="user">User</Table.th>,
+ <Table.th key="action">Action</Table.th>,
+ <Table.th key="target">Target</Table.th>,
+ <Table.th key="date">Date</Table.th>,
+ ]}
+ body={
+ sortedLogs?.map((log) => {
+ const user = members.find((member) => member.gotrue_id === log.actor.id)
+ const role = roles.find((role) => user?.role_ids?.[0] === role.id)
+ const project = projects?.find(
+ (project) => project.ref === log.permission_group.project_ref
+ )
+ const organization = organizations?.find(
+ (org) => org.slug === log.permission_group.org_slug
+ )
+
+ const userIcon =
+ user?.invited_id || user?.username === user?.primary_email ? (
+ <div className="flex p-2 border-2 rounded-full border-scale-700">
+ <IconUser size={20} strokeWidth={2} />
+ </div>
+ ) : (
+ <Image
+ alt={user?.username}
+ src={`https://github.com/${user?.username ?? ''}.png?size=80`}
+ width="40"
+ height="40"
+ className="border rounded-full"
+ />
+ )
+
+ return (
+ <Table.tr
+ key={log.timestamp}
+ onClick={() => setSelectedLog(log)}
+ className="cursor-pointer hover:!bg-scale-100 transition duration-100"
+ >
+ <Table.td>
+ <div className="flex items-center space-x-4">
+ {userIcon}
+ <div>
+ <p className="text-scale-1100">{user?.username ?? log.actor.id}</p>
+ <p className="mt-0.5 text-xs text-scale-1000">{role?.name}</p>
+ </div>
+ </div>
+ </Table.td>
+ <Table.td>
+ <div className="flex items-center space-x-2">
+ <p className="bg-scale-400 rounded px-1 flex items-center justify-center text-xs font-mono border">
+ {log.action.metadata[0].status}
+ </p>
+ <p className="max-w-[200px] truncate">{log.action.name}</p>
+ </div>
+ </Table.td>
+ <Table.td>
+ <p className="text-scale-1100">
+ {project?.name ?? organization?.name ?? 'Entity no longer exists'}
+ </p>
+ <p className="text-scale-1000 text-xs mt-0.5">
+ {log.permission_group.org_slug ?? log.permission_group.project_ref}
+ </p>
+ </Table.td>
+ <Table.td>{dayjs(log.timestamp).format('DD MMM YYYY, HH:mm:ss')}</Table.td>
+ </Table.tr>
+ )
+ }) ?? []
+ }
+ />
+ </>
+ )}
+ </div>
+
+ <LogDetailsPanel selectedLog={selectedLog} onClose={() => setSelectedLog(undefined)} />
+ </>
+ )
+}
+
+export default AuditLogs
diff --git a/studio/components/interfaces/Organization/AuditLogs/LogDetailsPanel.tsx b/studio/components/interfaces/Organization/AuditLogs/LogDetailsPanel.tsx
new file mode 100644
index 00000000000..34bbf7f9c35
--- /dev/null
+++ b/studio/components/interfaces/Organization/AuditLogs/LogDetailsPanel.tsx
@@ -0,0 +1,96 @@
+import { useParams } from 'common'
+import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms'
+import { OrganizationAuditLog } from 'data/organizations/organization-audit-logs-query'
+import { useOrganizationDetailQuery } from 'data/organizations/organization-detail-query'
+import dayjs from 'dayjs'
+import { Button, Input, SidePanel } from 'ui'
+
+export interface LogDetailsPanelProps {
+ selectedLog?: OrganizationAuditLog
+ onClose: () => void
+}
+
+const LogDetailsPanel = ({ selectedLog, onClose }: LogDetailsPanelProps) => {
+ console.log({ selectedLog })
+
+ return (
+ <SidePanel
+ size="large"
+ header={`"${selectedLog?.action.name}" on ${dayjs(selectedLog?.timestamp).format(
+ 'DD MMM YYYY, HH:mm:ss'
+ )}`}
+ visible={selectedLog !== undefined}
+ onCancel={onClose}
+ cancelText="Close"
+ >
+ <FormSection header={<FormSectionLabel>General</FormSectionLabel>}>
+ <FormSectionContent loading={false}>
+ <Input
+ readOnly
+ size="small"
+ label="Description"
+ value={selectedLog?.target.description}
+ />
+ <Input
+ readOnly
+ size="small"
+ label="Timestamp"
+ value={selectedLog?.timestamp}
+ descriptionText={dayjs(selectedLog?.timestamp).format('DD MMM YYYY, HH:mm:ss (ZZ)')}
+ />
+ </FormSectionContent>
+ </FormSection>
+
+ <SidePanel.Separator />
+
+ <FormSection header={<FormSectionLabel>Actor</FormSectionLabel>}>
+ <FormSectionContent loading={false}>
+ <Input readOnly size="small" label="Actor ID" value={selectedLog?.actor.id} />
+ <Input.TextArea
+ readOnly
+ size="small"
+ label="Metadata"
+ value={JSON.stringify(selectedLog?.actor.metadata)}
+ />
+ </FormSectionContent>
+ </FormSection>
+
+ <SidePanel.Separator />
+
+ <FormSection header={<FormSectionLabel>Action</FormSectionLabel>}>
+ <FormSectionContent loading={false}>
+ <Input readOnly size="small" label="Name" value={selectedLog?.action.name} />
+ <Input.TextArea
+ readOnly
+ size="small"
+ label="Metadata"
+ value={JSON.stringify(selectedLog?.action.metadata)}
+ />
+ </FormSectionContent>
+ </FormSection>
+
+ <SidePanel.Separator />
+
+ <FormSection header={<FormSectionLabel>Permission Group</FormSectionLabel>}>
+ <FormSectionContent loading={false}>
+ <Input
+ readOnly
+ size="small"
+ label="Organization slug"
+ disabled={(selectedLog?.permission_group.org_slug ?? '').length === 0}
+ value={selectedLog?.permission_group.org_slug ?? 'None'}
+ />
+ <Input
+ readOnly
+ size="small"
+ label="Project reference"
+ disabled={(selectedLog?.permission_group.project_ref ?? '').length === 0}
+ value={selectedLog?.permission_group.project_ref ?? 'None'}
+ />
+ </FormSectionContent>
+ </FormSection>
+ </SidePanel>
+ )
+}
+
+export default LogDetailsPanel
diff --git a/studio/components/interfaces/Organization/index.ts b/studio/components/interfaces/Organization/index.ts
index beee07cbc43..78b4f8f97bc 100644
--- a/studio/components/interfaces/Organization/index.ts
+++ b/studio/components/interfaces/Organization/index.ts
@@ -3,5 +3,6 @@ import TeamSettings from './TeamSettings/TeamSettings'
import BillingSettings from './BillingSettings/BillingSettings'
import InvoicesSettings from './InvoicesSettings/InvoicesSettings'
import NewOrgForm from './NewOrg/NewOrgForm'
+import AuditLogs from './AuditLogs/AuditLogs'
-export { GeneralSettings, TeamSettings, BillingSettings, InvoicesSettings, NewOrgForm }
+export { GeneralSettings, TeamSettings, BillingSettings, InvoicesSettings, NewOrgForm, AuditLogs }
diff --git a/studio/components/ui/AlertError.tsx b/studio/components/ui/AlertError.tsx
new file mode 100644
index 00000000000..04294793831
--- /dev/null
+++ b/studio/components/ui/AlertError.tsx
@@ -0,0 +1,38 @@
+import Link from 'next/link'
+import { Alert, Button } from 'ui'
+
+export interface AlertErrorProps {
+ ref?: string
+ subject?: string
+}
+
+// [Joshen] To standardize the language for all error UIs
+
+const AlertError = ({ ref, subject }: AlertErrorProps) => {
+ const subjectString = subject?.replace(/ /g, '%20')
+ let href = `/support/new?category=dashboard_bug`
+
+ if (ref) href += `&ref=${ref}`
+ if (subjectString) href += `&subject=${subjectString}`
+
+ return (
+ <Alert
+ withIcon
+ variant="warning"
+ title="Failed to retrieve upcoming invoice details"
+ actions={[
+ <Link key="contact-support" href={href}>
+ <a>
+ <Button type="default" className="ml-4">
+ Contact support
+ </Button>
+ </a>
+ </Link>,
+ ]}
+ >
+ Try refreshing your browser, but if the issue persists, please reach out to us via support.
+ </Alert>
+ )
+}
+
+export default AlertError
diff --git a/studio/data/organizations/keys.ts b/studio/data/organizations/keys.ts
index 72e646037bb..71baa33c8f9 100644
--- a/studio/data/organizations/keys.ts
+++ b/studio/data/organizations/keys.ts
@@ -7,4 +7,5 @@ export const organizationKeys = {
['organizations', slug, 'free-project-limit-check'] as const,
customerProfile: (slug: string | undefined) =>
['organizations', slug, 'customer-profile'] as const,
+ auditLogs: (slug: string | undefined) => ['organizations', slug, 'audit-logs'] as const,
}
diff --git a/studio/data/organizations/organization-audit-logs-query.ts b/studio/data/organizations/organization-audit-logs-query.ts
new file mode 100644
index 00000000000..49f1cc6e707
--- /dev/null
+++ b/studio/data/organizations/organization-audit-logs-query.ts
@@ -0,0 +1,85 @@
+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { useCallback } from 'react'
+import { organizationKeys } from './keys'
+
+export type OrganizationAuditLog = {
+ action: {
+ metadata: {
+ method: string
+ status: number
+ }[]
+ name: string
+ }
+ actor: {
+ id: string
+ type: 'user' | string
+ metadata: {
+ email: string
+ }[]
+ }
+ permission_group: {
+ org_slug: string
+ project_ref: string | null
+ }
+ target: {
+ description: string
+ }
+ timestamp: string
+}
+
+export type OrganizationAuditLogsVariables = {
+ slug?: string
+ iso_timestamp_start?: string
+ iso_timestamp_end?: string
+ project_refs?: string // Comma-separated
+}
+
+export async function getOrganizationAuditLogs(
+ { slug, iso_timestamp_start, iso_timestamp_end, project_refs }: OrganizationAuditLogsVariables,
+ signal?: AbortSignal
+) {
+ if (!slug) throw new Error('slug is required')
+
+ const response = await get(
+ `${API_URL}/organizations/${slug}/audit?iso_timestamp_start=${iso_timestamp_start}&iso_timestamp_end=${iso_timestamp_end}`,
+ { signal }
+ )
+ if (response.error) throw response.error
+ return response.result as OrganizationAuditLog[]
+}
+
+export type OrganizationAuditLogsData = Awaited<ReturnType<typeof getOrganizationAuditLogs>>
+export type OrganizationAuditLogsError = unknown
+
+export const useOrganizationAuditLogsQuery = <TData = OrganizationAuditLogsData>(
+ vars: OrganizationAuditLogsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<OrganizationAuditLogsData, OrganizationAuditLogsError, TData> = {}
+) => {
+ const { slug } = vars
+ return useQuery<OrganizationAuditLogsData, OrganizationAuditLogsError, TData>(
+ organizationKeys.auditLogs(slug),
+ ({ signal }) => getOrganizationAuditLogs(vars, signal),
+ {
+ enabled: enabled && typeof slug !== 'undefined',
+ ...options,
+ }
+ )
+}
+
+export const useOrganizationAuditLogsPrefetch = (vars: OrganizationAuditLogsVariables) => {
+ const { slug } = vars
+ const client = useQueryClient()
+
+ return useCallback(() => {
+ if (slug) {
+ client.prefetchQuery(organizationKeys.auditLogs(slug), ({ signal }) =>
+ getOrganizationAuditLogs(vars, signal)
+ )
+ }
+ }, [client, slug, vars])
+}
diff --git a/studio/pages/org/[slug]/audit.tsx b/studio/pages/org/[slug]/audit.tsx
new file mode 100644
index 00000000000..c16e6ca7cf6
--- /dev/null
+++ b/studio/pages/org/[slug]/audit.tsx
@@ -0,0 +1,57 @@
+import { useRouter } from 'next/router'
+import { observer } from 'mobx-react-lite'
+import { Tabs } from 'ui'
+
+import { NextPageWithLayout } from 'types'
+import { useStore } from 'hooks'
+import { useParams } from 'common/hooks'
+import Loading from 'components/ui/Loading'
+import { OrganizationLayout } from 'components/layouts'
+import { AuditLogs } from 'components/interfaces/Organization'
+
+const OrgAuditLogs: NextPageWithLayout = () => {
+ const { ui } = useStore()
+ const { slug } = useParams()
+ const router = useRouter()
+
+ return (
+ <>
+ {ui.selectedOrganization === undefined && (ui?.permissions ?? []).length === 0 ? (
+ <Loading />
+ ) : (
+ <div className="p-4 pt-0">
+ <div className="space-y-3">
+ <section className="mt-4">
+ <h1 className="text-3xl">
+ {ui.selectedOrganization?.name ?? 'Organization'} settings
+ </h1>
+ </section>
+ <nav>
+ <Tabs
+ size="small"
+ type="underlined"
+ activeId="audit"
+ onChange={(id: any) => {
+ if (id !== 'audit') router.push(`/org/${slug}/${id}`)
+ }}
+ >
+ <Tabs.Panel id="general" label="General" />
+ <Tabs.Panel id="team" label="Team" />
+ <Tabs.Panel id="billing" label="Billing" />
+ <Tabs.Panel id="invoices" label="Invoices" />
+ <Tabs.Panel id="audit" label="Audit Logs" />
+ </Tabs>
+ </nav>
+ </div>
+
+ <div className="mb-8">
+ <AuditLogs />
+ </div>
+ </div>
+ )}
+ </>
+ )
+}
+
+OrgAuditLogs.getLayout = (page) => <OrganizationLayout>{page}</OrganizationLayout>
+export default observer(OrgAuditLogs)