The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(account): let OAuth-only users add a password to their account (#49057)
fadymak17dde3d324fc
diff --git a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.test.tsx b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.test.tsxnew file mode 100644index 00000000000..479d1664acd--- /dev/null+++ b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.test.tsx@@ -0,0 +1,216 @@+import { fireEvent, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { mockAnimationsApi } from 'jsdom-testing-mocks'+import { http, HttpResponse } from 'msw'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { AccountIdentities } from './AccountIdentities'+import { BASE_PATH } from '@/lib/constants'+import { customRender } from '@/tests/lib/custom-render'+import { mswServer } from '@/tests/lib/msw'++// Radix Dialog relies on the Web Animations API, which jsdom lacks.+mockAnimationsApi()++const { getUserMock, updateUserMock, refreshSessionMock, signOutMock, useFlagMock } = vi.hoisted(+ () => ({+ getUserMock: vi.fn(),+ updateUserMock: vi.fn(),+ refreshSessionMock: vi.fn(),+ signOutMock: vi.fn(),+ useFlagMock: vi.fn(),+ })+)++// Overrides the global partial mock from vitestSetup, so re-apply `useParams` alongside `useFlag`.+vi.mock('common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('common')>()+ return {+ ...actual,+ useParams: () => ({ ref: 'default' }),+ useFlag: useFlagMock,+ }+})++vi.mock('@/lib/gotrue', () => ({+ auth: {+ getUser: getUserMock,+ updateUser: updateUserMock,+ refreshSession: refreshSessionMock,+ signOut: signOutMock,+ },+ buildPathWithParams: (path: string) => path,+}))++const EMAIL = '[email protected]'+const VALID_PASSWORD = 'Str0ng!password'++type IdentityFixture = {+ identity_id: string+ id: string+ user_id: string+ provider: string+ identity_data: Record<string, string>+ email: string+}++const githubIdentity: IdentityFixture = {+ identity_id: 'github-identity-id',+ id: 'github-user-id',+ user_id: 'user-id',+ provider: 'github',+ identity_data: { user_name: 'testuser' },+ email: EMAIL,+}++const emailIdentity: IdentityFixture = {+ identity_id: 'email-identity-id',+ id: 'user-id',+ user_id: 'user-id',+ provider: 'email',+ identity_data: {},+ email: EMAIL,+}++const ssoIdentity: IdentityFixture = {+ identity_id: 'sso-identity-id',+ id: 'sso-user-id',+ user_id: 'user-id',+ provider: 'sso:4d21b3cf-3a2f-44d3-b7d6-2b0dd393f671',+ identity_data: {},+ email: EMAIL,+}++const mockGetUser = (identities: IdentityFixture[]) => {+ getUserMock.mockResolvedValue({+ data: { user: { id: 'user-id', email: EMAIL, identities } },+ error: null,+ })+}++const renderAccountIdentities = () => {+ mswServer.use(+ http.get(`${BASE_PATH}/api/enabled-features-overrides`, () =>+ HttpResponse.json({ disabled_features: [] })+ )+ )++ return customRender(<AccountIdentities />)+}++const openAddPasswordDialog = async () => {+ const openButton = await screen.findByRole('button', { name: 'Add password' })+ fireEvent.click(openButton)++ return await screen.findByRole('dialog')+}++describe('AccountIdentities', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ refreshSessionMock.mockResolvedValue({ data: {}, error: null })+ signOutMock.mockResolvedValue({ error: null })+ useFlagMock.mockImplementation((name: string) => name === 'enableAccountPassword')+ })++ it('offers to add a password when the user only has OAuth identities', async () => {+ mockGetUser([githubIdentity])++ renderAccountIdentities()++ expect(await screen.findByRole('button', { name: 'Add password' })).toBeInTheDocument()+ expect(screen.getByText('Email')).toBeInTheDocument()+ expect(screen.queryByRole('link', { name: 'Change password' })).not.toBeInTheDocument()+ })++ it('does not offer to add a password when an email identity exists', async () => {+ mockGetUser([githubIdentity, emailIdentity])++ renderAccountIdentities()++ expect(await screen.findByRole('link', { name: 'Change password' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Add password' })).not.toBeInTheDocument()+ })++ it('does not offer to add a password when the feature flag is disabled', async () => {+ useFlagMock.mockReturnValue(false)+ mockGetUser([githubIdentity])++ renderAccountIdentities()++ expect(await screen.findByText('GitHub')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Add password' })).not.toBeInTheDocument()+ expect(screen.queryByText('Email')).not.toBeInTheDocument()+ })++ it('does not offer to add a password to SSO users', async () => {+ mockGetUser([ssoIdentity])++ renderAccountIdentities()++ expect(await screen.findByText('SSO')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Add password' })).not.toBeInTheDocument()+ })++ it('adds a password and flips the row to the email identity actions', async () => {+ mockGetUser([githubIdentity])+ updateUserMock.mockImplementation(async () => {+ // GoTrue creates the email identity when the password is set, so the+ // post-mutation refetch sees both identities.+ mockGetUser([githubIdentity, emailIdentity])+ return { data: { user: { id: 'user-id', email: EMAIL } }, error: null }+ })++ renderAccountIdentities()+ const dialog = await openAddPasswordDialog()++ const emailInput = within(dialog).getByLabelText('Email')+ expect(emailInput).toBeDisabled()+ expect(emailInput).toHaveValue(EMAIL)++ await userEvent.type(within(dialog).getByPlaceholderText('••••••••'), VALID_PASSWORD)+ fireEvent.click(within(dialog).getByRole('button', { name: 'Add password' }))++ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(updateUserMock).toHaveBeenCalledWith({ password: VALID_PASSWORD })+ expect(signOutMock).toHaveBeenCalledWith({ scope: 'others' })++ expect(await screen.findByRole('link', { name: 'Change password' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Add password' })).not.toBeInTheDocument()+ })++ it('keeps the dialog open when setting the password fails', async () => {+ mockGetUser([githubIdentity])+ updateUserMock.mockResolvedValue({+ data: { user: null },+ error: { message: 'Password update failed' },+ })++ renderAccountIdentities()+ const dialog = await openAddPasswordDialog()++ await userEvent.type(within(dialog).getByPlaceholderText('••••••••'), VALID_PASSWORD)+ fireEvent.click(within(dialog).getByRole('button', { name: 'Add password' }))++ await waitFor(() => expect(updateUserMock).toHaveBeenCalledWith({ password: VALID_PASSWORD }))+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(signOutMock).not.toHaveBeenCalled()+ })++ it('does not submit a password that fails validation', async () => {+ mockGetUser([githubIdentity])++ renderAccountIdentities()+ const dialog = await openAddPasswordDialog()++ await userEvent.type(within(dialog).getByPlaceholderText('••••••••'), 'weak')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Add password' }))++ expect(+ await within(dialog).findByText(+ 'Password must contain at least 8 characters, including uppercase, lowercase, number, and special character'+ )+ ).toBeInTheDocument()+ expect(updateUserMock).not.toHaveBeenCalled()+ })+})diff --git a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.tsx b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.tsxindex 2456d57068d..9e74deca4fd 100644--- a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.tsx+++ b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.tsx@@ -1,4 +1,5 @@import type { Provider } from '@supabase/auth-js'+import { useFlag } from 'common'import dayjs from 'dayjs'import { Edit, Unlink } from 'lucide-react'import Link from 'next/link'@@ -29,7 +30,8 @@ import {} from 'ui-patterns/PageSection'import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'-import { parseRedirectMessage } from './AccountIdentities.utils'+import { parseRedirectMessage, shouldShowAddPasswordRow } from './AccountIdentities.utils'+import { AddPasswordRow } from './AddPasswordRow'import {ChangeEmailAddressForm,GitHubChangeEmailAddress,@@ -60,7 +62,11 @@ export const AccountIdentities = () => {[enabledProviders])+ const isAddAccountPasswordEnabled = useFlag('enableAccountPassword')+const identities = data?.identities ?? []+ const showAddPasswordRow =+ isAddAccountPasswordEnabled && shouldShowAddPasswordRow({ identities, email: data?.email })const isChangeExpired = data?.email_change_sent_at? dayjs().utc().diff(dayjs(data?.email_change_sent_at).utc(), 'minute') > 10: false@@ -127,7 +133,7 @@ export const AccountIdentities = () => {<PageSection><PageSectionMeta><PageSectionSummary>- <PageSectionTitle>Account identities</PageSectionTitle>+ <PageSectionTitle>Sign-in methods</PageSectionTitle><PageSectionDescription>Manage the providers linked to your Supabase account and update their details.</PageSectionDescription>@@ -142,6 +148,8 @@ export const AccountIdentities = () => {)}{isSuccess && (<div className="divide-y">+ {showAddPasswordRow && !!data.email && <AddPasswordRow email={data.email} />}+{identities.map((identity) => {const { identity_id, provider } = identityconst username = identity.identity_data?.user_namediff --git a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.utils.test.ts b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.utils.test.tsindex fffe0612f40..8a0d2f0ead3 100644--- a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.utils.test.ts+++ b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.utils.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { parseRedirectMessage } from './AccountIdentities.utils'+import { parseRedirectMessage, shouldShowAddPasswordRow } from './AccountIdentities.utils'describe('parseRedirectMessage', () => {it('drops the trailing sb marker and decodes + as spaces', () => {@@ -27,3 +27,49 @@ describe('parseRedirectMessage', () => {expect(parseRedirectMessage('/account/me#message=a%2Bb&sb=')).toBe('a+b')})})++describe('shouldShowAddPasswordRow', () => {+ const email = '[email protected]'++ it('shows the row for an OAuth-only user', () => {+ expect(shouldShowAddPasswordRow({ identities: [{ provider: 'github' }], email })).toBe(true)+ })++ it('shows the row when there are no identities at all', () => {+ expect(shouldShowAddPasswordRow({ identities: [], email })).toBe(true)+ })++ it('hides the row when an email identity already exists', () => {+ expect(shouldShowAddPasswordRow({ identities: [{ provider: 'email' }], email })).toBe(false)+ expect(+ shouldShowAddPasswordRow({+ identities: [{ provider: 'github' }, { provider: 'email' }],+ email,+ })+ ).toBe(false)+ })++ it('hides the row for SSO users', () => {+ expect(+ shouldShowAddPasswordRow({+ identities: [{ provider: 'sso:4d21b3cf-3a2f-44d3-b7d6-2b0dd393f671' }],+ email,+ })+ ).toBe(false)+ expect(+ shouldShowAddPasswordRow({+ identities: [{ provider: 'github' }, { provider: 'sso' }],+ email,+ })+ ).toBe(false)+ })++ it('hides the row when the user has no email', () => {+ expect(+ shouldShowAddPasswordRow({ identities: [{ provider: 'github' }], email: undefined })+ ).toBe(false)+ expect(shouldShowAddPasswordRow({ identities: [{ provider: 'github' }], email: '' })).toBe(+ false+ )+ })+})diff --git a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.utils.ts b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.utils.tsindex 842c102db1c..8c0baeed9c4 100644--- a/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.utils.ts+++ b/apps/studio/components/interfaces/Account/Preferences/AccountIdentities.utils.ts@@ -1,2 +1,21 @@export const parseRedirectMessage = (asPath: string) =>new URLSearchParams(asPath.split('#')[1] ?? '').get('message') ?? undefined++/**+ * Whether to offer creating a password (which creates an email identity) to a user+ * who signs in only through OAuth.+ */+export const shouldShowAddPasswordRow = ({+ identities,+ email,+}: {+ identities: { provider: string }[]+ email: string | undefined+}): boolean => {+ if (!email) return false++ const hasEmailIdentity = identities.some((identity) => identity.provider === 'email')+ const hasSsoIdentity = identities.some((identity) => identity.provider.startsWith('sso'))++ return !hasEmailIdentity && !hasSsoIdentity+}diff --git a/apps/studio/components/interfaces/Account/Preferences/AddPasswordRow.tsx b/apps/studio/components/interfaces/Account/Preferences/AddPasswordRow.tsxnew file mode 100644index 00000000000..825d034c785--- /dev/null+++ b/apps/studio/components/interfaces/Account/Preferences/AddPasswordRow.tsx@@ -0,0 +1,149 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { Eye, EyeOff } from 'lucide-react'+import { useState } from 'react'+import { useForm, useWatch } from 'react-hook-form'+import { toast } from 'sonner'+import {+ Button,+ CardContent,+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogSection,+ DialogTitle,+ Form,+ FormControl,+ FormField,+ Input,+} from 'ui'+import { Input as InputWithActions } from 'ui-patterns/DataInputs/Input'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { z } from 'zod'++import PasswordConditionsHelper from '@/components/interfaces/SignIn/PasswordConditionsHelper'+import { IdentityProviderIcon } from '@/components/ui/ProviderIcon'+import { useSetPasswordMutation } from '@/data/profile/profile-set-password-mutation'+import { getProviderDisplay } from '@/lib/external-identity-providers'+import { passwordValidation } from '@/lib/password-validation'++const FORM_ID = 'add-password-form'+const EMAIL_INPUT_ID = 'add-password-email'++const FormSchema = z.object({ password: passwordValidation })+type FormValues = z.infer<typeof FormSchema>++const defaultValues: FormValues = { password: '' }++/**+ * Offers a user without an email identity (OAuth-only account) a way to create one by setting a+ * password.+ *+ * Auth creates the email identity for the user's current email when the password is+ * saved.+ */+export const AddPasswordRow = ({ email }: { email: string }) => {+ const [isDialogOpen, setIsDialogOpen] = useState(false)+ const providerDisplay = getProviderDisplay('email')++ return (+ <>+ <CardContent className="flex justify-between items-center py-4">+ <div className="flex gap-x-4">+ <IdentityProviderIcon display={providerDisplay} size={30} />+ <div>+ <p className="text-sm">{providerDisplay.displayName}</p>+ <p className="text-sm text-foreground-lighter">{email}</p>+ </div>+ </div>+ <Button variant="default" onClick={() => setIsDialogOpen(true)}>+ Add password+ </Button>+ </CardContent>++ <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>+ <DialogContent>+ <DialogHeader className="border-b">+ <DialogTitle>Add password</DialogTitle>+ </DialogHeader>+ <AddPasswordForm email={email} onClose={() => setIsDialogOpen(false)} />+ </DialogContent>+ </Dialog>+ </>+ )+}++const AddPasswordForm = ({ email, onClose }: { email: string; onClose: () => void }) => {+ const [passwordHidden, setPasswordHidden] = useState(true)++ const form = useForm<FormValues>({+ resolver: zodResolver(FormSchema),+ defaultValues,+ mode: 'onChange',+ })+ const password = useWatch({ control: form.control, name: 'password' })++ const { mutate: setPassword, isPending } = useSetPasswordMutation({+ onSuccess: () => {+ toast.success('Password added successfully')+ onClose()+ },+ })++ const onSubmit = (values: FormValues) => setPassword({ password: values.password })++ return (+ <Form {...form}>+ <form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>+ <DialogSection className="flex flex-col gap-y-4">+ <FormItemLayout+ isReactForm={false}+ id={EMAIL_INPUT_ID}+ label="Email"+ description="Adding a password lets you sign in with this email address"+ >+ <Input id={EMAIL_INPUT_ID} disabled value={email} />+ </FormItemLayout>++ <FormField+ control={form.control}+ name="password"+ render={({ field }) => (+ <FormItemLayout label="Password">+ <FormControl>+ <InputWithActions+ id="password"+ type={passwordHidden ? 'password' : 'text'}+ placeholder="••••••••"+ disabled={isPending}+ autoComplete="new-password"+ actions={+ <Button+ icon={passwordHidden ? <Eye /> : <EyeOff />}+ variant="default"+ className="w-7"+ onClick={() => setPasswordHidden((prev) => !prev)}+ />+ }+ {...field}+ />+ </FormControl>+ </FormItemLayout>+ )}+ />++ <PasswordConditionsHelper password={password} />+ </DialogSection>++ <DialogFooter>+ <Button variant="default" disabled={isPending} onClick={onClose}>+ Cancel+ </Button>+ <Button type="submit" loading={isPending} disabled={isPending}>+ Add password+ </Button>+ </DialogFooter>+ </form>+ </Form>+ )+}diff --git a/apps/studio/components/interfaces/SignIn/ResetPasswordForm.tsx b/apps/studio/components/interfaces/SignIn/ResetPasswordForm.tsxindex c5257fd3afa..09b425ef49b 100644--- a/apps/studio/components/interfaces/SignIn/ResetPasswordForm.tsx+++ b/apps/studio/components/interfaces/SignIn/ResetPasswordForm.tsx@@ -13,20 +13,7 @@ import { z } from 'zod'import PasswordConditionsHelper from './PasswordConditionsHelper'import { captureCriticalError } from '@/lib/error-reporting'import { auth, getReturnToPath } from '@/lib/gotrue'--const passwordValidation = z- .string()- .min(1, 'Password is required')- .max(72, 'Password cannot exceed 72 characters')- .refine((password) => {- const hasUppercase = /[A-Z]/.test(password)- const hasLowercase = /[a-z]/.test(password)- const hasNumber = /[0-9]/.test(password)- const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};`':"\\|,.<>\/?]/.test(password)- const isLongEnough = password.length >= 8-- return hasUppercase && hasLowercase && hasNumber && hasSpecialChar && isLongEnough- }, 'Password must contain at least 8 characters, including uppercase, lowercase, number, and special character')+import { passwordValidation } from '@/lib/password-validation'const passwordSchema = z.object({currentPassword: z.string().min(1, 'Current password is required'),diff --git a/apps/studio/data/profile/profile-identities-query.ts b/apps/studio/data/profile/profile-identities-query.tsindex cb7260499c1..fc88b1e2a5b 100644--- a/apps/studio/data/profile/profile-identities-query.ts+++ b/apps/studio/data/profile/profile-identities-query.ts@@ -14,12 +14,13 @@ export async function getProfileIdentities() {if (error) throw errorif (!data.user) throw new Error('User not found with getUser()')- const { identities = [], new_email, email_change_sent_at } = data.user- return { identities, new_email, email_change_sent_at }+ const { identities = [], email, new_email, email_change_sent_at } = data.user+ return { identities, email, new_email, email_change_sent_at }}type ProfileIdentitiesData = {identities: (UserIdentity & { email?: string })[]+ email?: stringnew_email?: stringemail_change_sent_at?: string}diff --git a/apps/studio/data/profile/profile-set-password-mutation.ts b/apps/studio/data/profile/profile-set-password-mutation.tsnew file mode 100644index 00000000000..62437117c42--- /dev/null+++ b/apps/studio/data/profile/profile-set-password-mutation.ts@@ -0,0 +1,51 @@+import type { AuthError } from '@supabase/auth-js'+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { profileKeys } from './keys'+import { auth } from '@/lib/gotrue'++export type SetPasswordVariables = {+ password: string+}++async function setPassword({ password }: SetPasswordVariables) {+ const { data, error } = await auth.updateUser({ password })++ if (error) throw error+ return data+}++export type SetPasswordData = Awaited<ReturnType<typeof setPassword>>+export type SetPasswordError = AuthError++export const useSetPasswordMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<SetPasswordData, SetPasswordError, SetPasswordVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()+ return useMutation({+ mutationFn: (vars) => setPassword(vars),+ async onSuccess(data, variables, context) {+ // logout all other sessions after setting a password+ await auth.signOut({ scope: 'others' })+ await Promise.all([+ auth.refreshSession(),+ queryClient.invalidateQueries({ queryKey: profileKeys.identities() }),+ ])+ await onSuccess?.(data, variables, context)+ },+ async onError(error, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to add password: ${error.message}`)+ } else {+ onError(error, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/lib/password-validation.ts b/apps/studio/lib/password-validation.tsnew file mode 100644index 00000000000..cfe97f2ce32--- /dev/null+++ b/apps/studio/lib/password-validation.ts@@ -0,0 +1,15 @@+import { z } from 'zod'++export const passwordValidation = z+ .string()+ .min(1, 'Password is required')+ .max(72, 'Password cannot exceed 72 characters')+ .refine((password) => {+ const hasUppercase = /[A-Z]/.test(password)+ const hasLowercase = /[a-z]/.test(password)+ const hasNumber = /[0-9]/.test(password)+ const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};`':"\\|,.<>\/?]/.test(password)+ const isLongEnough = password.length >= 8++ return hasUppercase && hasLowercase && hasNumber && hasSpecialChar && isLongEnough+ }, 'Password must contain at least 8 characters, including uppercase, lowercase, number, and special character')diff --git a/apps/studio/pages/account/me.tsx b/apps/studio/pages/account/me.tsxindex f069bdee82c..0e24daaa36f 100644--- a/apps/studio/pages/account/me.tsx+++ b/apps/studio/pages/account/me.tsx@@ -150,7 +150,7 @@ const ProfileLoadingSections = ({<PageSection><PageSectionMeta><PageSectionSummary>- <PageSectionTitle>Account identities</PageSectionTitle>+ <PageSectionTitle>Sign-in methods</PageSectionTitle><PageSectionDescription>Manage the providers linked to your Supabase account and update their details.</PageSectionDescription>