From ed6ae142755c46af556a0c493dc44afa81a5c803 Mon Sep 17 00:00:00 2001 From: Alaister Young Date: Tue, 31 Jan 2023 23:01:21 +1100 Subject: [PATCH 1/2] feat: create users in dashboard --- .../interfaces/Auth/Users/CreateUserModal.tsx | 189 ++++++++++++++++++ .../interfaces/Auth/Users/Users.tsx | 5 +- studio/data/auth/user-create-mutation.ts | 47 +++++ studio/data/config/keys.ts | 1 + studio/data/config/project-api-query.ts | 117 +++++++++++ 5 files changed, 357 insertions(+), 2 deletions(-) create mode 100644 studio/components/interfaces/Auth/Users/CreateUserModal.tsx create mode 100644 studio/data/auth/user-create-mutation.ts create mode 100644 studio/data/config/project-api-query.ts 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 ( +
+ + + + + + {!canCreateUsers && ( + + +
+ + You need additional permissions to create users + +
+
+ )} +
+ + +
+ {({ isSubmitting }: { isSubmitting: boolean }) => ( + +
+ +
+ } + type="email" + name="email" + placeholder="user@example.com" + disabled={isSubmitting || isLoading} + /> + + } + disabled={isSubmitting || isLoading} + autoComplete="new-password" + /> + + +
+
+ + + + +
+
+ )} +
+
+
+ ) +} + +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 = () => { -
+
{inviteEnabled && } +
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> + +export const useUserCreateMutation = ( + options: Omit, 'mutationFn'> = {} +) => { + return useMutation( + (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> +export type ProjectApiError = unknown + +export const useProjectApiQuery = ( + { projectRef }: ProjectApiVariables, + { enabled = true, ...options }: UseQueryOptions = {} +) => + useQuery( + 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]) +} From 6ebdd8885f1ae6b40d3866f64d073a65b100caf0 Mon Sep 17 00:00:00 2001 From: Alaister Young Date: Wed, 1 Feb 2023 21:25:20 +1100 Subject: [PATCH 2/2] move add/invite user into dropdown --- .../interfaces/Auth/Users/AddUserDropdown.tsx | 108 +++++++++++ .../interfaces/Auth/Users/CreateUserModal.tsx | 177 ++++++++---------- .../interfaces/Auth/Users/InviteUserModal.tsx | 47 ++--- .../interfaces/Auth/Users/Users.tsx | 20 +- 4 files changed, 203 insertions(+), 149 deletions(-) create mode 100644 studio/components/interfaces/Auth/Users/AddUserDropdown.tsx diff --git a/studio/components/interfaces/Auth/Users/AddUserDropdown.tsx b/studio/components/interfaces/Auth/Users/AddUserDropdown.tsx new file mode 100644 index 00000000000..29505af9dab --- /dev/null +++ b/studio/components/interfaces/Auth/Users/AddUserDropdown.tsx @@ -0,0 +1,108 @@ +import * as Tooltip from '@radix-ui/react-tooltip' +import { PermissionAction } from '@supabase/shared-types/out/constants' +import { checkPermissions } from 'hooks' +import { IS_PLATFORM } from 'lib/constants' +import { useState } from 'react' +import semver from 'semver' +import { Button, Dropdown, IconMail, IconPlus, IconUserPlus } from 'ui' +import CreateUserModal from './CreateUserModal' +import InviteUserModal from './InviteUserModal' + +export type AddUserDropdownProps = { + projectKpsVersion?: string +} + +const AddUserDropdown = ({ projectKpsVersion }: AddUserDropdownProps) => { + const inviteEnabled = IS_PLATFORM + ? semver.gte( + // @ts-ignore + semver.coerce(projectKpsVersion ?? 'kps-v2.5.4'), + semver.coerce('kps-v2.5.3') + ) + : true + + const canInviteUsers = checkPermissions(PermissionAction.AUTH_EXECUTE, 'invite_user') + const canCreateUsers = checkPermissions(PermissionAction.AUTH_EXECUTE, 'create_user') + + const [inviteVisible, setInviteVisible] = useState(false) + const [createVisible, setCreateVisible] = useState(false) + + return ( + <> + + {inviteEnabled && ( + + + } + disabled={!canInviteUsers} + onClick={() => setInviteVisible(true)} + > + Send Invitation + + + {!canInviteUsers && ( + + +
+ + You need additional permissions to invite users + +
+
+ )} +
+ )} + + + + } + disabled={!canCreateUsers} + onClick={() => setCreateVisible(true)} + > + Create New User + + + + {!canCreateUsers && ( + + +
+ + You need additional permissions to create users + +
+
+ )} +
+ + } + > + +
+ + {inviteEnabled && } + + + ) +} + +export default AddUserDropdown diff --git a/studio/components/interfaces/Auth/Users/CreateUserModal.tsx b/studio/components/interfaces/Auth/Users/CreateUserModal.tsx index ac28c20da8c..94698aca740 100644 --- a/studio/components/interfaces/Auth/Users/CreateUserModal.tsx +++ b/studio/components/interfaces/Auth/Users/CreateUserModal.tsx @@ -1,21 +1,23 @@ -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 { useContext } from 'react' +import { Button, Checkbox, Form, IconLock, IconMail, 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 = () => { +export type CreateUserModalProps = { + visible: boolean + setVisible: (visible: boolean) => void +} + +const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => { 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) @@ -84,105 +86,78 @@ const CreateUserModal = () => { } return ( -
- - - - - - {!canCreateUsers && ( - - -
- - You need additional permissions to create users - -
-
- )} -
- - +
- - {({ isSubmitting }: { isSubmitting: boolean }) => ( - -
- -
- } - type="email" - name="email" - placeholder="user@example.com" - disabled={isSubmitting || isLoading} - /> + {({ isSubmitting }: { isSubmitting: boolean }) => ( + +
+ +
+ } + type="email" + name="email" + placeholder="user@example.com" + disabled={isSubmitting || isLoading} + /> - } - disabled={isSubmitting || isLoading} - autoComplete="new-password" - /> + } + disabled={isSubmitting || isLoading} + autoComplete="new-password" + /> - -
-
+ +
+ - - - -
- - )} - - -
+ + + +
+ + )} + + ) } diff --git a/studio/components/interfaces/Auth/Users/InviteUserModal.tsx b/studio/components/interfaces/Auth/Users/InviteUserModal.tsx index 5f5898714cf..2ec628eb448 100644 --- a/studio/components/interfaces/Auth/Users/InviteUserModal.tsx +++ b/studio/components/interfaces/Auth/Users/InviteUserModal.tsx @@ -1,18 +1,21 @@ -import { useContext, useState } from 'react' -import { observer } from 'mobx-react-lite' -import * as Tooltip from '@radix-ui/react-tooltip' -import { Button, Modal, Input, IconPlus, IconMail, Form } from 'ui' import { PermissionAction } from '@supabase/shared-types/out/constants' +import { observer } from 'mobx-react-lite' +import { useContext } from 'react' +import { Button, Form, IconMail, Input, Modal } from 'ui' -import { useStore, checkPermissions } from 'hooks' +import { checkPermissions, useStore } from 'hooks' import { post } from 'lib/common/fetch' import { API_URL } from 'lib/constants' import { PageContext } from 'pages/project/[ref]/auth/users' -const InviteUserModal = () => { +export type InviteUserModalProps = { + visible: boolean + setVisible: (visible: boolean) => void +} + +const InviteUserModal = ({ visible, setVisible }: InviteUserModalProps) => { const { ui } = useStore() const PageState: any = useContext(PageContext) - const [visible, setVisible] = useState(false) const handleToggle = () => setVisible(!visible) const canInviteUsers = checkPermissions(PermissionAction.AUTH_EXECUTE, 'invite_user') @@ -31,7 +34,7 @@ const InviteUserModal = () => { return errors } - const onInviteuser = async (values: any, { setSubmitting }: any) => { + const onInviteUser = async (values: any, { setSubmitting }: any) => { setSubmitting(true) const response = await post(`${API_URL}/auth/${PageState.projectRef}/invite`, { @@ -56,28 +59,6 @@ const InviteUserModal = () => { return (
- - - - - {!canInviteUsers && ( - - -
- - You need additional permissions to invite users - -
-
- )} -
{ onCancel={handleToggle} >
{({ isSubmitting }: { isSubmitting: boolean }) => (
{ placeholder="User email" /> + - {inviteEnabled && } - + +