refactor: modernize the create user page (#28894)
> 🤖 This PR was modified by Coder Agents on behalf of Jake Howell. Redesigns the create user flow using the settings page layout and renames it to "New user." The form includes clearer field guidance, explicit authentication-method loading, error, and empty states, updated documentation, and aligned end-to-end selectors. | Old | New | | --- | --- | | <img width="2560" height="2516" alt="02-create-user" src="https://github.com/user-attachments/assets/c79fb42b-3b0f-47fa-b03d-801c81584dba"/> | <img width="2560" height="2748" alt="02-create-user-page" src="https://github.com/user-attachments/assets/2d2dd777-3ae9-444d-9811-082f30eb8387"/> | Depends on #28893. <details> <summary>Stack</summary> 1. #28893 - Edit user page redesign 2. #28894 - Create user page redesign (this PR) </details>
This commit is contained in:
1 parent
3b1828db5b
commit
486d2faa81
9 files changed
+466
-296
No files matched your search
@@ -27,8 +27,7 @@ coder users create \
|
||||
|
||||
## UI
|
||||
|
||||
Navigate to **Deployment** > **Users** > **Create user**, then select
|
||||
**Service account** as the login type.
|
||||
Navigate to **Deployment** > **Users** > **New user**, then select **Service account** as the login type.
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -74,13 +74,11 @@ To create a user with the web UI:
|
||||
|
||||
1. Log in as a user admin.
|
||||
2. Go to **Users** > **New user**.
|
||||
3. In the window that opens, provide the **username**, **email**, and
|
||||
**password** for the user (they can opt to change their password after their
|
||||
initial login).
|
||||
4. Select **Submit** to create the user.
|
||||
3. Enter the **Username**, **Email**, and **Password**.
|
||||
4. Select **Save**.
|
||||
|
||||
The new user will appear in the **Users** list. Use the toggle to change their
|
||||
**Roles** if desired.
|
||||
The new user appears in the **Users** list.
|
||||
You can assign roles on this page before you save, or later from the user's actions menu.
|
||||
|
||||
To create a user via the Coder CLI, run:
|
||||
|
||||
|
||||
+3
-3
@@ -1342,8 +1342,8 @@ export async function createUser(
|
||||
await page.goto("/deployment/users", { waitUntil: "domcontentloaded" });
|
||||
await expect(page).toHaveTitle("Users - Coder");
|
||||
|
||||
await page.getByRole("link", { name: "Create user" }).click();
|
||||
await expect(page).toHaveTitle("Create User - Coder");
|
||||
await page.getByRole("link", { name: "New user" }).click();
|
||||
await expect(page).toHaveTitle("New user - Coder");
|
||||
|
||||
const username = userValues.username ?? randomName();
|
||||
const name = userValues.name ?? username;
|
||||
@@ -1353,7 +1353,7 @@ export async function createUser(
|
||||
|
||||
await page.getByLabel("Username").fill(username);
|
||||
if (name) {
|
||||
await page.getByLabel("Full name").fill(name);
|
||||
await page.getByLabel("Name", { exact: true }).fill(name);
|
||||
}
|
||||
await page.getByLabel("Email").fill(email);
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { action } from "storybook/actions";
|
||||
import { userEvent, within } from "storybook/test";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { permittedOrganizationsKey } from "#/api/queries/organizations";
|
||||
import {
|
||||
assignableRole,
|
||||
MockAuditorRole,
|
||||
MockAuthMethodsAll,
|
||||
MockAuthMethodsPasswordOnly,
|
||||
MockOrganization,
|
||||
MockOrganization2,
|
||||
@@ -21,27 +23,83 @@ const meta: Meta<typeof CreateUserForm> = {
|
||||
onCancel: action("cancel"),
|
||||
onSubmit: action("submit"),
|
||||
isLoading: false,
|
||||
showOrganizations: false,
|
||||
serviceAccountsEnabled: true,
|
||||
authMethods: MockAuthMethodsPasswordOnly,
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof CreateUserForm>;
|
||||
|
||||
export const Ready: Story = {};
|
||||
export const Ready: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(
|
||||
canvas.getByRole("heading", { name: "New user" }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
canvas.getByRole("link", { name: /back to users/i }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
canvas.getByText(/add a user to this coder deployment/i),
|
||||
).toBeVisible();
|
||||
await expect(canvas.getByText("Unique identifier.")).toBeVisible();
|
||||
await expect(
|
||||
canvas.getByText("Friendly name. Defaults to the username if blank."),
|
||||
).toBeVisible();
|
||||
await expect(canvas.queryByText(/optional/i)).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
// Query key used by permittedOrganizations() in the form.
|
||||
const permittedOrgsKey = [
|
||||
"organizations",
|
||||
"permitted",
|
||||
{ object: { resource_type: "organization_member" }, action: "create" },
|
||||
];
|
||||
export const NoAvailableLoginTypes: Story = {
|
||||
args: {
|
||||
authMethods: {
|
||||
password: { enabled: false },
|
||||
github: { enabled: false, default_provider_configured: false },
|
||||
oidc: { enabled: false, signInText: "", iconUrl: "" },
|
||||
},
|
||||
serviceAccountsEnabled: false,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(
|
||||
canvas.getByText(
|
||||
"No authentication methods are available for new users.",
|
||||
),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
canvas.queryByRole("button", { name: /save/i }),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const KeepsEmailForExternalLogin: Story = {
|
||||
args: {
|
||||
authMethods: MockAuthMethodsAll,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
const email = canvas.getByLabelText(/email/i);
|
||||
await userEvent.type(email, "someone@coder.com");
|
||||
await userEvent.click(canvas.getByTestId("login-type-input"));
|
||||
await userEvent.click(
|
||||
await within(document.body).findByRole("option", {
|
||||
name: /openID connect/i,
|
||||
}),
|
||||
);
|
||||
await expect(email).toHaveValue("someone@coder.com");
|
||||
},
|
||||
};
|
||||
|
||||
export const WithOrganizations: Story = {
|
||||
parameters: {
|
||||
queries: [
|
||||
{
|
||||
key: permittedOrgsKey,
|
||||
key: permittedOrganizationsKey({
|
||||
object: { resource_type: "organization_member" },
|
||||
action: "create",
|
||||
}),
|
||||
data: [MockOrganization, MockOrganization2],
|
||||
},
|
||||
],
|
||||
@@ -61,6 +119,12 @@ export const FormError: Story = {
|
||||
validations: [{ field: "username", detail: "Username taken" }],
|
||||
}),
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("button", { name: /save/i }));
|
||||
await expect(await canvas.findByText("Username taken")).toBeVisible();
|
||||
await expect(canvas.queryByRole("alert")).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const GeneralError: Story = {
|
||||
@@ -69,12 +133,22 @@ export const GeneralError: Story = {
|
||||
message: "User already exists",
|
||||
}),
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByText("User already exists")).toBeVisible();
|
||||
await expect(canvas.getByLabelText(/username/i)).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
export const Loading: Story = {
|
||||
args: {
|
||||
isLoading: true,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByRole("button", { name: /save/i })).toBeDisabled();
|
||||
await expect(canvas.getByRole("button", { name: /cancel/i })).toBeEnabled();
|
||||
},
|
||||
};
|
||||
|
||||
const mockAvailableRoles = [
|
||||
@@ -87,7 +161,13 @@ const mockAvailableRoles = [
|
||||
export const RolesLoading: Story = {
|
||||
args: {
|
||||
rolesLoading: true,
|
||||
authMethods: MockAuthMethodsPasswordOnly,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByText("Roles")).toBeVisible();
|
||||
await expect(
|
||||
canvas.queryByRole("checkbox", { name: /owner/i }),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -96,25 +176,40 @@ export const RolesError: Story = {
|
||||
rolesError: mockApiError({
|
||||
message: "Failed to fetch assignable roles.",
|
||||
}),
|
||||
authMethods: MockAuthMethodsPasswordOnly,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(
|
||||
canvas.getByText("Failed to fetch assignable roles."),
|
||||
).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
export const WithRoles: Story = {
|
||||
args: {
|
||||
availableRoles: mockAvailableRoles,
|
||||
authMethods: MockAuthMethodsPasswordOnly,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(
|
||||
canvas.getByRole("checkbox", { name: /owner/i }),
|
||||
).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
export const WithRolesSelected: Story = {
|
||||
args: {
|
||||
availableRoles: mockAvailableRoles,
|
||||
authMethods: MockAuthMethodsPasswordOnly,
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("checkbox", { name: /owner/i }));
|
||||
await userEvent.click(canvas.getByRole("checkbox", { name: /auditor/i }));
|
||||
await expect(
|
||||
canvas.getByRole("checkbox", { name: /owner/i }),
|
||||
).toBeChecked();
|
||||
await expect(
|
||||
canvas.getByRole("checkbox", { name: /auditor/i }),
|
||||
).toBeChecked();
|
||||
},
|
||||
};
|
||||
@@ -1,18 +1,19 @@
|
||||
import { cn } from "cn";
|
||||
import { useFormik } from "formik";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { ArrowLeftIcon, CheckIcon } from "lucide-react";
|
||||
import { Select as SelectPrimitive } from "radix-ui";
|
||||
import { type FC, useState } from "react";
|
||||
import { useQuery } from "react-query";
|
||||
import { Link } from "react-router";
|
||||
import * as Yup from "yup";
|
||||
import { hasApiFieldErrors, isApiError } from "#/api/errors";
|
||||
import { permittedOrganizations } from "#/api/queries/organizations";
|
||||
import type * as TypesGen from "#/api/typesGenerated";
|
||||
import { Alert } from "#/components/Alert/Alert";
|
||||
import { ErrorAlert } from "#/components/Alert/ErrorAlert";
|
||||
import { Button } from "#/components/Button/Button";
|
||||
import { FormFooter } from "#/components/Form/Form";
|
||||
import { FormFields, FormFooter } from "#/components/Form/Form";
|
||||
import { FormField } from "#/components/FormField/FormField";
|
||||
import { FullPageForm } from "#/components/FullPageForm/FullPageForm";
|
||||
import { Label } from "#/components/Label/Label";
|
||||
import { OrganizationAutocomplete } from "#/components/OrganizationAutocomplete/OrganizationAutocomplete";
|
||||
import {
|
||||
@@ -21,6 +22,11 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "#/components/Select/Select";
|
||||
import {
|
||||
SettingsHeader,
|
||||
SettingsHeaderDescription,
|
||||
SettingsHeaderTitle,
|
||||
} from "#/components/SettingsHeader/SettingsHeader";
|
||||
import { Spinner } from "#/components/Spinner/Spinner";
|
||||
import { RoleSelector } from "#/modules/roles/RoleSelector";
|
||||
import {
|
||||
@@ -52,7 +58,7 @@ const loginTypeOptions = {
|
||||
|
||||
const validationSchema = Yup.object({
|
||||
username: nameValidator("Username"),
|
||||
name: displayNameValidator("Full name"),
|
||||
name: displayNameValidator("Name"),
|
||||
email: Yup.string()
|
||||
.trim()
|
||||
.when("service_account", {
|
||||
@@ -89,7 +95,7 @@ type CreateUserFormProps = {
|
||||
isLoading: boolean;
|
||||
onSubmit: (user: CreateUserFormData) => void;
|
||||
onCancel: () => void;
|
||||
authMethods?: TypesGen.AuthMethods;
|
||||
authMethods: TypesGen.AuthMethods;
|
||||
showOrganizations: boolean;
|
||||
serviceAccountsEnabled: boolean;
|
||||
availableRoles?: TypesGen.AssignableRoles[];
|
||||
@@ -101,27 +107,74 @@ type CreateUserFormProps = {
|
||||
// in the render-time state adjustment pattern.
|
||||
const emptyOrgs: TypesGen.Organization[] = [];
|
||||
|
||||
export const CreateUserForm: FC<CreateUserFormProps> = ({
|
||||
const createOrgMemberCheck = {
|
||||
object: { resource_type: "organization_member" },
|
||||
action: "create",
|
||||
} as const;
|
||||
|
||||
export const CreateUserForm: FC<CreateUserFormProps> = (props) => {
|
||||
const availableLoginTypes = (
|
||||
["password", "oidc", "github", "none"] as const
|
||||
).filter((key) => {
|
||||
if (key === "none") {
|
||||
return props.serviceAccountsEnabled;
|
||||
}
|
||||
return props.authMethods[key].enabled;
|
||||
});
|
||||
const defaultLoginType = availableLoginTypes[0];
|
||||
|
||||
if (!defaultLoginType) {
|
||||
return (
|
||||
<div>
|
||||
<Button variant="subtle" asChild className="-ml-3">
|
||||
<Link to="/deployment/users">
|
||||
<ArrowLeftIcon />
|
||||
<span>Back to users</span>
|
||||
</Link>
|
||||
</Button>
|
||||
<div className="pt-6">
|
||||
<SettingsHeader>
|
||||
<SettingsHeaderTitle>New user</SettingsHeaderTitle>
|
||||
<SettingsHeaderDescription>
|
||||
Add a user to this Coder deployment.
|
||||
</SettingsHeaderDescription>
|
||||
</SettingsHeader>
|
||||
<Alert severity="error" prominent>
|
||||
No authentication methods are available for new users.
|
||||
</Alert>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CreateUserFormFields
|
||||
{...props}
|
||||
availableLoginTypes={availableLoginTypes}
|
||||
defaultLoginType={defaultLoginType}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
type AvailableLoginType = keyof typeof loginTypeOptions;
|
||||
|
||||
type CreateUserFormFieldsProps = CreateUserFormProps & {
|
||||
availableLoginTypes: readonly AvailableLoginType[];
|
||||
defaultLoginType: AvailableLoginType;
|
||||
};
|
||||
|
||||
const CreateUserFormFields: FC<CreateUserFormFieldsProps> = ({
|
||||
error,
|
||||
isLoading,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
showOrganizations,
|
||||
authMethods,
|
||||
serviceAccountsEnabled,
|
||||
availableRoles,
|
||||
rolesLoading,
|
||||
rolesError,
|
||||
availableLoginTypes,
|
||||
defaultLoginType,
|
||||
}) => {
|
||||
const availableLoginTypes = [
|
||||
authMethods?.password.enabled && "password",
|
||||
authMethods?.oidc.enabled && "oidc",
|
||||
authMethods?.github.enabled && "github",
|
||||
serviceAccountsEnabled && "none",
|
||||
].filter(Boolean) as Array<keyof typeof loginTypeOptions>;
|
||||
|
||||
const defaultLoginType = availableLoginTypes[0];
|
||||
|
||||
const form = useFormik<CreateUserFormData>({
|
||||
initialValues: {
|
||||
email: "",
|
||||
@@ -137,7 +190,6 @@ export const CreateUserForm: FC<CreateUserFormProps> = ({
|
||||
},
|
||||
validationSchema,
|
||||
onSubmit,
|
||||
enableReinitialize: true,
|
||||
});
|
||||
|
||||
const [selectedOrg, setSelectedOrg] = useState<TypesGen.Organization | null>(
|
||||
@@ -145,10 +197,7 @@ export const CreateUserForm: FC<CreateUserFormProps> = ({
|
||||
);
|
||||
|
||||
const permittedOrgsQuery = useQuery({
|
||||
...permittedOrganizations({
|
||||
object: { resource_type: "organization_member" },
|
||||
action: "create",
|
||||
}),
|
||||
...permittedOrganizations(createOrgMemberCheck),
|
||||
enabled: showOrganizations,
|
||||
});
|
||||
const orgOptions = permittedOrgsQuery.data ?? emptyOrgs;
|
||||
@@ -181,190 +230,183 @@ export const CreateUserForm: FC<CreateUserFormProps> = ({
|
||||
});
|
||||
|
||||
return (
|
||||
<FullPageForm title="Create user" size="condensed">
|
||||
{isApiError(error) && !hasApiFieldErrors(error) && (
|
||||
<ErrorAlert error={error} className="mb-8" />
|
||||
)}
|
||||
<form
|
||||
onSubmit={form.handleSubmit}
|
||||
autoComplete="off"
|
||||
className="border border-border border-solid rounded-md p-4"
|
||||
>
|
||||
<div className="flex flex-col gap-6">
|
||||
{showOrganizations && (
|
||||
<div className="flex flex-col gap-2 max-w-sm">
|
||||
<Label htmlFor="organization">Organization</Label>
|
||||
<OrganizationAutocomplete
|
||||
id="organization"
|
||||
required
|
||||
value={selectedOrg}
|
||||
options={orgOptions}
|
||||
onChange={(newValue) => {
|
||||
setSelectedOrg(newValue);
|
||||
void form.setFieldValue("organization", newValue?.id ?? "");
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Login type — "none" is presented as "Service account" */}
|
||||
<div className="flex flex-col gap-2 max-w-sm">
|
||||
<Label htmlFor="login_type">Login type</Label>
|
||||
<Select
|
||||
value={form.values.login_type}
|
||||
onValueChange={async (value) => {
|
||||
const isServiceAccount = value === "none";
|
||||
await Promise.all([
|
||||
form.setFieldValue("login_type", value),
|
||||
form.setFieldValue("service_account", isServiceAccount),
|
||||
value !== "email"
|
||||
? form.setFieldValue("email", "")
|
||||
: Promise.resolve(),
|
||||
value !== "password"
|
||||
? form.setFieldValue("password", "")
|
||||
: Promise.resolve(),
|
||||
]);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="login_type"
|
||||
data-testid="login-type-input"
|
||||
aria-invalid={loginTypeField.error}
|
||||
aria-describedby={
|
||||
loginTypeField.error
|
||||
? "login_type-error"
|
||||
: "login_type-helper"
|
||||
}
|
||||
className={cn(
|
||||
loginTypeField.error && "border-border-destructive",
|
||||
)}
|
||||
>
|
||||
<SelectValue placeholder="Select a login type…" />
|
||||
</SelectTrigger>
|
||||
|
||||
<SelectContent className="max-w-sm">
|
||||
{availableLoginTypes.map((key) => {
|
||||
const opt = loginTypeOptions[key];
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
key={key}
|
||||
value={key}
|
||||
className="relative flex w-full cursor-default select-none items-start rounded-sm py-1.5 pl-2 pr-8 text-sm text-content-secondary outline-hidden focus:bg-surface-secondary focus:text-content-primary data-disabled:pointer-events-none data-disabled:opacity-50"
|
||||
>
|
||||
<span className="absolute right-2 top-2 flex items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-icon-sm" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<div className="flex flex-col py-0.5">
|
||||
<SelectPrimitive.ItemText>
|
||||
{opt.label}
|
||||
</SelectPrimitive.ItemText>
|
||||
<span className="text-xs text-content-secondary whitespace-normal wrap-break-word">
|
||||
{opt.description}
|
||||
</span>
|
||||
</div>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{loginTypeField.helperText && (
|
||||
<span
|
||||
id="login_type-helper"
|
||||
className="text-xs text-content-secondary"
|
||||
>
|
||||
{loginTypeField.helperText}
|
||||
</span>
|
||||
<div>
|
||||
<Button variant="subtle" asChild className="-ml-3">
|
||||
<Link to="/deployment/users">
|
||||
<ArrowLeftIcon />
|
||||
<span>Back to users</span>
|
||||
</Link>
|
||||
</Button>
|
||||
<div className="pt-6">
|
||||
<SettingsHeader>
|
||||
<SettingsHeaderTitle>New user</SettingsHeaderTitle>
|
||||
<SettingsHeaderDescription>
|
||||
Add a user to this Coder deployment.
|
||||
</SettingsHeaderDescription>
|
||||
</SettingsHeader>
|
||||
<div className="border border-solid p-6 rounded-lg">
|
||||
<form
|
||||
onSubmit={form.handleSubmit}
|
||||
autoComplete="off"
|
||||
className="flex flex-col gap-6"
|
||||
>
|
||||
{isApiError(error) && !hasApiFieldErrors(error) && (
|
||||
<ErrorAlert error={error} />
|
||||
)}
|
||||
</div>
|
||||
<FormFields>
|
||||
{showOrganizations && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="organization">Organization</Label>
|
||||
<OrganizationAutocomplete
|
||||
id="organization"
|
||||
required
|
||||
value={selectedOrg}
|
||||
options={orgOptions}
|
||||
onChange={(newValue) => {
|
||||
setSelectedOrg(newValue);
|
||||
void form.setFieldValue(
|
||||
"organization",
|
||||
newValue?.id ?? "",
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
field={getFieldHelpers("username")}
|
||||
label="Username"
|
||||
id="username"
|
||||
name="username"
|
||||
value={form.values.username}
|
||||
onChange={onChangeTrimmed(form)}
|
||||
onBlur={form.handleBlur}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="login_type">Login type</Label>
|
||||
<Select
|
||||
value={form.values.login_type}
|
||||
onValueChange={async (value) => {
|
||||
const isServiceAccount = value === "none";
|
||||
await Promise.all([
|
||||
form.setFieldValue("login_type", value),
|
||||
form.setFieldValue("service_account", isServiceAccount),
|
||||
isServiceAccount
|
||||
? form.setFieldValue("email", "")
|
||||
: Promise.resolve(),
|
||||
value !== "password"
|
||||
? form.setFieldValue("password", "")
|
||||
: Promise.resolve(),
|
||||
]);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
id="login_type"
|
||||
data-testid="login-type-input"
|
||||
aria-invalid={loginTypeField.error}
|
||||
aria-describedby={
|
||||
loginTypeField.error
|
||||
? "login_type-error"
|
||||
: "login_type-helper"
|
||||
}
|
||||
className={cn(
|
||||
loginTypeField.error && "border-border-destructive",
|
||||
)}
|
||||
>
|
||||
<SelectValue placeholder="Select a login type…" />
|
||||
</SelectTrigger>
|
||||
|
||||
<FormField
|
||||
field={getFieldHelpers("name")}
|
||||
label={
|
||||
<>
|
||||
Full name{" "}
|
||||
<span className="font-normal text-content-secondary">
|
||||
(optional)
|
||||
</span>
|
||||
</>
|
||||
}
|
||||
id="name"
|
||||
name="name"
|
||||
value={form.values.name}
|
||||
onChange={form.handleChange}
|
||||
onBlur={form.handleBlur}
|
||||
autoComplete="name"
|
||||
/>
|
||||
|
||||
{!isServiceAccount && (
|
||||
<FormField
|
||||
field={getFieldHelpers("email")}
|
||||
label={
|
||||
<>
|
||||
Email{" "}
|
||||
<span className="text-xs font-bold text-content-destructive">
|
||||
*
|
||||
<SelectContent>
|
||||
{availableLoginTypes.map((key) => {
|
||||
const opt = loginTypeOptions[key];
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
key={key}
|
||||
value={key}
|
||||
className="relative flex w-full cursor-default select-none items-start rounded-sm py-1.5 pl-2 pr-8 text-sm text-content-secondary outline-hidden focus:bg-surface-secondary focus:text-content-primary data-disabled:pointer-events-none data-disabled:opacity-50"
|
||||
>
|
||||
<span className="absolute right-2 top-2 flex items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-icon-sm" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<div className="flex flex-col py-0.5">
|
||||
<SelectPrimitive.ItemText>
|
||||
{opt.label}
|
||||
</SelectPrimitive.ItemText>
|
||||
<span className="text-xs text-content-secondary whitespace-normal wrap-break-word">
|
||||
{opt.description}
|
||||
</span>
|
||||
</div>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{loginTypeField.helperText && (
|
||||
<span
|
||||
id="login_type-helper"
|
||||
className="text-xs text-content-secondary"
|
||||
>
|
||||
{loginTypeField.helperText}
|
||||
</span>
|
||||
</>
|
||||
}
|
||||
id="email"
|
||||
name="email"
|
||||
value={form.values.email}
|
||||
onChange={onChangeTrimmed(form)}
|
||||
onBlur={form.handleBlur}
|
||||
autoComplete="email"
|
||||
type="email"
|
||||
/>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isPasswordLogin && (
|
||||
<FormField
|
||||
field={getFieldHelpers("password")}
|
||||
label="Password"
|
||||
id="password"
|
||||
name="password"
|
||||
value={form.values.password}
|
||||
onChange={form.handleChange}
|
||||
onBlur={form.handleBlur}
|
||||
autoComplete="new-password"
|
||||
type="password"
|
||||
data-testid="password-input"
|
||||
/>
|
||||
)}
|
||||
<FormField
|
||||
field={getFieldHelpers("username", {
|
||||
helperText: "Unique identifier.",
|
||||
})}
|
||||
label="Username"
|
||||
required
|
||||
onChange={onChangeTrimmed(form)}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<RoleSelector
|
||||
loading={rolesLoading}
|
||||
error={rolesError}
|
||||
availableRoles={availableRoles}
|
||||
selectedRoles={form.values.roles}
|
||||
onChange={(roles) => form.setFieldValue("roles", roles)}
|
||||
/>
|
||||
<FormField
|
||||
field={getFieldHelpers("name", {
|
||||
helperText:
|
||||
"Friendly name. Defaults to the username if blank.",
|
||||
})}
|
||||
label="Name"
|
||||
autoComplete="name"
|
||||
/>
|
||||
|
||||
{!isServiceAccount && (
|
||||
<FormField
|
||||
field={getFieldHelpers("email")}
|
||||
label="Email"
|
||||
required
|
||||
autoComplete="email"
|
||||
type="email"
|
||||
/>
|
||||
)}
|
||||
|
||||
{isPasswordLogin && (
|
||||
<FormField
|
||||
field={getFieldHelpers("password")}
|
||||
label="Password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
type="password"
|
||||
// The login type select's visible value is also "Password".
|
||||
data-testid="password-input"
|
||||
/>
|
||||
)}
|
||||
|
||||
<RoleSelector
|
||||
loading={rolesLoading}
|
||||
error={rolesError}
|
||||
availableRoles={availableRoles}
|
||||
selectedRoles={form.values.roles}
|
||||
onChange={(roles) => form.setFieldValue("roles", roles)}
|
||||
/>
|
||||
</FormFields>
|
||||
|
||||
<FormFooter className="mt-0">
|
||||
<Button onClick={onCancel} variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
<Spinner loading={isLoading} />
|
||||
Save
|
||||
</Button>
|
||||
</FormFooter>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<FormFooter className="mt-8">
|
||||
<Button onClick={onCancel} variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isLoading}>
|
||||
<Spinner loading={isLoading} />
|
||||
Save
|
||||
</Button>
|
||||
</FormFooter>
|
||||
</form>
|
||||
</FullPageForm>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -26,6 +26,38 @@ const meta = {
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Loading: Story = {
|
||||
parameters: {
|
||||
queries: [{ key: rolesQueryKey, data: [] }],
|
||||
},
|
||||
beforeEach: () => {
|
||||
spyOn(API, "getAuthMethods").mockReturnValue(new Promise(() => {}));
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(
|
||||
canvas.getByRole("status", { name: /loading/i }),
|
||||
).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
export const AuthMethodsError: Story = {
|
||||
parameters: {
|
||||
queries: [{ key: rolesQueryKey, data: [] }],
|
||||
},
|
||||
beforeEach: () => {
|
||||
spyOn(API, "getAuthMethods").mockRejectedValue(
|
||||
mockApiError({ message: "Failed to load authentication methods." }),
|
||||
);
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(
|
||||
await canvas.findByText("Failed to load authentication methods."),
|
||||
).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
export const ShowsSuccessNotificationOnSubmit: Story = {
|
||||
beforeEach: () => {
|
||||
spyOn(API, "createUser").mockResolvedValue({
|
||||
@@ -106,29 +138,26 @@ async function fillForm(
|
||||
loginType: "password" | "service account" = "password",
|
||||
) {
|
||||
const isPasswordLogin = loginType === "password";
|
||||
const body = within(document.body);
|
||||
|
||||
await user.type(await canvas.findByLabelText("Username"), "someuser");
|
||||
await user.type(await canvas.findByLabelText(/username/i), "someuser");
|
||||
if (isPasswordLogin) {
|
||||
await user.type(canvas.getByLabelText(/email/i), "someone@coder.com");
|
||||
}
|
||||
|
||||
await user.click(canvas.getByTestId("login-type-input"));
|
||||
await user.click(
|
||||
await body.findByRole("option", { name: new RegExp(loginType, "i") }),
|
||||
);
|
||||
// Wait for the select to finish closing; while it is open or exit-animating
|
||||
// Radix locks body pointer-events, which would fail the next interaction.
|
||||
await waitFor(() =>
|
||||
expect(body.queryByRole("listbox")).not.toBeInTheDocument(),
|
||||
);
|
||||
|
||||
if (isPasswordLogin) {
|
||||
await user.type(
|
||||
await canvas.findByTestId("password-input"),
|
||||
canvas.getByTestId("password-input"),
|
||||
"SomeSecurePassword!",
|
||||
);
|
||||
} else {
|
||||
const body = within(document.body);
|
||||
await user.click(canvas.getByTestId("login-type-input"));
|
||||
await user.click(
|
||||
await body.findByRole("option", { name: /service account/i }),
|
||||
);
|
||||
// Wait for the select to finish closing; while it is open or exit-animating
|
||||
// Radix locks body pointer-events, which would fail the next interaction.
|
||||
await waitFor(() =>
|
||||
expect(body.queryByRole("listbox")).not.toBeInTheDocument(),
|
||||
);
|
||||
}
|
||||
|
||||
await user.click(canvas.getByRole("button", { name: /save/i }));
|
||||
await user.click(await canvas.findByRole("button", { name: /save/i }));
|
||||
}
|
||||
@@ -5,7 +5,8 @@ import { toast } from "sonner";
|
||||
import { getErrorDetail, getErrorMessage } from "#/api/errors";
|
||||
import { roles } from "#/api/queries/roles";
|
||||
import { authMethods, createUser } from "#/api/queries/users";
|
||||
import { Margins } from "#/components/Margins/Margins";
|
||||
import { ErrorAlert } from "#/components/Alert/ErrorAlert";
|
||||
import { Loader } from "#/components/Loader/Loader";
|
||||
import { useDashboard } from "#/modules/dashboard/useDashboard";
|
||||
import { useFeatureVisibility } from "#/modules/dashboard/useFeatureVisibility";
|
||||
import { pageTitle } from "#/utils/page";
|
||||
@@ -21,58 +22,66 @@ const CreateUserPage: FC = () => {
|
||||
const { service_accounts: serviceAccountsEnabled } = useFeatureVisibility();
|
||||
|
||||
return (
|
||||
<Margins>
|
||||
<title>{pageTitle("Create User")}</title>
|
||||
<>
|
||||
<title>{pageTitle("New user")}</title>
|
||||
|
||||
<CreateUserForm
|
||||
error={createUserMutation.error}
|
||||
isLoading={createUserMutation.isPending}
|
||||
onSubmit={async (user) => {
|
||||
const mutation = createUserMutation.mutateAsync(
|
||||
{
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
organization_ids: [user.organization],
|
||||
login_type: user.login_type,
|
||||
password: user.password,
|
||||
user_status: null,
|
||||
service_account: user.service_account,
|
||||
roles: [...user.roles],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
navigate("..", { relative: "path" });
|
||||
{!authMethodsQuery.data ? (
|
||||
authMethodsQuery.error ? (
|
||||
<ErrorAlert error={authMethodsQuery.error} />
|
||||
) : (
|
||||
<Loader />
|
||||
)
|
||||
) : (
|
||||
<CreateUserForm
|
||||
error={createUserMutation.error}
|
||||
isLoading={createUserMutation.isPending}
|
||||
onSubmit={async (user) => {
|
||||
const mutation = createUserMutation.mutateAsync(
|
||||
{
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
organization_ids: [user.organization],
|
||||
login_type: user.login_type,
|
||||
password: user.password,
|
||||
user_status: null,
|
||||
service_account: user.service_account,
|
||||
roles: [...user.roles],
|
||||
},
|
||||
},
|
||||
);
|
||||
const requestedAccount = user.service_account
|
||||
? "service account"
|
||||
: "user";
|
||||
toast.promise(mutation, {
|
||||
loading: `Creating ${requestedAccount} "${user.username}"...`,
|
||||
success: (created) =>
|
||||
`${created.is_service_account ? "Service account" : "User"} "${created.username}" created successfully.`,
|
||||
error: (e) => ({
|
||||
message: getErrorMessage(
|
||||
e,
|
||||
`Failed to create ${requestedAccount} "${user.username}".`,
|
||||
),
|
||||
description: getErrorDetail(e),
|
||||
}),
|
||||
});
|
||||
}}
|
||||
onCancel={() => {
|
||||
navigate("..", { relative: "path" });
|
||||
}}
|
||||
authMethods={authMethodsQuery.data}
|
||||
showOrganizations={showOrganizations}
|
||||
serviceAccountsEnabled={serviceAccountsEnabled}
|
||||
availableRoles={rolesQuery.data}
|
||||
rolesLoading={rolesQuery.isLoading}
|
||||
rolesError={rolesQuery.error}
|
||||
/>
|
||||
</Margins>
|
||||
{
|
||||
onSuccess: () => {
|
||||
navigate("..", { relative: "path" });
|
||||
},
|
||||
},
|
||||
);
|
||||
const requestedAccount = user.service_account
|
||||
? "service account"
|
||||
: "user";
|
||||
toast.promise(mutation, {
|
||||
loading: `Creating ${requestedAccount} "${user.username}"...`,
|
||||
success: (created) =>
|
||||
`${created.is_service_account ? "Service account" : "User"} "${created.username}" created successfully.`,
|
||||
error: (e) => ({
|
||||
message: getErrorMessage(
|
||||
e,
|
||||
`Failed to create ${requestedAccount} "${user.username}".`,
|
||||
),
|
||||
description: getErrorDetail(e),
|
||||
}),
|
||||
});
|
||||
}}
|
||||
onCancel={() => {
|
||||
navigate("..", { relative: "path" });
|
||||
}}
|
||||
authMethods={authMethodsQuery.data}
|
||||
showOrganizations={showOrganizations}
|
||||
serviceAccountsEnabled={serviceAccountsEnabled}
|
||||
availableRoles={rolesQuery.data}
|
||||
rolesLoading={rolesQuery.isLoading}
|
||||
rolesError={rolesQuery.error}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -52,9 +52,7 @@ export const Admin: Story = {
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(
|
||||
canvas.getByRole("link", { name: "Create user" }),
|
||||
).toBeVisible();
|
||||
await expect(canvas.getByRole("link", { name: "New user" })).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ export const UsersPageView: FC<UsersPageViewProps> = ({
|
||||
<Button asChild>
|
||||
<Link to="create">
|
||||
<UserPlusIcon />
|
||||
Create user
|
||||
New user
|
||||
</Link>
|
||||
</Button>
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user