The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: Add Login event to account audit logs (#33660)
Kamil Ogórekf553065a2e5c
diff --git a/apps/studio/components/interfaces/SignIn/SignInForm.tsx b/apps/studio/components/interfaces/SignIn/SignInForm.tsxindex 85358caaa51..8e8e29f5c4a 100644--- a/apps/studio/components/interfaces/SignIn/SignInForm.tsx+++ b/apps/studio/components/interfaces/SignIn/SignInForm.tsx@@ -9,6 +9,7 @@ import { toast } from 'sonner'import { object, string } from 'yup'import { TelemetryActions } from 'common/telemetry-constants'+import { useAddLoginEvent } from 'data/misc/audit-login-mutation'import { getMfaAuthenticatorAssuranceLevel } from 'data/profile/mfa-authenticator-assurance-level-query'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useLastSignIn } from 'hooks/misc/useLastSignIn'@@ -30,6 +31,7 @@ const SignInForm = () => {const captchaRef = useRef<HCaptcha>(null)const { mutate: sendEvent } = useSendEventMutation()+ const { mutate: addLoginEvent } = useAddLoginEvent()const onSignIn = async ({ email, password }: { email: string; password: string }) => {const toastId = toast.loading('Signing in...')@@ -61,6 +63,8 @@ const SignInForm = () => {toast.success(`Signed in successfully!`, { id: toastId })sendEvent({ action: TelemetryActions.SIGN_IN, properties: { category: 'account' } })+ addLoginEvent({})+await queryClient.resetQueries()const returnTo = getReturnToPath()// since we're already on the /sign-in page, prevent redirect loopsdiff --git a/apps/studio/components/interfaces/SignIn/SignInSSOForm.tsx b/apps/studio/components/interfaces/SignIn/SignInSSOForm.tsxindex fb5c2b11feb..436b5f4c149 100644--- a/apps/studio/components/interfaces/SignIn/SignInSSOForm.tsx+++ b/apps/studio/components/interfaces/SignIn/SignInSSOForm.tsx@@ -5,8 +5,6 @@ import { useRef, useState } from 'react'import { toast } from 'sonner'import { object, string } from 'yup'-import { TelemetryActions } from 'common/telemetry-constants'-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { useLastSignIn } from 'hooks/misc/useLastSignIn'import { BASE_PATH } from 'lib/constants'import { auth, buildPathWithParams } from 'lib/gotrue'@@ -24,8 +22,6 @@ const SignInSSOForm = () => {email: string().email('Must be a valid email').required('Email is required'),})- const { mutate: sendEvent } = useSendEventMutation()-const onSignIn = async ({ email }: { email: string }) => {const toastId = toast.loading('Signing in...')@@ -53,7 +49,6 @@ const SignInSSOForm = () => {})if (!error) {- sendEvent({ action: TelemetryActions.SIGN_IN, properties: { category: 'account' } })await queryClient.resetQueries()setLastSignInUsed('sso')if (data) {diff --git a/apps/studio/components/interfaces/SignIn/SignInWithGitHub.tsx b/apps/studio/components/interfaces/SignIn/SignInWithGitHub.tsxindex b98d02ed6e1..23ac466283c 100644--- a/apps/studio/components/interfaces/SignIn/SignInWithGitHub.tsx+++ b/apps/studio/components/interfaces/SignIn/SignInWithGitHub.tsx@@ -5,14 +5,15 @@ import { toast } from 'sonner'import { BASE_PATH } from 'lib/constants'+import { useLastSignIn } from 'hooks/misc/useLastSignIn'import { auth, buildPathWithParams } from 'lib/gotrue'import { Button } from 'ui'-import { useLastSignIn } from 'hooks/misc/useLastSignIn'import { LastSignInWrapper } from './LastSignInWrapper'const SignInWithGitHub = () => {const [loading, setLoading] = useState(false)- const [lastSignInUsed, setLastSignInUsed] = useLastSignIn()+ const [_, setLastSignInUsed] = useLastSignIn()+async function handleGithubSignIn() {setLoading(true)@@ -28,14 +29,11 @@ const SignInWithGitHub = () => {const { error } = await auth.signInWithOAuth({provider: 'github',- options: {- redirectTo,- },+ options: { redirectTo },})+if (error) throw error- else {- setLastSignInUsed('github')- }+ else setLastSignInUsed('github')} catch (error: any) {toast.error(`Failed to sign in via GitHub: ${error.message}`)Sentry.captureMessage('[CRITICAL] Failed to sign in via GH: ' + error.message)diff --git a/apps/studio/data/misc/audit-login-mutation.ts b/apps/studio/data/misc/audit-login-mutation.tsnew file mode 100644index 00000000000..376e9301705--- /dev/null+++ b/apps/studio/data/misc/audit-login-mutation.ts@@ -0,0 +1,43 @@+import * as Sentry from '@sentry/nextjs'+import { useMutation, UseMutationOptions } from '@tanstack/react-query'+import { toast } from 'sonner'++import { handleError, post } from 'data/fetchers'+import type { ResponseError } from 'types'++export async function addLoginEvent() {+ const { error } = await post('/platform/profile/audit-login')+ if (error) handleError(error)+}++type AddLoginEventVariables = {}+type AddLoginEventData = Awaited<ReturnType<typeof addLoginEvent>>++export const useAddLoginEvent = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<AddLoginEventData, ResponseError, AddLoginEventVariables>,+ 'mutationFn'+> = {}) => {+ return useMutation<AddLoginEventData, ResponseError, AddLoginEventVariables>(+ (vars) => addLoginEvent(),+ {+ async onSuccess(data, variables, context) {+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ Sentry.captureException(+ new Error("Failed to add login event to user's audit log", { cause: data })+ )+ if (onError === undefined) {+ toast.error(`Failed to add login event: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ }+ )+}diff --git a/apps/studio/pages/sign-in-mfa.tsx b/apps/studio/pages/sign-in-mfa.tsxindex b73e2922c79..9060fb3a981 100644--- a/apps/studio/pages/sign-in-mfa.tsx+++ b/apps/studio/pages/sign-in-mfa.tsx@@ -7,6 +7,7 @@ import { TelemetryActions } from 'common/telemetry-constants'import SignInMfaForm from 'components/interfaces/SignIn/SignInMfaForm'import SignInLayout from 'components/layouts/SignInLayout/SignInLayout'import { Loading } from 'components/ui/Loading'+import { useAddLoginEvent } from 'data/misc/audit-login-mutation'import { useSendEventMutation } from 'data/telemetry/send-event-mutation'import { auth, buildPathWithParams, getAccessToken, getReturnToPath } from 'lib/gotrue'import type { NextPageWithLayout } from 'types'@@ -14,7 +15,9 @@ import type { NextPageWithLayout } from 'types'const SignInMfaPage: NextPageWithLayout = () => {const router = useRouter()const queryClient = useQueryClient()+const { mutate: sendEvent } = useSendEventMutation()+ const { mutate: addLoginEvent } = useAddLoginEvent()const [loading, setLoading] = useState(true)@@ -44,6 +47,8 @@ const SignInMfaPage: NextPageWithLayout = () => {if (data.currentLevel === data.nextLevel) {sendEvent({ action: TelemetryActions.SIGN_IN, properties: { category: 'account' } })+ addLoginEvent({})+await queryClient.resetQueries()router.push(getReturnToPath())returndiff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.tsindex cc5c6d25bc3..9480cf33367 100644--- a/packages/api-types/types/api.d.ts+++ b/packages/api-types/types/api.d.ts@@ -1310,7 +1310,7 @@ export interface paths {path?: nevercookie?: never}- /** Gets the Stripe customer */+ /** Gets the Billing customer */get: operations['CustomerController_getCustomer']/** Updates the billing customer */put: operations['updateCustomerV2']@@ -1660,7 +1660,7 @@ export interface paths {cookie?: never}/** Gets the given organization's roles */- get: operations['OrganizationRolesController_getAllRolesV2']+ get: operations['OrganizationRolesController_getAllRoles']put?: neverpost?: neverdelete?: never@@ -2109,6 +2109,23 @@ export interface paths {patch?: nevertrace?: never}+ '/platform/profile/audit-login': {+ parameters: {+ query?: never+ header?: never+ path?: never+ cookie?: never+ }+ get?: never+ put?: never+ /** Logged into account */+ post: operations['ProfileController_auditAccountLogin']+ delete?: never+ options?: never+ head?: never+ patch?: never+ trace?: never+ }'/platform/profile/password-check': {parameters: {query?: never@@ -5183,7 +5200,7 @@ export interface paths {cookie?: never}/** Gets the given organization's roles */- get: operations['OrganizationRolesController_getAllRolesV2']+ get: operations['OrganizationRolesController_getAllRoles']put?: neverpost?: neverdelete?: never@@ -15386,7 +15403,7 @@ export interface operations {'application/json': components['schemas']['CustomerResponse']}}- /** @description Failed to retrieve the Stripe customer */+ /** @description Failed to retrieve the Billing customer */500: {headers: {[name: string]: unknown@@ -16296,7 +16313,7 @@ export interface operations {}}}- OrganizationRolesController_getAllRolesV2: {+ OrganizationRolesController_getAllRoles: {parameters: {query?: neverheader?: never@@ -18444,6 +18461,23 @@ export interface operations {}}}+ ProfileController_auditAccountLogin: {+ parameters: {+ query?: never+ header?: never+ path?: never+ cookie?: never+ }+ requestBody?: never+ responses: {+ 201: {+ headers: {+ [name: string]: unknown+ }+ content?: never+ }+ }+ }PasswordCheckController_checkPassword: {parameters: {query?: never@@ -25746,7 +25780,7 @@ export interface operations {}}}- OrganizationRolesController_getAllRolesV2: {+ OrganizationRolesController_getAllRoles: {parameters: {query?: neverheader?: never