The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Add profile audit logs page.
Ivan Vasilov24820c5f3fc0
diff --git a/studio/components/interfaces/Account/AuditLogs/AuditLogs.tsx b/studio/components/interfaces/Account/AuditLogs/AuditLogs.tsxnew file mode 100644index 00000000000..58875a395ce--- /dev/null+++ b/studio/components/interfaces/Account/AuditLogs/AuditLogs.tsx@@ -0,0 +1,343 @@+import * as Tooltip from '@radix-ui/react-tooltip'+import dayjs from 'dayjs'+import Image from 'next/image'+import { useState } from 'react'++import { useParams } from 'common'+import { ScaffoldContainerLegacy } from 'components/layouts/Scaffold'+import Table from 'components/to-be-cleaned/Table'+import AlertError from 'components/ui/AlertError'+import { DatePicker } from 'components/ui/DatePicker'+import ShimmeringLoader from 'components/ui/ShimmeringLoader'+import { OrganizationAuditLog } 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 { useProfileAuditLogsQuery } from 'data/profile/profile-audit-logs-query'+import { useProjectsQuery } from 'data/projects/projects-query'+import { Alert, Button, IconArrowDown, IconArrowUp, IconRefreshCw, IconUser } from 'ui'+import FilterPopover from './FilterPopover'+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+// - 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++const AuditLogs = () => {+ const { slug } = useParams()+ const currentTime = dayjs().utc().set('millisecond', 0)+ const [dateSortDesc, setDateSortDesc] = useState(true)+ const [dateRange, setDateRange] = useState({+ from: currentTime.subtract(1, 'day').toISOString(),+ to: currentTime.toISOString(),+ })+ const [selectedLog, setSelectedLog] = useState<OrganizationAuditLog>()+ const [filters, setFilters] = useState<{ users: string[]; projects: string[] }>({+ users: [], // gotrue_id[]+ projects: [], // project_ref[]+ })++ const { data: projects } = useProjectsQuery()+ const { data: organizations } = useOrganizationsQuery()+ const { data: detailData } = useOrganizationDetailQuery({ slug })+ const { data: rolesData } = useOrganizationRolesQuery({ slug })+ const { data, error, isLoading, isSuccess, isError, isRefetching, refetch } =+ useProfileAuditLogsQuery({+ iso_timestamp_start: dateRange.from,+ iso_timestamp_end: dateRange.to,+ })++ const members = detailData?.members ?? []+ const roles = rolesData?.roles ?? []++ const retentionPeriod = data?.retention_period ?? 0+ const logs = data?.result ?? []+ const sortedLogs = logs+ ?.sort((a, b) =>+ dateSortDesc+ ? Number(new Date(b.occurred_at)) - Number(new Date(a.occurred_at))+ : Number(new Date(a.occurred_at)) - Number(new Date(b.occurred_at))+ )+ ?.filter((log) => {+ if (filters.users.length > 0) {+ return filters.users.includes(log.actor.id)+ } else {+ return log+ }+ })+ ?.filter((log) => {+ if (filters.projects.length > 0) {+ return filters.projects.includes(log.target.metadata.project_ref || '')+ } else {+ return log+ }+ })++ return (+ <>+ <ScaffoldContainerLegacy>+ <div className="space-y-4 flex flex-col">+ <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={members ?? []}+ 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 })}+ />+ <DatePicker+ hideTime+ hideClear+ triggerButtonType="dashed"+ triggerButtonTitle=""+ from={dateRange.from}+ to={dateRange.to}+ minDate={dayjs().subtract(retentionPeriod, 'days').toDate()}+ maxDate={dayjs().toDate()}+ onChange={(value) => {+ if (value.from !== null && value.to !== null) {+ const current = dayjs().utc()+ const from = dayjs(value.from)+ .utc()+ .hour(current.hour())+ .minute(current.minute())+ .second(current.second())+ .toISOString()+ const to = dayjs(value.to)+ .utc()+ .hour(current.hour())+ .minute(current.minute())+ .second(current.second())+ .toISOString()+ setDateRange({ from, to })+ }+ }}+ renderFooter={() => {+ return (+ <Alert title="" variant="info" className="mx-3 pl-2 pr-2 pt-1 pb-2">+ Your organization has a log retention period of{' '}+ <span className="text-brand">+ {retentionPeriod} day+ {retentionPeriod > 1 ? 's' : ''}+ </span>+ . You may only view logs from{' '}+ {dayjs().subtract(retentionPeriod, 'days').format('DD MMM YYYY')} as the+ earliest date.+ </Alert>+ )+ }}+ />+ {isSuccess && (+ <>+ <div className="h-[20px] border-r border-scale-700 !ml-4 !mr-2" />+ <p className="prose text-xs">Viewing {sortedLogs.length} logs in total</p>+ </>+ )}+ </div>+ <Button+ type="default"+ disabled={isLoading || isRefetching}+ icon={<IconRefreshCw className={isRefetching ? 'animate-spin' : ''} />}+ onClick={() => refetch()}+ >+ {isRefetching ? 'Refreshing' : 'Refresh'}+ </Button>+ </div>++ {isLoading && (+ <div className="space-y-2">+ <ShimmeringLoader />+ <ShimmeringLoader className="w-3/4" />+ <ShimmeringLoader className="w-1/2" />+ </div>+ )}++ {isError && <AlertError error={error} subject="Failed to retrieve audit logs" />}++ {isSuccess && (+ <>+ {logs.length === 0 ? (+ <div className="bg-scale-100 dark:bg-scale-300 border rounded 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 className="bg-scale-100 dark:bg-scale-300 border rounded 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>++ <Tooltip.Root delayDuration={0}>+ <Tooltip.Trigger>+ <Button+ type="text"+ className="px-1"+ icon={+ dateSortDesc ? (+ <IconArrowDown strokeWidth={1.5} size={14} />+ ) : (+ <IconArrowUp strokeWidth={1.5} size={14} />+ )+ }+ onClick={() => setDateSortDesc(!dateSortDesc)}+ />+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Portal>+ <Tooltip.Content side="right">+ <Tooltip.Arrow className="radix-tooltip-arrow" />+ <div+ className={[+ 'rounded bg-scale-100 py-1 px-2 leading-none shadow',+ 'border border-scale-200',+ ].join(' ')}+ >+ <span className="text-xs text-scale-1200">+ {dateSortDesc ? 'Sort latest first' : 'Sort earliest first'}+ </span>+ </div>+ </Tooltip.Content>+ </Tooltip.Portal>+ </Tooltip.Portal>+ </Tooltip.Root>+ </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.id)+ const role = roles.find((role) => user?.role_ids?.[0] === role.id)+ const project = projects?.find(+ (project) => project.ref === log.target.metadata.project_ref+ )+ const organization = organizations?.find(+ (org) => org.slug === log.target.metadata.org_slug+ )++ const hasStatusCode = log.action.metadata[0]?.status !== undefined+ const userIcon =+ user === undefined ? (+ <div className="flex h-[30px] w-[30px] flex items-center justify-center border-2 rounded-full border-scale-700">+ <p>?</p>+ </div>+ ) : user?.invited_id || user?.username === user?.primary_email ? (+ <div className="flex h-[30px] w-[30px] flex items-center justify-center border-2 rounded-full border-scale-700">+ <IconUser 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"+ />+ )++ return (+ <Table.tr+ key={log.occurred_at}+ onClick={() => setSelectedLog(log)}+ className="cursor-pointer hover:!bg-scale-100 transition duration-100"+ >+ <Table.td>+ <div className="flex items-center space-x-4">+ <div>{userIcon}</div>+ <div>+ <p className="text-scale-1100">{user?.username ?? 'Unknown'}</p>+ {role && (+ <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">+ {hasStatusCode && (+ <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-[170px] truncate" title={log.action.name}>+ {log.action.name}+ </p>+ </div>+ </Table.td>+ <Table.td>+ <p+ className="text-scale-1100 max-w-[230px] truncate"+ title={project?.name ?? organization?.name ?? 'Unknown'}+ >+ {project?.name+ ? 'Project: '+ : organization?.name+ ? 'Organization: '+ : null}+ {project?.name ?? organization?.name ?? 'Unknown'}+ </p>+ <p+ className="text-scale-1000 text-xs mt-0.5 truncate"+ title={+ log.target.metadata.project_ref ?? log.target.metadata.org_slug+ }+ >+ {log.target.metadata.project_ref+ ? 'Ref: '+ : log.target.metadata.org_slug+ ? 'Slug: '+ : null}+ {log.target.metadata.project_ref ?? log.target.metadata.org_slug}+ </p>+ </Table.td>+ <Table.td>+ {dayjs(log.occurred_at).format('DD MMM YYYY, HH:mm:ss')}+ </Table.td>+ <Table.td align="right">+ <Button type="default">View details</Button>+ </Table.td>+ </Table.tr>+ )+ }) ?? []+ }+ />+ )}+ </>+ )}+ </div>+ </ScaffoldContainerLegacy>++ <LogDetailsPanel selectedLog={selectedLog} onClose={() => setSelectedLog(undefined)} />+ </>+ )+}++export default AuditLogsdiff --git a/studio/components/interfaces/Account/AuditLogs/FilterPopover.tsx b/studio/components/interfaces/Account/AuditLogs/FilterPopover.tsxnew file mode 100644index 00000000000..c38c96736e3--- /dev/null+++ b/studio/components/interfaces/Account/AuditLogs/FilterPopover.tsx@@ -0,0 +1,100 @@+import { useState } from 'react'+import { Button, Checkbox, Popover } from 'ui'++interface FilterPopoverProps {+ options: any[]+ activeOptions: any[]+ valueKey: string+ labelKey: string+ name: string+ onSaveFilters: (options: string[]) => void+}++// [Joshen] Form + Checkbox.Group doesn't seem to work properly RE form state+// hence why the manual implementation here as a workaround++const FilterPopover = ({+ options = [],+ activeOptions = [],+ valueKey,+ labelKey,+ name,+ onSaveFilters,+}: FilterPopoverProps) => {+ const [open, setOpen] = useState(false)+ const [selectedOptions, setSelectedOptions] = useState<string[]>([])++ const formattedOptions = activeOptions.map((option) => {+ const base = options.find((x) => x[valueKey] === option)+ return base[labelKey]+ })++ return (+ <Popover+ side="bottom"+ align="start"+ open={open}+ onOpenChange={() => setOpen(!open)}+ header={<div className="prose text-xs">Select {name.toLowerCase()}</div>}+ overlay={+ <>+ <div className="space-y-4 px-3 py-3 min-w-[170px]">+ <Checkbox.Group+ id="projects"+ onChange={(event) => {+ const value = event.target.value+ if (selectedOptions.includes(value)) {+ setSelectedOptions(selectedOptions.filter((x) => x !== value))+ } else {+ setSelectedOptions(selectedOptions.concat(value))+ }+ }}+ options={options.map((option) => {+ return {+ value: option[valueKey],+ label: option[labelKey],+ defaultChecked: activeOptions.includes(option[valueKey]),+ }+ })}+ ></Checkbox.Group>+ </div>+ <div className="flex items-center justify-end gap-2 border-t border-scale-400 bg-scale-200 py-2 px-3 dark:border-scale-500 dark:bg-scale-400 ">+ <Button+ size="tiny"+ type="default"+ onClick={() => {+ onSaveFilters([])+ setOpen(false)+ }}+ >+ Clear+ </Button>+ <Button+ type="primary"+ onClick={() => {+ onSaveFilters(selectedOptions)+ setOpen(false)+ }}+ >+ Save+ </Button>+ </div>+ </>+ }+ >+ <Button type={activeOptions.length > 0 ? 'default' : 'dashed'} onClick={() => setOpen(false)}>+ <span>{name}</span>+ {activeOptions.length > 0 && <span className="mr-1">:</span>}+ {activeOptions.length >= 3 ? (+ <span>+ {formattedOptions[0]} and {activeOptions.length - 1} others+ </span>+ ) : activeOptions.length > 0 ? (+ <span>{formattedOptions.join(', ')}</span>+ ) : null}+ </Button>+ </Popover>+ )+}++export default FilterPopoverdiff --git a/studio/components/interfaces/Account/AuditLogs/LogDetailsPanel.tsx b/studio/components/interfaces/Account/AuditLogs/LogDetailsPanel.tsxnew file mode 100644index 00000000000..0f374319b15--- /dev/null+++ b/studio/components/interfaces/Account/AuditLogs/LogDetailsPanel.tsx@@ -0,0 +1,97 @@+import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms'+import { OrganizationAuditLog } from 'data/organizations/organization-audit-logs-query'+import { useOrganizationsQuery } from 'data/organizations/organizations-query'+import { useProjectsQuery } from 'data/projects/projects-query'+import dayjs from 'dayjs'+import { Input, SidePanel } from 'ui'++export interface LogDetailsPanelProps {+ selectedLog?: OrganizationAuditLog+ onClose: () => void+}++const LogDetailsPanel = ({ selectedLog, onClose }: LogDetailsPanelProps) => {+ const { data: projects } = useProjectsQuery()+ const { data: organizations } = useOrganizationsQuery()++ const project = projects?.find(+ (project) => project.ref === selectedLog?.target.metadata.project_ref+ )+ const organization = organizations?.find(+ (org) => org.slug === selectedLog?.target.metadata.org_slug+ )++ return (+ <SidePanel+ size="large"+ header={`"${selectedLog?.action.name}" on ${dayjs(selectedLog?.occurred_at).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="Occurred at"+ value={selectedLog?.occurred_at}+ descriptionText={dayjs(selectedLog?.occurred_at).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"+ rows={5}+ className="input-mono input-xs"+ value={JSON.stringify(selectedLog?.actor.metadata, null, 2)}+ />+ </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"+ rows={5}+ className="input-mono input-xs"+ value={JSON.stringify(selectedLog?.action.metadata, null, 2)}+ />+ </FormSectionContent>+ </FormSection>++ <SidePanel.Separator />++ <FormSection header={<FormSectionLabel>Target</FormSectionLabel>}>+ <FormSectionContent loading={false}>+ <Input readOnly size="small" label="Name" value={selectedLog?.target.description} />+ <Input.TextArea+ readOnly+ size="small"+ label="Metadata"+ rows={5}+ className="input-mono input-xs"+ value={JSON.stringify(selectedLog?.target.metadata, null, 2)}+ />+ </FormSectionContent>+ </FormSection>+ </SidePanel>+ )+}++export default LogDetailsPaneldiff --git a/studio/components/interfaces/Account/index.ts b/studio/components/interfaces/Account/index.tsindex 4630ecbb9d8..3c653490437 100644--- a/studio/components/interfaces/Account/index.ts+++ b/studio/components/interfaces/Account/index.ts@@ -1,6 +1,7 @@import AccessTokenList from './AccessTokenList'+import AuditLogs from './AuditLogs/AuditLogs'import NewAccessTokenButton from './NewAccessTokenButton'import NewTokenBanner from './NewTokenBanner'import TOTPFactors from './TOTPFactors'-export { AccessTokenList, NewTokenBanner, NewAccessTokenButton, TOTPFactors }+export { AccessTokenList, NewTokenBanner, NewAccessTokenButton, TOTPFactors, AuditLogs }diff --git a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsxindex 614154776f3..52c1554eab0 100644--- a/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx+++ b/studio/components/layouts/ProjectLayout/NavigationBar/NavigationBar.tsx@@ -10,6 +10,7 @@ import { detectOS } from 'lib/helpers'import {Button,Dropdown,+ IconBookOpen,IconCommand,IconHome,IconSearch,@@ -146,6 +147,14 @@ const NavigationBar = () => {Account Preferences</Dropdown.Item></Link>+ <Link href="/account/audit">+ <Dropdown.Item+ key="header"+ icon={<IconBookOpen size={14} strokeWidth={1.5} />}+ >+ Audit Logs+ </Dropdown.Item>+ </Link><Dropdown.Separator /></>)}diff --git a/studio/data/profile/keys.ts b/studio/data/profile/keys.tsindex 2ed0d876185..bd25d359282 100644--- a/studio/data/profile/keys.ts+++ b/studio/data/profile/keys.ts@@ -2,4 +2,11 @@ export const profileKeys = {profile: () => ['profile'] as const,mfaFactors: () => ['mfa', 'factors'] as const,aaLevel: () => ['mfa', 'aaLevel'] as const,+ auditLogs: ({+ date_start,+ date_end,+ }: {+ date_start: string | undefined+ date_end: string | undefined+ }) => ['profile', 'audit-logs', { date_start, date_end }] as const,}diff --git a/studio/data/profile/profile-audit-logs-query.ts b/studio/data/profile/profile-audit-logs-query.tsnew file mode 100644index 00000000000..9e7b3ae6101--- /dev/null+++ b/studio/data/profile/profile-audit-logs-query.ts@@ -0,0 +1,48 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'+import { get } from 'data/fetchers'+import dayjs from 'dayjs'+import { ResponseError } from 'types'+import { profileKeys } from './keys'++export type ProfileAuditLogsVariables = {+ iso_timestamp_start?: string+ iso_timestamp_end?: string+}++export async function getProfileAuditLogs(+ { iso_timestamp_start, iso_timestamp_end }: ProfileAuditLogsVariables,+ signal?: AbortSignal+) {+ const { data, error } = await get('/platform/profile/audit', {+ params: {+ query: {+ iso_timestamp_start,+ iso_timestamp_end,+ },+ },+ signal,+ })++ if (error) throw error+ return data+}++export type ProfileAuditLogsData = Awaited<ReturnType<typeof getProfileAuditLogs>>+export type ProfileAuditLogsError = ResponseError++export const useProfileAuditLogsQuery = <TData = ProfileAuditLogsData>(+ vars: ProfileAuditLogsVariables,+ options: UseQueryOptions<ProfileAuditLogsData, ProfileAuditLogsError, TData> = {}+) => {+ const { iso_timestamp_start, iso_timestamp_end } = vars+ const date_start = dayjs(iso_timestamp_start).utc().format('YYYY-MM-DD')+ const date_end = dayjs(iso_timestamp_end).utc().format('YYYY-MM-DD')++ return useQuery<ProfileAuditLogsData, ProfileAuditLogsError, TData>(+ profileKeys.auditLogs({ date_start, date_end }),+ ({ signal }) => getProfileAuditLogs(vars, signal),+ {+ ...options,+ }+ )+}diff --git a/studio/pages/account/audit.tsx b/studio/pages/account/audit.tsxnew file mode 100644index 00000000000..7dddb8705a3--- /dev/null+++ b/studio/pages/account/audit.tsx@@ -0,0 +1,27 @@+import { AuditLogs } from 'components/interfaces/Account'+import { AccountLayout } from 'components/layouts'+import { NextPageWithLayout } from 'types'++const User: NextPageWithLayout = () => {+ return (+ <div className="my-2">+ <AuditLogs />+ </div>+ )+}++User.getLayout = (page) => (+ <AccountLayout+ title="Preferences"+ breadcrumbs={[+ {+ key: `supabase-settings`,+ label: 'Preferences',+ },+ ]}+ >+ {page}+ </AccountLayout>+)++export default User