Skip to content

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

feat: create users in dashboard

Alaister Younged6ae142755c
diff --git a/studio/components/interfaces/Auth/Users/CreateUserModal.tsx b/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
new file mode 100644
index 00000000000..ac28c20da8c
--- /dev/null
+++ b/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
@@ -0,0 +1,189 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { observer } from 'mobx-react-lite'
+import { useContext, useState } from 'react'
+import { Button, Checkbox, Form, IconLock, IconMail, IconPlus, Input, Loading, Modal } from 'ui'
+
+import { useUserCreateMutation } from 'data/auth/user-create-mutation'
+import { useProjectApiQuery } from 'data/config/project-api-query'
+import { checkPermissions, useStore } from 'hooks'
+import { PageContext } from 'pages/project/[ref]/auth/users'
+
+const CreateUserModal = () => {
+ const { ui } = useStore()
+ const PageState: any = useContext(PageContext)
+ const projectRef = PageState.projectRef
+
+ const [visible, setVisible] = useState(false)
+
+ const { data, isLoading, isSuccess } = useProjectApiQuery({ projectRef }, { enabled: visible })
+
+ const handleToggle = () => setVisible(!visible)
+ const canCreateUsers = checkPermissions(PermissionAction.AUTH_EXECUTE, 'create_user')
+
+ const validate = (values: any) => {
+ const errors: any = {}
+ const emailValidateRegex =
+ /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
+
+ if (values.email.length === 0) {
+ errors.email = 'Please enter a valid email'
+ } else if (!emailValidateRegex.test(values.email)) {
+ errors.email = `${values.email} is an invalid email`
+ }
+
+ if (!values.password?.trim()) {
+ errors.password = 'Please enter a password'
+ }
+
+ return errors
+ }
+
+ const { mutateAsync: createUser } = useUserCreateMutation({
+ async onSuccess() {
+ await PageState.fetchData(1)
+ },
+ })
+
+ const onCreateUser = async (values: any, { setSubmitting }: any) => {
+ if (!isSuccess) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to create user: Error loading project config`,
+ })
+
+ return
+ }
+
+ const { protocol, endpoint, serviceApiKey } = data.autoApiService
+
+ setSubmitting(true)
+
+ try {
+ await createUser({
+ endpoint,
+ protocol,
+ serviceApiKey,
+ user: values,
+ })
+
+ ui.setNotification({
+ category: 'success',
+ message: `Created user: ${values.email}`,
+ })
+
+ setVisible(false)
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to create user: ${error.message}`,
+ })
+ }
+
+ setSubmitting(false)
+ }
+
+ return (
+ <div>
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <Button as="span" onClick={handleToggle} icon={<IconPlus />} disabled={!canCreateUsers}>
+ Create
+ </Button>
+ </Tooltip.Trigger>
+
+ {!canCreateUsers && (
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-scale-100 py-1 px-2 leading-none shadow',
+ 'border border-scale-200',
+ ].join(' ')}
+ >
+ <span className="text-xs text-scale-1200">
+ You need additional permissions to create users
+ </span>
+ </div>
+ </Tooltip.Content>
+ )}
+ </Tooltip.Root>
+
+ <Modal
+ closable
+ hideFooter
+ size="small"
+ key="create-user-modal"
+ visible={visible}
+ header="Create a new user"
+ onCancel={handleToggle}
+ loading={true}
+ >
+ <Form
+ validateOnBlur
+ initialValues={{ email: '', password: '', autoConfirmUser: true }}
+ validate={validate}
+ onSubmit={onCreateUser}
+ >
+ {({ isSubmitting }: { isSubmitting: boolean }) => (
+ <Loading active={isLoading}>
+ <div className="space-y-6 py-4">
+ <Modal.Content>
+ <div className="space-y-4">
+ <Input
+ autoFocus
+ id="email"
+ autoComplete="off"
+ label="User Email"
+ icon={<IconMail />}
+ type="email"
+ name="email"
+ placeholder="[email protected]"
+ disabled={isSubmitting || isLoading}
+ />
+
+ <Input
+ id="password"
+ name="password"
+ type="password"
+ label="User Password"
+ placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;"
+ icon={<IconLock />}
+ disabled={isSubmitting || isLoading}
+ autoComplete="new-password"
+ />
+
+ <Checkbox
+ value="true"
+ id="autoConfirmUser"
+ name="autoConfirmUser"
+ label="Auto Confirm User?"
+ size="medium"
+ description="Creates the user without sending them a confirmation email"
+ defaultChecked={true}
+ disabled={isSubmitting || isLoading}
+ />
+ </div>
+ </Modal.Content>
+
+ <Modal.Content>
+ <Button
+ block
+ size="small"
+ htmlType="submit"
+ loading={isSubmitting}
+ disabled={!canCreateUsers || isSubmitting || isLoading}
+ >
+ Create user
+ </Button>
+ </Modal.Content>
+ </div>
+ </Loading>
+ )}
+ </Form>
+ </Modal>
+ </div>
+ )
+}
+
+export default observer(CreateUserModal)
diff --git a/studio/components/interfaces/Auth/Users/Users.tsx b/studio/components/interfaces/Auth/Users/Users.tsx
index 6f726cb8c4c..28eb4b785c6 100644
--- a/studio/components/interfaces/Auth/Users/Users.tsx
+++ b/studio/components/interfaces/Auth/Users/Users.tsx
@@ -7,6 +7,7 @@ import { IS_PLATFORM } from 'lib/constants'
import { PageContext } from 'pages/project/[ref]/auth/users'
import UsersList from './UsersList'
import InviteUserModal from './InviteUserModal'
+import CreateUserModal from './CreateUserModal'
const Users = () => {
const PageState: any = useContext(PageContext)
@@ -94,9 +95,8 @@ const Users = () => {
</Listbox.Option>
</Listbox>
</div>
- <div className="mt-4 flex items-center md:mt-0">
+ <div className="mt-4 flex items-center gap-2 md:mt-0">
<Button
- className="mr-2"
size="tiny"
icon={<IconRefreshCw />}
type="default"
@@ -106,6 +106,7 @@ const Users = () => {
Reload
</Button>
{inviteEnabled && <InviteUserModal />}
+ <CreateUserModal />
</div>
</div>
<section className="users-table-container mt-4 overflow-visible px-6">
diff --git a/studio/data/auth/user-create-mutation.ts b/studio/data/auth/user-create-mutation.ts
new file mode 100644
index 00000000000..8b41d9612a3
--- /dev/null
+++ b/studio/data/auth/user-create-mutation.ts
@@ -0,0 +1,47 @@
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+
+export type UserCreateVariables = {
+ protocol: string
+ endpoint: string
+ serviceApiKey: string
+ user: {
+ email: string
+ password: string
+ autoConfirmUser: string
+ }
+}
+
+export async function createUser({ protocol, endpoint, serviceApiKey, user }: UserCreateVariables) {
+ const response = await post(
+ `${protocol}://${endpoint}/auth/v1/admin/users`,
+ {
+ email: user.email,
+ password: user.password,
+ email_confirm: user.autoConfirmUser,
+ },
+ {
+ headers: {
+ apikey: serviceApiKey,
+ Authorization: `Bearer ${serviceApiKey}`,
+ },
+ credentials: 'omit',
+ }
+ )
+ if (response.error) {
+ throw response.error
+ }
+
+ return response
+}
+
+type UserCreateData = Awaited<ReturnType<typeof createUser>>
+
+export const useUserCreateMutation = (
+ options: Omit<UseMutationOptions<UserCreateData, unknown, UserCreateVariables>, 'mutationFn'> = {}
+) => {
+ return useMutation<UserCreateData, unknown, UserCreateVariables>(
+ (vars) => createUser(vars),
+ options
+ )
+}
diff --git a/studio/data/config/keys.ts b/studio/data/config/keys.ts
index 875848a4247..baa6c204ebd 100644
--- a/studio/data/config/keys.ts
+++ b/studio/data/config/keys.ts
@@ -1,3 +1,4 @@
export const configKeys = {
settings: (projectRef: string | undefined) => ['projects', projectRef, 'settings'] as const,
+ api: (projectRef: string | undefined) => ['projects', projectRef, 'settings', 'api'] as const,
}
diff --git a/studio/data/config/project-api-query.ts b/studio/data/config/project-api-query.ts
new file mode 100644
index 00000000000..5fc7d414364
--- /dev/null
+++ b/studio/data/config/project-api-query.ts
@@ -0,0 +1,117 @@
+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { useCallback } from 'react'
+import { configKeys } from './keys'
+
+export type ProjectApiVariables = {
+ projectRef?: string
+}
+
+export type Project = {
+ id: number
+ name: string
+ ref: string
+ status: string
+ db_host: string
+ db_name: string
+ db_user: string
+ db_schema: string
+ db_port: number
+ db_ssl: boolean
+ services: Service[]
+}
+
+export type App = {
+ id: number
+ name: string
+}
+
+export type AppConfig = {
+ endpoint: string
+ db_schema: string
+ realtime_multitenant_enabled: boolean
+}
+
+export type Service = {
+ id: number
+ name: string
+ app_config: AppConfig
+ app: App
+ service_api_keys: ServiceApiKey[]
+}
+
+export type ServiceApiKey = {
+ api_key_encrypted: string
+ tags: string
+ name: string
+}
+
+export type AutoApiService = Service & {
+ protocol: 'https' | 'http'
+ endpoint: string
+ restUrl: string
+ project: Project
+ defaultApiKey: string
+ serviceApiKey: string
+}
+
+export type ProjectApiResponse = {
+ project: Project
+ autoApiService: AutoApiService
+}
+
+export async function getProjectApi({ projectRef }: ProjectApiVariables, signal?: AbortSignal) {
+ if (!projectRef) {
+ throw new Error('projectRef is required')
+ }
+
+ const response = await get(`${API_URL}/props/project/${projectRef}/api`, {
+ signal,
+ })
+ if (response.error) {
+ throw response.error
+ }
+
+ return response as ProjectApiResponse
+}
+
+export type ProjectApiData = Awaited<ReturnType<typeof getProjectApi>>
+export type ProjectApiError = unknown
+
+export const useProjectApiQuery = <TData = ProjectApiData>(
+ { projectRef }: ProjectApiVariables,
+ { enabled = true, ...options }: UseQueryOptions<ProjectApiData, ProjectApiError, TData> = {}
+) =>
+ useQuery<ProjectApiData, ProjectApiError, TData>(
+ configKeys.api(projectRef),
+ ({ signal }) => getProjectApi({ projectRef }, signal),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ refetchInterval(data, query) {
+ if (!data) {
+ return false
+ }
+
+ const { autoApiService } = data as unknown as ProjectApiData
+
+ const apiKeys = autoApiService?.service_api_keys ?? []
+ const interval = apiKeys.length === 0 ? 2000 : 0
+
+ return interval
+ },
+ ...options,
+ }
+ )
+
+export const useProjectApiPrefetch = ({ projectRef }: ProjectApiVariables) => {
+ const client = useQueryClient()
+
+ return useCallback(() => {
+ if (projectRef) {
+ client.prefetchQuery(configKeys.api(projectRef), ({ signal }) =>
+ getProjectApi({ projectRef }, signal)
+ )
+ }
+ }, [projectRef])
+}