Skip to content

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

Chore/update create and update user to use platform endpoints (#30379)

Joshen Lim55c4dffda7af
diff --git a/apps/studio/components/interfaces/Auth/Users/BanUserModal.tsx b/apps/studio/components/interfaces/Auth/Users/BanUserModal.tsx
index 04a923d0082..7543072de08 100644
--- a/apps/studio/components/interfaces/Auth/Users/BanUserModal.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/BanUserModal.tsx
@@ -8,7 +8,6 @@ import * as z from 'zod'
import { useParams } from 'common'
import { useUserUpdateMutation } from 'data/auth/user-update-mutation'
import { User } from 'data/auth/users-infinite-query'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import {
Button,
cn,
@@ -34,7 +33,6 @@ interface BanUserModalProps {
export const BanUserModal = ({ visible, user, onClose }: BanUserModalProps) => {
const { ref: projectRef } = useParams()
- const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { mutate: updateUser, isLoading: isBanningUser } = useUserUpdateMutation({
onSuccess: (_, vars) => {
const bannedUntil = dayjs()
@@ -62,25 +60,15 @@ export const BanUserModal = ({ visible, user, onClose }: BanUserModalProps) => {
const bannedUntil = dayjs().add(Number(value), unit).format('DD MMM YYYY HH:mm (ZZ)')
const onSubmit = (data: FormType) => {
- if (!settings) {
- return toast.error(`Failed to ban user: Error loading project config`)
- } else if (user.id === undefined) {
+ if (projectRef === undefined) return console.error('Project ref is required')
+ if (user.id === undefined) {
return toast.error(`Failed to ban user: User ID not found`)
}
const durationHours = data.unit === 'hours' ? Number(data.value) : Number(data.value) * 24
- const protocol = settings?.app_config?.protocol ?? 'https'
- const endpoint = settings?.app_config?.endpoint
- const { serviceKey } = getAPIKeys(settings)
-
- if (!endpoint) return toast.error(`Failed to ban user: Unable to retrieve API endpoint`)
- if (!serviceKey?.api_key) return toast.error(`Failed to ban user: Unable to retrieve API key`)
updateUser({
projectRef,
- protocol,
- endpoint,
- serviceApiKey: serviceKey.api_key,
userId: user.id,
banDuration: durationHours,
})
diff --git a/apps/studio/components/interfaces/Auth/Users/CreateUserModal.tsx b/apps/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
index 8e0b2467781..dd6b79e3de6 100644
--- a/apps/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
@@ -7,7 +7,6 @@ import * as z from 'zod'
import { useParams } from 'common'
import { useUserCreateMutation } from 'data/auth/user-create-mutation'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import {
Button,
@@ -39,13 +38,6 @@ const CreateUserFormSchema = z.object({
const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
const { ref: projectRef } = useParams()
-
- const {
- data: settings,
- isLoading,
- isSuccess,
- } = useProjectSettingsV2Query({ projectRef }, { enabled: visible })
-
const canCreateUsers = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'create_user')
const { mutate: createUser, isLoading: isCreatingUser } = useUserCreateMutation({
@@ -57,24 +49,9 @@ const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
})
const onCreateUser = async (values: any) => {
- if (!isSuccess) {
- return toast.error(`Failed to create user: Error loading project config`)
- }
- const protocol = settings?.app_config?.protocol ?? 'https'
- const endpoint = settings?.app_config?.endpoint
- const { serviceKey } = getAPIKeys(settings)
+ if (!projectRef) return console.error('Project ref is required')
- if (!endpoint) return toast.error(`Failed to create user: Unable to retrieve API endpoint`)
- if (!serviceKey?.api_key)
- return toast.error(`Failed to create user: Unable to retrieve API key`)
-
- createUser({
- projectRef,
- protocol,
- endpoint,
- serviceApiKey: serviceKey.api_key,
- user: values,
- })
+ createUser({ projectRef, user: values })
}
const form = useForm<z.infer<typeof CreateUserFormSchema>>({
@@ -115,7 +92,7 @@ const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
type="email"
name="email"
placeholder="[email protected]"
- disabled={isCreatingUser || isLoading}
+ disabled={isCreatingUser}
className="pl-8"
/>
</div>
@@ -145,9 +122,9 @@ const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
type="password"
name="password"
placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;"
- disabled={isCreatingUser || isLoading}
+ disabled={isCreatingUser}
className="pl-8"
- ></Input_Shadcn_>
+ />
</div>
</FormControl_Shadcn_>
<FormMessage_Shadcn_ />
@@ -182,7 +159,7 @@ const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
size="small"
htmlType="submit"
loading={isCreatingUser}
- disabled={!canCreateUsers || isCreatingUser || isLoading}
+ disabled={!canCreateUsers || isCreatingUser}
>
Create user
</Button>
diff --git a/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx b/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
index 81d08ea2a2c..af15700c840 100644
--- a/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
@@ -16,7 +16,6 @@ import { useUserSendMagicLinkMutation } from 'data/auth/user-send-magic-link-mut
import { useUserSendOTPMutation } from 'data/auth/user-send-otp-mutation'
import { useUserUpdateMutation } from 'data/auth/user-update-mutation'
import { User } from 'data/auth/users-infinite-query'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { BASE_PATH } from 'lib/constants'
import { timeout } from 'lib/helpers'
@@ -58,6 +57,7 @@ export const UserOverview = ({ user, onDeleteSuccess }: UserOverviewProps) => {
}
})
+ const canUpdateUser = useCheckPermissions(PermissionAction.AUTH_EXECUTE, '*')
const canSendMagicLink = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_magic_link')
const canSendRecovery = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_recovery')
const canSendOtp = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'send_otp')
@@ -76,7 +76,6 @@ export const UserOverview = ({ user, onDeleteSuccess }: UserOverviewProps) => {
const [isDeleteFactorsModalOpen, setIsDeleteFactorsModalOpen] = useState(false)
const { data } = useAuthConfigQuery({ projectRef })
- const { data: settings } = useProjectSettingsV2Query({ projectRef })
const mailerOtpExpiry = data?.MAILER_OTP_EXP ?? 0
const minutes = Math.floor(mailerOtpExpiry / 60)
@@ -143,24 +142,13 @@ export const UserOverview = ({ user, onDeleteSuccess }: UserOverviewProps) => {
}
const handleUnban = () => {
- if (!settings) {
- return toast.error(`Failed to ban user: Error loading project config`)
- } else if (user.id === undefined) {
+ if (projectRef === undefined) return console.error('Proejct ref is required')
+ if (user.id === undefined) {
return toast.error(`Failed to ban user: User ID not found`)
}
- const protocol = settings?.app_config?.protocol ?? 'https'
- const endpoint = settings?.app_config?.endpoint
- const { serviceKey } = getAPIKeys(settings)
-
- if (!endpoint) return toast.error(`Failed to unban user: Unable to retrieve API endpoint`)
- if (!serviceKey?.api_key) return toast.error(`Failed to unban user: Unable to retrieve API key`)
-
updateUser({
projectRef,
- protocol,
- endpoint,
- serviceApiKey: serviceKey.api_key,
userId: user.id,
banDuration: 'none',
})
@@ -386,7 +374,7 @@ export const UserOverview = ({ user, onDeleteSuccess }: UserOverviewProps) => {
button={{
icon: <Ban />,
text: isBanned ? 'Unban user' : 'Ban user',
- disabled: !canRemoveMFAFactors,
+ disabled: !canUpdateUser,
onClick: () => {
if (isBanned) {
setIsUnbanModalOpen(true)
diff --git a/apps/studio/data/auth/user-create-mutation.ts b/apps/studio/data/auth/user-create-mutation.ts
index 4484f199cc7..83adf73a3ff 100644
--- a/apps/studio/data/auth/user-create-mutation.ts
+++ b/apps/studio/data/auth/user-create-mutation.ts
@@ -1,59 +1,31 @@
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
+import { handleError, post } from 'data/fetchers'
import { sqlKeys } from 'data/sql/keys'
-import { post } from 'lib/common/fetch'
-import { IS_PLATFORM } from 'lib/constants'
-import { PROJECT_ENDPOINT_PROTOCOL } from 'pages/api/constants'
import type { ResponseError } from 'types'
import { authKeys } from './keys'
export type UserCreateVariables = {
- projectRef?: string
- protocol: string
- endpoint: string
- serviceApiKey: string
+ projectRef: string
user: {
email: string
password: string
- autoConfirmUser: string
+ autoConfirmUser: boolean
}
}
-export type UserCreateResponse = {
- id: string
- phone: string
- role: string
- updated_at: string
- app_metadata: {
- provider: string
- providers: string[]
- }
- aud: string
- created_at: string
- email: string
- email_confirmed_at: string
- identities: any[]
- user_metadata: any
-}
-
-export async function createUser({ protocol, endpoint, serviceApiKey, user }: UserCreateVariables) {
- const response = await post(
- `${protocol}://${endpoint}/auth/v1/admin/users`,
- {
+export async function createUser({ projectRef, user }: UserCreateVariables) {
+ const { data, error } = await post('/platform/auth/{ref}/users', {
+ params: { path: { ref: projectRef } },
+ body: {
email: user.email,
password: user.password,
email_confirm: user.autoConfirmUser,
},
- {
- headers: {
- apikey: serviceApiKey,
- Authorization: `Bearer ${serviceApiKey}`,
- },
- }
- )
- if (response.error) throw response.error
- return response
+ })
+ if (error) handleError(error)
+ return data
}
type UserCreateData = Awaited<ReturnType<typeof createUser>>
diff --git a/apps/studio/data/auth/user-update-mutation.ts b/apps/studio/data/auth/user-update-mutation.ts
index d6f2e5a7623..19cf3ae3b9f 100644
--- a/apps/studio/data/auth/user-update-mutation.ts
+++ b/apps/studio/data/auth/user-update-mutation.ts
@@ -1,46 +1,25 @@
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
-import { put } from 'lib/common/fetch'
-import { IS_PLATFORM } from 'lib/constants'
-import { PROJECT_ENDPOINT_PROTOCOL } from 'pages/api/constants'
+import { handleError, patch } from 'data/fetchers'
import type { ResponseError } from 'types'
import { authKeys } from './keys'
export type UserUpdateVariables = {
- projectRef?: string
- protocol: string
- endpoint: string
- serviceApiKey: string
-
+ projectRef: string
userId: string
// For now just support updating banning the user
banDuration: number | 'none' // In hours, "none" to unban, otherwise a string in hours e.g "24h"
}
-export async function updateUser({
- protocol,
- endpoint,
- serviceApiKey,
- userId,
- banDuration,
-}: UserUpdateVariables) {
- // [Joshen] This is probably the only endpoint that needs the put method from lib/common/fetch
- // as it's not our internal API.
- const response = await put(
- `${protocol}://${endpoint}/auth/v1/admin/users/${userId}`,
- { ban_duration: typeof banDuration === 'number' ? `${banDuration}h` : banDuration },
- {
- headers: {
- apikey: serviceApiKey,
- Authorization: `Bearer ${serviceApiKey}`,
- },
- credentials: undefined,
- }
- )
+export async function updateUser({ projectRef, userId, banDuration }: UserUpdateVariables) {
+ const { data, error } = await patch('/platform/auth/{ref}/users/{id}', {
+ params: { path: { ref: projectRef, id: userId } },
+ body: { ban_duration: typeof banDuration === 'number' ? `${banDuration}h` : banDuration },
+ })
- if (response.error) throw response.error
- return response
+ if (error) handleError(error)
+ return data
}
type UserUpdateData = Awaited<ReturnType<typeof updateUser>>
diff --git a/apps/studio/pages/api/auth/[ref]/users.ts b/apps/studio/pages/api/auth/[ref]/users.ts
index 5acfcfd044c..0fbcf299d36 100644
--- a/apps/studio/pages/api/auth/[ref]/users.ts
+++ b/apps/studio/pages/api/auth/[ref]/users.ts
@@ -1,5 +1,6 @@
import { NextApiRequest, NextApiResponse } from 'next'
import SqlString from 'sqlstring'
+import { createClient } from '@supabase/supabase-js'
import { post } from 'lib/common/fetch'
import { tryParseInt } from 'lib/helpers'
@@ -7,6 +8,8 @@ import { PG_META_URL } from 'lib/constants'
import apiWrapper from 'lib/api/apiWrapper'
import { constructHeaders } from 'lib/api/apiHelpers'
+const supabase = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SERVICE_KEY!)
+
export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
async function handler(req: NextApiRequest, res: NextApiResponse) {
@@ -15,10 +18,12 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
switch (method) {
case 'GET':
return handleGetAll(req, res)
+ case 'POST':
+ return handlePost(req, res)
case 'DELETE':
return handleDelete(req, res)
default:
- res.setHeader('Allow', ['GET', 'DELETE'])
+ res.setHeader('Allow', ['GET', 'POST', 'DELETE'])
res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
}
}
@@ -110,18 +115,18 @@ const handleGetAll = async (req: NextApiRequest, res: NextApiResponse) => {
return res.status(200).json({ total, users: getUsers })
}
-const handleDelete = async (req: NextApiRequest, res: NextApiResponse) => {
- const headers = constructHeaders(req.headers)
-
- const payload = req.body
- const query = { query: `DELETE from auth.users where id='${payload.id}';` }
+const handlePost = async (req: NextApiRequest, res: NextApiResponse) => {
+ const { email, password, email_confirm } = req.body
+ const { data, error } = await supabase.auth.admin.createUser({ email, password, email_confirm })
- const response = await post(`${PG_META_URL}/query`, query, { headers })
+ if (error) return res.status(400).json({ error: { message: error.message } })
+ return res.status(200).json(data.user)
+}
- if (response.error) {
- console.error('Delete Users POST:', response.error)
- return res.status(400).json({ error: response.error })
- }
+const handleDelete = async (req: NextApiRequest, res: NextApiResponse) => {
+ const { id } = req.body
+ const { data, error } = await supabase.auth.admin.deleteUser(id)
- return res.status(200).json(response)
+ if (error) return res.status(400).json({ error: { message: error.message } })
+ return res.status(200).json(data.user)
}
diff --git a/apps/studio/pages/api/auth/[ref]/users/[id]/index.ts b/apps/studio/pages/api/auth/[ref]/users/[id]/index.ts
new file mode 100644
index 00000000000..531cf3ba6f7
--- /dev/null
+++ b/apps/studio/pages/api/auth/[ref]/users/[id]/index.ts
@@ -0,0 +1,29 @@
+import { createClient } from '@supabase/supabase-js'
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import apiWrapper from 'lib/api/apiWrapper'
+
+const supabase = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SERVICE_KEY!)
+
+export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)
+
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ const { method } = req
+
+ switch (method) {
+ case 'PATCH':
+ return handlePatch(req, res)
+ default:
+ res.setHeader('Allow', ['PATCH'])
+ res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
+ }
+}
+
+const handlePatch = async (req: NextApiRequest, res: NextApiResponse) => {
+ const { id } = req.query
+ const { ban_duration } = req.body
+ const { data, error } = await supabase.auth.admin.updateUserById(id as string, { ban_duration })
+
+ if (error) return res.status(400).json({ error: { message: error.message } })
+ return res.status(200).json(data.user)
+}