Skip to content

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

2.1 KB
Raw Blame
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'

import { jitDbAccessKeys } from './keys'
import { handleError, put } from '@/data/fetchers'
import type { ResponseError } from '@/types'

type JitDbAccessGrantVariables = {
  projectRef: string
  userId: string
  roles: Array<{
    role: string
    branches_only?: boolean
    expires_at?: number // Unix timestamp in seconds per role
    allowed_networks?: {
      allowed_cidrs?: Array<{ cidr: string }>
      allowed_cidrs_v6?: Array<{ cidr: string }>
    }
  }>
}

async function grantJitDbAccess({ projectRef, userId, roles }: JitDbAccessGrantVariables) {
  if (!projectRef) throw new Error('projectRef is required')
  if (!userId) throw new Error('userId is required')
  if (!roles || roles.length === 0) throw new Error('At least one role is required')

  const { data, error } = await put(`/v1/projects/{ref}/database/jit`, {
    params: { path: { ref: projectRef } },
    body: {
      user_id: userId,
      roles,
    },
  })

  if (error) handleError(error)
  return data
}

type JitDbAccessGrantData = Awaited<ReturnType<typeof grantJitDbAccess>>

export const useJitDbAccessGrantMutation = ({
  onSuccess,
  onError,
  ...options
}: Omit<
  UseMutationOptions<JitDbAccessGrantData, ResponseError, JitDbAccessGrantVariables>,
  'mutationFn'
> = {}) => {
  const queryClient = useQueryClient()

  return useMutation<JitDbAccessGrantData, ResponseError, JitDbAccessGrantVariables>({
    mutationFn: (vars) => grantJitDbAccess(vars),

    async onSuccess(data, variables, context, mutationContext) {
      const { projectRef } = variables
      await queryClient.invalidateQueries({ queryKey: jitDbAccessKeys.members(projectRef) })
      await onSuccess?.(data, variables, context, mutationContext)
    },
    async onError(data, variables, context, mutationContext) {
      if (onError === undefined) {
        toast.error(`Failed to grant temporary access: ${data.message}`)
      } else {
        onError(data, variables, context, mutationContext)
      }
    },
    ...options,
  })
}