The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): auth overview usage section (#39207)
kemal.earth79278656691b
diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewLearnMore.tsx b/apps/studio/components/interfaces/Auth/Overview/OverviewLearnMore.tsxindex 09053d42ce7..14274aeb8e8 100644--- a/apps/studio/components/interfaces/Auth/Overview/OverviewLearnMore.tsx+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewLearnMore.tsx@@ -15,7 +15,7 @@ export const OverviewLearnMore = () => {{label: 'Docs',title: 'Authentication docs',- description: 'Read more on authentication and benefits of using Supabase policies.',+ description: 'Read more on authentication and the benefits of using Supabase policies.',image: `${BASE_PATH}/img/auth-overview/auth-overview-docs.jpg`,actions: [{@@ -68,8 +68,7 @@ export const OverviewLearnMore = () => {{label: 'Logs',title: 'Dive into the logs',- description:- 'Our authentication logs provide a deeper view into your auth requests and errors.',+ description: 'Authentication logs provide a deeper view into your auth requests.',image: `${BASE_PATH}/img/auth-overview/auth-overview-logs.jpg`,actions: [{@@ -84,7 +83,7 @@ export const OverviewLearnMore = () => {return (<ScaffoldSection isFullWidth><ScaffoldSectionTitle className="mb-4">Learn more</ScaffoldSectionTitle>- <div className="grid grid-cols-1 lg:grid-cols-3 gap-3">+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">{LearnMoreCards.map((card) => (<Card key={card.label} className="relative"><CardHeader className="absolute top-0 left-0 right-0 border-b-0">@@ -100,12 +99,12 @@ export const OverviewLearnMore = () => {className="object-fit"/></div>- <div className="p-4">- <div className="flex flex-col gap-1 mb-4">+ <div className="p-4 flex flex-col">+ <div className="flex flex-col gap-1 mb-4 flex-1"><h4>{card.title}</h4><p className="text-sm text-foreground-lighter">{card.description}</p></div>- <div className="flex flex-col gap-2 items-start">+ <div className="flex flex-col gap-2 items-start mt-auto">{card.actions.map((action) => {if ('href' in action) {return (diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.constants.ts b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.constants.tsnew file mode 100644index 00000000000..caad4e20030--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.constants.ts@@ -0,0 +1,105 @@+import dayjs from 'dayjs'+import { fetchLogs } from 'data/reports/report.utils'++// Date range helpers+export const getDateRanges = () => {+ const endDate = dayjs().toISOString()+ const startDate = dayjs().subtract(24, 'hour').toISOString()+ const previousEndDate = dayjs().subtract(24, 'hour').toISOString()+ const previousStartDate = dayjs().subtract(48, 'hour').toISOString()++ return {+ current: { startDate, endDate },+ previous: { startDate: previousStartDate, endDate: previousEndDate },+ }+}++export const AUTH_COMBINED_QUERY = () => `+ with base as (+ select+ json_value(event_message, "$.auth_event.action") as action,+ json_value(event_message, "$.auth_event.actor_id") as actor_id,+ cast(json_value(event_message, "$.duration") as int64) as duration_ns+ from auth_logs+ )++ select+ 'activeUsers' as metric,+ cast(count(distinct case+ when action in (+ 'login','user_signedup','token_refreshed','user_modified',+ 'user_recovery_requested','user_reauthenticate_requested'+ ) then actor_id+ else null+ end) as float64) as value+ from base++ union all+ select 'passwordResetRequests' as metric,+ cast(count(case when action = 'user_recovery_requested' then 1 else null end) as float64)+ from base++ union all+ select 'signUpCount' as metric,+ cast(count(case when action = 'user_signedup' then 1 else null end) as float64)+ from base++ union all+ select 'signInLatency' as metric,+ coalesce(round(avg(case when action = 'login' then duration_ns else null end) / 1000000, 2), 0)+ from base++ union all+ select 'signUpLatency' as metric,+ coalesce(round(avg(case when action = 'user_signedup' then duration_ns else null end) / 1000000, 2), 0)+ from base+`++export const fetchAllAuthMetrics = async (projectRef: string, period: 'current' | 'previous') => {+ const sql = AUTH_COMBINED_QUERY()+ const { current, previous } = getDateRanges()+ const dateRange = period === 'current' ? current : previous++ return await fetchLogs(projectRef, sql, dateRange.startDate, dateRange.endDate)+}++export const processAllAuthMetrics = (currentData: any[], previousData: any[]) => {+ const processData = (data: any[]) => {+ if (!data || !Array.isArray(data)) {+ return { activeUsers: 0, passwordResets: 0, signInLatency: 0, signUpLatency: 0 }+ }++ const result = data.reduce(+ (acc, row) => {+ const { metric, value } = row+ if (metric === 'activeUsers') acc.activeUsers = value || 0+ if (metric === 'passwordResetRequests') acc.passwordResets = value || 0+ if (metric === 'signInLatency') acc.signInLatency = value || 0+ if (metric === 'signUpLatency') acc.signUpLatency = value || 0+ return acc+ },+ { activeUsers: 0, passwordResets: 0, signInLatency: 0, signUpLatency: 0 }+ )++ return result+ }++ return {+ current: processData(currentData),+ previous: processData(previousData),+ }+}++// Utility functions+export const calculatePercentageChange = (current: number, previous: number): number => {+ if (previous === 0) return current > 0 ? 100 : 0+ return ((current - previous) / previous) * 100+}++export const getChangeColor = (percentageChange: number): string => {+ return percentageChange >= 0 ? 'text-brand' : 'text-destructive'+}++export const getChangeSign = (percentageChange: number): string => {+ return percentageChange >= 0 ? '+' : ''+}diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.tsx b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.tsxindex f0223bd5091..dac8b7b29ab 100644--- a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.tsx+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.tsx@@ -1,14 +1,204 @@-import { ScaffoldSection, ScaffoldSectionTitle } from 'components/layouts/Scaffold'-import { Card } from 'ui'+import {+ ScaffoldSection,+ ScaffoldSectionTitle,+ ScaffoldSectionContent,+} from 'components/layouts/Scaffold'+import { Card, CardContent, cn } from 'ui'+import Link from 'next/link'+import { useParams } from 'common'+import { ChevronRight, Loader2 } from 'lucide-react'+import { Reports } from 'icons'+import {+ getChangeSign,+ getChangeColor,+ fetchAllAuthMetrics,+ processAllAuthMetrics,+ calculatePercentageChange,+} from './OverviewUsage.constants'+import { useQuery } from '@tanstack/react-query'+import { useMemo } from 'react'+import { ReportChartV2 } from 'components/interfaces/Reports/v2/ReportChartV2'+import { createAuthReportConfig } from 'data/reports/v2/auth.config'+import dayjs from 'dayjs'++const StatCard = ({+ title,+ current,+ previous,+ loading,+ suffix = '',+}: {+ title: string+ current: number+ previous: number+ loading: boolean+ suffix?: string+}) => {+ const changeColor = getChangeColor(previous)+ const changeSign = getChangeSign(previous)+ const formattedCurrent = suffix === 'ms' ? current.toFixed(2) : current++ return (+ <Card>+ <CardContent+ className={cn(+ 'flex flex-col my-1 gap-1',+ loading && 'opacity-50 items-center justify-center min-h-[108px]'+ )}+ >+ {loading ? (+ <Loader2 className="size-5 animate-spin text-foreground-light" />+ ) : (+ <>+ <h4 className="text-sm text-foreground-lighter font-normal mb-0 truncate">{title}</h4>+ <p className="text-xl">{`${formattedCurrent}${suffix}`}</p>+ <p className={cn('text-sm text-foreground-lighter', changeColor)}>+ {`${changeSign}${previous.toFixed(1)}%`}+ </p>+ </>+ )}+ </CardContent>+ </Card>+ )+}export const OverviewUsage = () => {+ const { ref } = useParams()++ const { data: currentData, isLoading: currentLoading } = useQuery({+ queryKey: ['auth-metrics', ref, 'current'],+ queryFn: () => fetchAllAuthMetrics(ref as string, 'current'),+ enabled: !!ref,+ })++ const { data: previousData, isLoading: previousLoading } = useQuery({+ queryKey: ['auth-metrics', ref, 'previous'],+ queryFn: () => fetchAllAuthMetrics(ref as string, 'previous'),+ enabled: !!ref,+ })++ const metrics = processAllAuthMetrics(currentData?.result || [], previousData?.result || [])+ const isLoading = currentLoading || previousLoading++ const activeUsersChange = calculatePercentageChange(+ metrics.current.activeUsers,+ metrics.previous.activeUsers+ )+ const passwordResetChange = calculatePercentageChange(+ metrics.current.passwordResets,+ metrics.previous.passwordResets+ )+ const signInLatencyChange = calculatePercentageChange(+ metrics.current.signInLatency,+ metrics.previous.signInLatency+ )+ const signUpLatencyChange = calculatePercentageChange(+ metrics.current.signUpLatency,+ metrics.previous.signUpLatency+ )++ const endDate = dayjs().toISOString()+ const startDate = dayjs().subtract(24, 'hour').toISOString()++ const signUpChartConfig = useMemo(() => {+ const config = createAuthReportConfig({+ projectRef: ref as string,+ startDate,+ endDate,+ interval: '1h',+ filters: { status_code: null },+ })+ const chart = config.find((c) => c.id === 'signups')+ if (chart) {+ return { ...chart, defaultChartStyle: 'bar' }+ }+ return chart+ }, [ref, startDate, endDate])++ const signInChartConfig = useMemo(() => {+ const config = createAuthReportConfig({+ projectRef: ref as string,+ startDate,+ endDate,+ interval: '1h',+ filters: { status_code: null },+ })+ const chart = config.find((c) => c.id === 'sign-in-attempts')+ if (chart) {+ return { ...chart, defaultChartStyle: 'bar' }+ }+ return chart+ }, [ref, startDate, endDate])++ const updateDateRange = (from: string, to: string) => {+ console.log('Date range update:', from, to)+ }+return (<ScaffoldSection isFullWidth>- <ScaffoldSectionTitle className="mb-4">Usage</ScaffoldSectionTitle>- <div className="grid grid-cols-1 md:grid-cols-2 gap-6 opacity-30 pointer-events-none">- <Card className="aspect-video" />- <Card className="aspect-video" />+ <div className="flex items-center justify-between mb-4">+ <ScaffoldSectionTitle>Usage</ScaffoldSectionTitle>+ <Link+ href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}&isHelper=true&helperText=Last+24+hours`}+ className="text-sm text-link inline-flex items-center gap-x-1.5"+ >+ <Reports size={14} />+ <span>View all reports</span>+ <ChevronRight size={14} />+ </Link></div>+ <ScaffoldSectionContent className="gap-4">+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ <StatCard+ title="Active Users"+ current={metrics.current.activeUsers}+ previous={activeUsersChange}+ loading={isLoading}+ />+ <StatCard+ title="Password Reset Requests"+ current={metrics.current.passwordResets}+ previous={passwordResetChange}+ loading={isLoading}+ />+ <StatCard+ title="Sign up Latency"+ current={Number(metrics.current.signUpLatency.toFixed(2))}+ previous={signUpLatencyChange}+ loading={isLoading}+ suffix="ms"+ />+ <StatCard+ title="Sign in Latency"+ current={Number(metrics.current.signInLatency.toFixed(2))}+ previous={signInLatencyChange}+ loading={isLoading}+ suffix="ms"+ />+ </div>+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ {signUpChartConfig && (+ <ReportChartV2+ report={signUpChartConfig}+ projectRef={ref as string}+ startDate={startDate}+ endDate={endDate}+ interval="1h"+ updateDateRange={updateDateRange}+ />+ )}+ {signInChartConfig && (+ <ReportChartV2+ report={signInChartConfig}+ projectRef={ref as string}+ startDate={startDate}+ endDate={endDate}+ interval="1h"+ updateDateRange={updateDateRange}+ />+ )}+ </div>+ </ScaffoldSectionContent></ScaffoldSection>)}diff --git a/apps/studio/pages/project/[ref]/auth/overview.tsx b/apps/studio/pages/project/[ref]/auth/overview.tsxindex 6f55feeb6c7..86f8f300fe1 100644--- a/apps/studio/pages/project/[ref]/auth/overview.tsx+++ b/apps/studio/pages/project/[ref]/auth/overview.tsx@@ -45,7 +45,14 @@ AuthOverview.getLayout = (page) => (<AuthLayout><PageLayouttitle="Overview"- secondaryActions={<DocsButton href={`${DOCS_URL}/guides/auth`} />}+ secondaryActions={+ <div className="flex items-center gap-2">+ <span className="text-sm text-foreground-light">+ All reports <span className="text-foreground">Last 24 hours</span>+ </span>+ <DocsButton href={`${DOCS_URL}/guides/auth`} />+ </div>+ }size="large">{page}