The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Refactor policies page
Joshen Lima258844ba622
diff --git a/studio/components/interfaces/Auth/Policies/Policies.tsx b/studio/components/interfaces/Auth/Policies/Policies.tsxnew file mode 100644index 00000000000..d734e40500d--- /dev/null+++ b/studio/components/interfaces/Auth/Policies/Policies.tsx@@ -0,0 +1,215 @@+import { useState, FC } from 'react'+import { isEmpty } from 'lodash'+import { IconHelpCircle } from 'ui'+import { useRouter } from 'next/router'+import { observer } from 'mobx-react-lite'+import { useParams, useStore } from 'hooks'+import { PolicyEditorModal, PolicyTableRow } from 'components/interfaces/Auth/Policies'+import { PostgresRole } from '@supabase/postgres-meta'++import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'+import NoTableState from 'components/ui/States/NoTableState'+import NoSearchResults from 'components/to-be-cleaned/NoSearchResults'+import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'+import InformationBox from 'components/ui/InformationBox'++interface Props {+ tables: any[]+ hasPublicTables: boolean+}++const Policies: FC<Props> = ({ tables, hasPublicTables }) => {+ const router = useRouter()+ const { ref } = useParams()++ const { ui, meta } = useStore()+ const roles = meta.roles.list((role: PostgresRole) => !meta.roles.systemRoles.includes(role.name))++ const [selectedSchemaAndTable, setSelectedSchemaAndTable] = useState<any>({})+ const [selectedTableToToggleRLS, setSelectedTableToToggleRLS] = useState<any>({})+ const [selectedPolicyToEdit, setSelectedPolicyToEdit] = useState<any>({})+ const [selectedPolicyToDelete, setSelectedPolicyToDelete] = useState<any>({})++ const closePolicyEditorModal = () => {+ setSelectedPolicyToEdit({})+ setSelectedSchemaAndTable({})+ }++ const closeConfirmModal = () => {+ setSelectedPolicyToDelete({})+ setSelectedTableToToggleRLS({})+ }++ const onSelectToggleRLS = (table: any) => {+ setSelectedTableToToggleRLS(table)+ }++ const onSelectCreatePolicy = (table: any) => {+ setSelectedSchemaAndTable({ schema: table.schema, table: table.name })+ }++ const onSelectEditPolicy = (policy: any) => {+ setSelectedPolicyToEdit(policy)+ setSelectedSchemaAndTable({ schema: policy.schema, table: policy.table })+ }++ const onSelectDeletePolicy = (policy: any) => {+ setSelectedPolicyToDelete(policy)+ }++ const onSavePolicySuccess = async () => {+ ui.setNotification({ category: 'success', message: 'Policy successfully saved!' })+ closePolicyEditorModal()+ }++ // Methods that involve some API+ const onToggleRLS = async () => {+ const payload = {+ id: selectedTableToToggleRLS.id,+ rls_enabled: !selectedTableToToggleRLS.rls_enabled,+ }++ const res: any = await meta.tables.update(payload.id, payload)+ if (res.error) {+ ui.setNotification({+ category: 'error',+ message: `Failed to toggle RLS: ${res.error.message}`,+ })+ }+ closeConfirmModal()+ }++ const onCreatePolicy = async (payload: any) => {+ const res = await meta.policies.create(payload)+ if (res.error) {+ ui.setNotification({+ category: 'error',+ message: `Error adding policy: ${res.error.message}`,+ })+ return true+ }+ return false+ }++ const onUpdatePolicy = async (payload: any) => {+ const res = await meta.policies.update(payload.id, payload)+ if (res.error) {+ ui.setNotification({+ category: 'error',+ message: `Error updating policy: ${res.error.message}`,+ })+ return true+ }+ return false+ }++ const onDeletePolicy = async () => {+ const res = await meta.policies.del(selectedPolicyToDelete.id)+ if (typeof res !== 'boolean' && res.error) {+ ui.setNotification({+ category: 'error',+ message: `Error deleting policy: ${res.error.message}`,+ })+ } else {+ ui.setNotification({ category: 'success', message: 'Successfully deleted policy!' })+ }+ closeConfirmModal()+ }++ if (!hasPublicTables)+ return <NoTableState message="Create a table first before writing a policy" />++ return (+ <>+ {tables.length > 0 ? (+ tables.map((table: any) => (+ <section key={table.id}>+ <PolicyTableRow+ table={table}+ onSelectToggleRLS={onSelectToggleRLS}+ onSelectCreatePolicy={onSelectCreatePolicy}+ onSelectEditPolicy={onSelectEditPolicy}+ onSelectDeletePolicy={onSelectDeletePolicy}+ />+ </section>+ ))+ ) : hasPublicTables ? (+ <NoSearchResults />+ ) : (+ <div className="flex-grow">+ <ProductEmptyState+ size="large"+ title="Postgres Policies"+ ctaButtonLabel="Create a table"+ infoButtonLabel="What is RLS?"+ infoButtonUrl="https://supabase.com/docs/guides/auth/row-level-security"+ onClickCta={() => router.push(`/project/${ref}/editor`)}+ >+ <div className="space-y-4">+ <InformationBox+ title="What are policies?"+ icon={<IconHelpCircle strokeWidth={2} />}+ description={+ <div className="space-y-2">+ <p className="text-sm">+ Policies restrict, on a per-user basis, which rows can be returned by normal+ queries, or inserted, updated, or deleted by data modification commands.+ </p>+ <p className="text-sm">+ This is also known as Row-Level Security (RLS). Each policy is attached to a+ table, and the policy is executed each time its accessed.+ </p>+ </div>+ }+ />+ <p className="text-sm text-scale-1100">+ A table within the public schema is required before you can create a Row-Level+ Security policy.+ </p>+ </div>+ </ProductEmptyState>+ </div>+ )}++ <PolicyEditorModal+ visible={!isEmpty(selectedSchemaAndTable)}+ roles={roles}+ schema={selectedSchemaAndTable.schema}+ table={selectedSchemaAndTable.table}+ selectedPolicyToEdit={selectedPolicyToEdit}+ onSelectCancel={closePolicyEditorModal}+ // @ts-ignore+ onCreatePolicy={onCreatePolicy}+ // @ts-ignore+ onUpdatePolicy={onUpdatePolicy}+ onSaveSuccess={onSavePolicySuccess}+ />++ <ConfirmModal+ danger+ visible={!isEmpty(selectedPolicyToDelete)}+ title="Confirm to delete policy"+ description={`This is permanent! Are you sure you want to delete the policy "${selectedPolicyToDelete.name}"`}+ buttonLabel="Delete"+ buttonLoadingLabel="Deleting"+ onSelectCancel={closeConfirmModal}+ onSelectConfirm={onDeletePolicy}+ />++ <ConfirmModal+ danger={selectedTableToToggleRLS.rls_enabled}+ visible={!isEmpty(selectedTableToToggleRLS)}+ title={`Confirm to ${selectedTableToToggleRLS.rls_enabled ? 'disable' : 'enable'} RLS`}+ description={`Are you sure you want to ${+ selectedTableToToggleRLS.rls_enabled ? 'disable' : 'enable'+ } row level security for the table "${selectedTableToToggleRLS.name}"?`}+ buttonLabel="Confirm"+ buttonLoadingLabel="Saving"+ onSelectCancel={closeConfirmModal}+ onSelectConfirm={onToggleRLS}+ />+ </>+ )+}++export default observer(Policies)diff --git a/studio/components/interfaces/Auth/Policies/index.tsx b/studio/components/interfaces/Auth/Policies/index.tsxindex f1cd35fac60..129075d7344 100644--- a/studio/components/interfaces/Auth/Policies/index.tsx+++ b/studio/components/interfaces/Auth/Policies/index.tsx@@ -1,7 +1,8 @@+import Policies from './Policies'import PolicyEditorModal from './PolicyEditorModal'import PolicyTableRow from './PolicyTableRow'import PolicySelection from './PolicySelection'import PolicyTemplates from './PolicyTemplates'export * from './Policies.constants'-export { PolicyEditorModal, PolicyTableRow, PolicySelection, PolicyTemplates }+export { Policies, PolicyEditorModal, PolicyTableRow, PolicySelection, PolicyTemplates }diff --git a/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsxindex 6329a56ae4c..b9a68c8aa27 100644--- a/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx+++ b/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx@@ -225,7 +225,6 @@ const TableEditor: FC<Props> = ({withIconvariant="warning"className="!px-4 !py-3 mt-3"- // @ts-ignoretitle="Turning off RLS means that you are allowing anonymous access to your table">As such, anyone with the anonymous key can modify or delete your data.diff --git a/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsxindex 1bc51c408ae..65ca74e668a 100644--- a/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx+++ b/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx@@ -1,5 +1,4 @@import { FC, useEffect, useState } from 'react'-import { useRouter } from 'next/router'import Link from 'next/link'import { partition } from 'lodash'import { observer } from 'mobx-react-lite'@@ -10,6 +9,7 @@ import {IconCopy,IconEdit,IconLoader,+ IconLock,IconRefreshCw,IconSearch,IconTrash,@@ -23,7 +23,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { PostgresSchema, PostgresTable } from '@supabase/postgres-meta'import Base64 from 'lib/base64'-import { checkPermissions, useStore } from 'hooks'+import { checkPermissions, useStore, useParams } from 'hooks'import { SchemaView } from './TableEditorLayout.types'import ProductMenuItem from 'components/ui/ProductMenu/ProductMenuItem'@@ -44,11 +44,9 @@ const TableEditorMenu: FC<Props> = ({onDeleteTable = () => {},onDuplicateTable = () => {},}) => {- const { meta, ui } = useStore()- const router = useRouter()- const { id } = router.query+ const { meta } = useStore()+ const { id, ref } = useParams()- const projectRef = ui.selectedProject?.refconst schemas: PostgresSchema[] = meta.schemas.list()const tables: PostgresTable[] = meta.tables.list((table: PostgresTable) => table.schema === selectedSchema@@ -67,15 +65,10 @@ const TableEditorMenu: FC<Props> = ({// We may need to shift this to the schema store and do something like meta.schema.loadViews()// I don't need we need a separate store for viewsuseEffect(() => {- let cancel = falseconst fetchViews = async (selectedSchema: string) => {await meta.schemas.loadViews(selectedSchema)}if (selectedSchema) fetchViews(selectedSchema)-- return () => {- cancel = true- }}, [selectedSchema])const refreshTables = async () => {@@ -258,7 +251,7 @@ const TableEditorMenu: FC<Props> = ({return (<ProductMenuItemkey={table.name}- url={`/project/${projectRef}/editor/${table.id}`}+ url={`/project/${ref}/editor/${table.id}`}name={table.name}hoverText={table.comment ? table.comment : table.name}isActive={isActive}@@ -284,6 +277,13 @@ const TableEditorMenu: FC<Props> = ({>Duplicate Table</Dropdown.Item>,+ <Link href={`/project/${ref}/auth/policies?search=${table.id}`}>+ <a>+ <Dropdown.Item key="delete-table" icon={<IconLock size="tiny" />}>+ View Policies+ </Dropdown.Item>+ </a>+ </Link>,<Dropdown.Separator key="separator" />,<Dropdown.Itemkey="delete-table"@@ -324,7 +324,7 @@ const TableEditorMenu: FC<Props> = ({const viewId = Base64.encode(JSON.stringify(view))const isActive = id === viewIdreturn (- <Link key={viewId} href={`/project/${projectRef}/editor/${viewId}`}>+ <Link key={viewId} href={`/project/${ref}/editor/${viewId}`}><a><Menu.Item key={viewId} rounded active={isActive}><div className="flex justify-between">@@ -356,7 +356,7 @@ const TableEditorMenu: FC<Props> = ({{filteredForeignTables.map((table: Partial<PostgresTable>) => {const isActive = Number(id) === table.idreturn (- <Link key={table.id} href={`/project/${projectRef}/editor/${table.id}`}>+ <Link key={table.id} href={`/project/${ref}/editor/${table.id}`}><a><Menu.Item key={table.id} rounded active={isActive}><div className="flex justify-between">diff --git a/studio/pages/project/[ref]/auth/policies.tsx b/studio/pages/project/[ref]/auth/policies.tsxindex 26a0ceb74ea..9d52be5eee7 100644--- a/studio/pages/project/[ref]/auth/policies.tsx+++ b/studio/pages/project/[ref]/auth/policies.tsx@@ -1,22 +1,14 @@-import React, { useState, FC } from 'react'-import { isEmpty } from 'lodash'-import { Button, IconSearch, Input, IconHelpCircle, IconExternalLink } from 'ui'-import { useRouter } from 'next/router'+import { useState, useEffect } from 'react'+import { Button, IconSearch, Input, IconExternalLink } from 'ui'import { observer } from 'mobx-react-lite'-import { checkPermissions, useStore } from 'hooks'-import { AuthLayout } from 'components/layouts'-import { NextPageWithLayout } from 'types'-import { PolicyEditorModal, PolicyTableRow } from 'components/interfaces/Auth/Policies'-import { PostgresRole } from '@supabase/postgres-meta'import { PostgresTable, PostgresPolicy } from '@supabase/postgres-meta'--import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'-import NoTableState from 'components/ui/States/NoTableState'-import NoSearchResults from 'components/to-be-cleaned/NoSearchResults'import { PermissionAction } from '@supabase/shared-types/out/constants'++import { NextPageWithLayout } from 'types'+import { checkPermissions, useParams, useStore } from 'hooks'+import { AuthLayout } from 'components/layouts'+import { Policies } from 'components/interfaces/Auth/Policies'import NoPermission from 'components/ui/NoPermission'-import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'-import InformationBox from 'components/ui/InformationBox'/*** Filter tables by table name and policy name@@ -39,13 +31,15 @@ const onFilterTables = (const findSearchString = (s: string) => s.toLowerCase().includes(filter)// @ts-ignore Type instantiation is excessively deep and possibly infiniteconst filteredPolicies = policies.filter((p: PostgresPolicy) => findSearchString(p.name))+return tables.slice().filter((x: PostgresTable) => {- const searchTableName = findSearchString(x.name)- if (searchTableName) return true- const searchPolicyName = filteredPolicies.some((p: PostgresPolicy) => p.table === x.name)- return searchPolicyName+ return (+ x.name.toLowerCase().includes(filter) ||+ x.id.toString() === filter ||+ filteredPolicies.some((p: PostgresPolicy) => p.table === x.name)+ )}).sort((a: PostgresTable, b: PostgresTable) => a.name.localeCompare(b.name))}@@ -53,8 +47,13 @@ const onFilterTables = (const AuthPoliciesPage: NextPageWithLayout = () => {const { meta } = useStore()+ const { search } = useParams()+ const [policiesFilter, setPoliciesFilter] = useState<string>('')++ useEffect(() => {+ if (search) setPoliciesFilter(search)+ }, [search])- const [policiesFilter, setPoliciesFilter] = useState<string | undefined>(undefined)const publicTables = meta.tables.list((table: { schema: string }) => table.schema === 'public')const policies = meta.policies.list()const filteredTables = onFilterTables(publicTables, policies, policiesFilter)@@ -89,7 +88,7 @@ const AuthPoliciesPage: NextPageWithLayout = () => {</div></div>)}- <AuthPoliciesTables hasPublicTables={publicTables.length > 0} tables={filteredTables} />+ <Policies hasPublicTables={publicTables.length > 0} tables={filteredTables} /></div>)}@@ -101,198 +100,3 @@ AuthPoliciesPage.getLayout = (page) => ()export default observer(AuthPoliciesPage)--interface AuthPoliciesTablesProps {- hasPublicTables: boolean- tables: any[]-}-const AuthPoliciesTables: FC<AuthPoliciesTablesProps> = observer(({ tables, hasPublicTables }) => {- const router = useRouter()- const { ref } = router.query-- const { ui, meta } = useStore()- const roles = meta.roles.list((role: PostgresRole) => !meta.roles.systemRoles.includes(role.name))-- const [selectedSchemaAndTable, setSelectedSchemaAndTable] = useState<any>({})- const [selectedTableToToggleRLS, setSelectedTableToToggleRLS] = useState<any>({})- const [selectedPolicyToEdit, setSelectedPolicyToEdit] = useState<any>({})- const [selectedPolicyToDelete, setSelectedPolicyToDelete] = useState<any>({})-- const closePolicyEditorModal = () => {- setSelectedPolicyToEdit({})- setSelectedSchemaAndTable({})- }-- const closeConfirmModal = () => {- setSelectedPolicyToDelete({})- setSelectedTableToToggleRLS({})- }-- const onSelectToggleRLS = (table: any) => {- setSelectedTableToToggleRLS(table)- }-- const onSelectCreatePolicy = (table: any) => {- setSelectedSchemaAndTable({ schema: table.schema, table: table.name })- }-- const onSelectEditPolicy = (policy: any) => {- setSelectedPolicyToEdit(policy)- setSelectedSchemaAndTable({ schema: policy.schema, table: policy.table })- }-- const onSelectDeletePolicy = (policy: any) => {- setSelectedPolicyToDelete(policy)- }-- const onSavePolicySuccess = async () => {- ui.setNotification({ category: 'success', message: 'Policy successfully saved!' })- closePolicyEditorModal()- }-- // Methods that involve some API- const onToggleRLS = async () => {- const payload = {- id: selectedTableToToggleRLS.id,- rls_enabled: !selectedTableToToggleRLS.rls_enabled,- }-- const res: any = await meta.tables.update(payload.id, payload)- if (res.error) {- ui.setNotification({- category: 'error',- message: `Failed to toggle RLS: ${res.error.message}`,- })- }- closeConfirmModal()- }-- const onCreatePolicy = async (payload: any) => {- const res = await meta.policies.create(payload)- if (res.error) {- ui.setNotification({- category: 'error',- message: `Error adding policy: ${res.error.message}`,- })- return true- }- return false- }-- const onUpdatePolicy = async (payload: any) => {- const res = await meta.policies.update(payload.id, payload)- if (res.error) {- ui.setNotification({- category: 'error',- message: `Error updating policy: ${res.error.message}`,- })- return true- }- return false- }-- const onDeletePolicy = async () => {- const res = await meta.policies.del(selectedPolicyToDelete.id)- if (typeof res !== 'boolean' && res.error) {- ui.setNotification({- category: 'error',- message: `Error deleting policy: ${res.error.message}`,- })- } else {- ui.setNotification({ category: 'success', message: 'Successfully deleted policy!' })- }- closeConfirmModal()- }-- return (- <>- {tables.length > 0 ? (- tables.map((table: any) => (- <section key={table.id}>- <PolicyTableRow- table={table}- onSelectToggleRLS={onSelectToggleRLS}- onSelectCreatePolicy={onSelectCreatePolicy}- onSelectEditPolicy={onSelectEditPolicy}- onSelectDeletePolicy={onSelectDeletePolicy}- />- </section>- ))- ) : hasPublicTables ? (- <NoSearchResults />- ) : (- <div className="flex-grow">- <ProductEmptyState- size="large"- title="Postgres Policies"- ctaButtonLabel="Create a table"- infoButtonLabel="What is RLS?"- infoButtonUrl="https://supabase.com/docs/guides/auth/row-level-security"- onClickCta={() => router.push(`/project/${ref}/editor`)}- >- <div className="space-y-4">- <InformationBox- title="What are policies?"- icon={<IconHelpCircle strokeWidth={2} />}- description={- <div className="space-y-2">- <p className="text-sm">- Policies restrict, on a per-user basis, which rows can be returned by normal- queries, or inserted, updated, or deleted by data modification commands.- </p>- <p className="text-sm">- This is also known as Row-Level Security (RLS). Each policy is attached to a- table, and the policy is executed each time its accessed.- </p>- </div>- }- />- <p className="text-sm text-scale-1100">- A table within the public schema is required before you can create a Row-Level- Security policy.- </p>- </div>- </ProductEmptyState>- </div>- )}-- <PolicyEditorModal- visible={!isEmpty(selectedSchemaAndTable)}- roles={roles}- schema={selectedSchemaAndTable.schema}- table={selectedSchemaAndTable.table}- selectedPolicyToEdit={selectedPolicyToEdit}- onSelectCancel={closePolicyEditorModal}- // @ts-ignore- onCreatePolicy={onCreatePolicy}- // @ts-ignore- onUpdatePolicy={onUpdatePolicy}- onSaveSuccess={onSavePolicySuccess}- />-- <ConfirmModal- danger- visible={!isEmpty(selectedPolicyToDelete)}- title="Confirm to delete policy"- description={`This is permanent! Are you sure you want to delete the policy "${selectedPolicyToDelete.name}"`}- buttonLabel="Delete"- buttonLoadingLabel="Deleting"- onSelectCancel={closeConfirmModal}- onSelectConfirm={onDeletePolicy}- />-- <ConfirmModal- danger={selectedTableToToggleRLS.rls_enabled}- visible={!isEmpty(selectedTableToToggleRLS)}- title={`Confirm to ${selectedTableToToggleRLS.rls_enabled ? 'disable' : 'enable'} RLS`}- description={`Are you sure you want to ${- selectedTableToToggleRLS.rls_enabled ? 'disable' : 'enable'- } row level security for the table "${selectedTableToToggleRLS.name}"?`}- buttonLabel="Confirm"- buttonLoadingLabel="Saving"- onSelectCancel={closeConfirmModal}- onSelectConfirm={onToggleRLS}- />- </>- )-})