Files
fffb1e23ca feat: implement profile permissions v2 api (#50966)
## Problem

Migrating Studio's permission checks from the old RLS json logic to
openfga backed permissions.

### New hooks and helpers

- `usePermissionsQueryV2` fetches the new profile openfga permisisons 
- `useAsyncCheckPermissionsV2` the replacement for the old check hook;
takes an FGA permission string (or a list)
- `FGA_PERMISSIONS` permission constants derived from
`@supabase/shared-types`. At the moment, the hook also accepts plain
strings for permissions not yet published in the package
- `useAsyncCheckUserContentPermissions` new hook for permission checks
on user content (SQL snippets, reports, log snippets). This wraps
``useAsyncCheckPermissionsV2` and adds existing content level rules on
top of the fga permission check

### Notes

- ~~Need api to support new permissions: project_operations_write,
billing_read/write, audit_logs_read~~ [DONE]
- ~~Still need to support: organization_config_read/write, auth hooks
and users permissions~~ [DONE]

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com>
2026-10-21 06:54:16 -04:00

196 lines
6.7 KiB
TypeScript

import { useParams } from 'common'
import type { ChangeEvent, ComponentProps, ReactNode } from 'react'
import { useEffect, useRef, useState } from 'react'
import { toast } from 'sonner'
import {
Button,
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogSection,
DialogSectionSeparator,
DialogTitle,
DialogTrigger,
} from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { Input } from 'ui-patterns/DataInputs/Input'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { PasswordStrengthBar } from '@/components/ui/PasswordStrengthBar'
import { useDatabasePasswordResetMutation } from '@/data/database/database-password-reset-mutation'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { useIsProjectActive } from '@/hooks/misc/useSelectedProject'
import { DEFAULT_MINIMUM_PASSWORD_STRENGTH } from '@/lib/constants'
import { passwordStrength, PasswordStrengthScore } from '@/lib/password-strength'
import { generateStrongPassword } from '@/lib/project'
export type ResetDbPasswordDialogProps = {
disabled?: boolean
onPasswordReset?: (password: string) => void
triggerClassName?: string
triggerIcon?: ReactNode
triggerLabel?: string
triggerVariant?: ComponentProps<typeof ButtonTooltip>['variant']
}
export const ResetDbPasswordDialog = ({
disabled = false,
onPasswordReset,
triggerClassName,
triggerIcon,
triggerLabel = 'Reset password',
triggerVariant = 'default',
}: ResetDbPasswordDialogProps) => {
const { ref } = useParams()
const isProjectActive = useIsProjectActive()
const { can: canResetDbPassword } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.DATABASE_CONFIG_WRITE
)
const [showResetDbPass, setShowResetDbPass] = useState<boolean>(false)
const [password, setPassword] = useState<string>('')
const [passwordStrengthMessage, setPasswordStrengthMessage] = useState<string>('')
const [passwordStrengthWarning, setPasswordStrengthWarning] = useState<string>('')
const [passwordStrengthScore, setPasswordStrengthScore] = useState(0)
const latestPasswordStrengthValueRef = useRef('')
const passwordStrengthResultValueRef = useRef('')
const { mutate: resetDatabasePassword, isPending: isUpdatingPassword } =
useDatabasePasswordResetMutation({
onSuccess: async (_data, variables) => {
toast.success('Successfully updated database password')
onPasswordReset?.(variables.password)
setShowResetDbPass(false)
},
})
useEffect(() => {
if (showResetDbPass) {
setPassword('')
setPasswordStrengthMessage('')
setPasswordStrengthWarning('')
setPasswordStrengthScore(0)
latestPasswordStrengthValueRef.current = ''
passwordStrengthResultValueRef.current = ''
}
}, [showResetDbPass])
async function checkPasswordStrength(value: string) {
latestPasswordStrengthValueRef.current = value
const { message, warning, strength } = await passwordStrength(value)
if (latestPasswordStrengthValueRef.current !== value) return
passwordStrengthResultValueRef.current = value
setPasswordStrengthScore(strength)
setPasswordStrengthWarning(warning)
setPasswordStrengthMessage(message)
}
const onDbPassChange = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
setPassword(value)
if (value == '') {
latestPasswordStrengthValueRef.current = value
passwordStrengthResultValueRef.current = value
setPasswordStrengthScore(-1)
setPasswordStrengthMessage('')
setPasswordStrengthWarning('')
} else checkPasswordStrength(value)
}
const confirmResetDbPass = async () => {
if (!ref) return console.error('Project ref is required')
if (
passwordStrengthResultValueRef.current === password &&
passwordStrengthScore >= DEFAULT_MINIMUM_PASSWORD_STRENGTH
) {
resetDatabasePassword({ ref, password })
}
}
function generatePassword() {
const password = generateStrongPassword()
setPassword(password)
checkPasswordStrength(password)
}
return (
<Dialog open={showResetDbPass} onOpenChange={(open) => setShowResetDbPass(open)}>
<DialogTrigger asChild>
<ButtonTooltip
variant={triggerVariant}
className={triggerClassName}
icon={triggerIcon}
disabled={!canResetDbPassword || !isProjectActive || disabled}
tooltip={{
content: {
side: 'bottom',
text: !canResetDbPassword
? 'You need additional permissions to reset the database password'
: !isProjectActive
? 'Unable to reset database password as project is not active'
: undefined,
},
}}
>
{triggerLabel}
</ButtonTooltip>
</DialogTrigger>
<DialogContent size="medium">
<DialogHeader>
<DialogTitle>Reset database password</DialogTitle>
</DialogHeader>
<DialogSectionSeparator />
<DialogSection className="w-full space-y-8">
<Admonition type="warning" title="This password is shared across every connection method">
Resetting it will disconnect the pooler, read replicas, and any app, ORM, or tool still
using the old password. Update it everywhere before switching over.
</Admonition>
<FormItemLayout
layout="vertical"
isReactForm={false}
error={passwordStrengthWarning}
description={
<PasswordStrengthBar
passwordStrengthScore={passwordStrengthScore as PasswordStrengthScore}
passwordStrengthMessage={passwordStrengthMessage}
password={password}
generateStrongPassword={generatePassword}
/>
}
>
<Input
copy={password.length > 0}
aria-invalid={!!passwordStrengthWarning}
type="password"
placeholder="Type in a strong password"
value={password}
autoComplete="off"
onChange={onDbPassChange}
/>
</FormItemLayout>
</DialogSection>
<DialogFooter>
<Button disabled={isUpdatingPassword} onClick={() => setShowResetDbPass(false)}>
Cancel
</Button>
<Button
variant="primary"
loading={isUpdatingPassword}
disabled={isUpdatingPassword}
onClick={() => confirmResetDbPass()}
>
Reset password
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}