wizard: add user information step (HMS-4903)

This commit introduces the user information step with the following fields:
(*) `userName` field
(*) `password` field
(*) add unit tests for create and edit mode
This commit is contained in:
Michal Gold 2024-12-18 17:39:51 +02:00 committed by Lucas Garfield
parent 7da478791e
commit d0f2317649
8 changed files with 342 additions and 3 deletions

View file

@ -10,7 +10,16 @@ import {
} from '@patternfly/react-core';
import UserIcon from '@patternfly/react-icons/dist/esm/icons/user-icon';
import { useAppDispatch } from '../../../../../store/hooks';
import { addUser } from '../../../../../store/wizardSlice';
const EmptyUserState = () => {
const dispatch = useAppDispatch();
const onAddUserClick = () => {
dispatch(addUser());
};
return (
<EmptyState variant={EmptyStateVariant.lg}>
<EmptyStateHeader
@ -18,11 +27,12 @@ const EmptyUserState = () => {
headingLevel="h4"
/>
<EmptyStateFooter>
<Button variant="secondary" onClick={() => {}}>
<Button variant="secondary" onClick={onAddUserClick}>
Add a user
</Button>
</EmptyStateFooter>
</EmptyState>
);
};
export default EmptyUserState;

View file

@ -0,0 +1,66 @@
import React from 'react';
import { Form, FormGroup } from '@patternfly/react-core';
import { useAppDispatch, useAppSelector } from '../../../../../store/hooks';
import {
selectUserNameByIndex,
selectUserPasswordByIndex,
setUserNameByIndex,
setUserPasswordByIndex,
} from '../../../../../store/wizardSlice';
import { HookValidatedInput } from '../../../ValidatedTextInput';
const UserInfo = () => {
const dispatch = useAppDispatch();
const index = 0;
const userNameSelector = selectUserNameByIndex(index);
const userName = useAppSelector(userNameSelector);
const userPasswordSelector = selectUserPasswordByIndex(index);
const userPassword = useAppSelector(userPasswordSelector);
const handleNameChange = (
_e: React.FormEvent<HTMLInputElement>,
value: string
) => {
dispatch(setUserNameByIndex({ index: index, name: value }));
};
const handlePasswordChange = (
_event: React.FormEvent<HTMLInputElement>,
value: string
) => {
dispatch(setUserPasswordByIndex({ index: index, password: value }));
};
const stepValidation = {
errors: {},
disabledNext: false,
};
return (
<Form>
<FormGroup isRequired label="Username">
<HookValidatedInput
ariaLabel="blueprint user name"
value={userName || ''}
placeholder="Enter username"
onChange={(_e, value) => handleNameChange(_e, value)}
stepValidation={stepValidation}
fieldName="userName"
/>
</FormGroup>
<FormGroup isRequired label="Password">
<HookValidatedInput
ariaLabel="blueprint user password"
value={userPassword || ''}
onChange={(_e, value) => handlePasswordChange(_e, value)}
placeholder="Enter password"
stepValidation={stepValidation}
fieldName="userPassword"
/>
</FormGroup>
</Form>
);
};
export default UserInfo;

View file

@ -3,15 +3,21 @@ import React from 'react';
import { Form, Text, Title } from '@patternfly/react-core';
import EmptyUserState from './component/Empty';
import UserInfo from './component/UserInfo';
import { useAppSelector } from '../../../../store/hooks';
import { selectUsers } from '../../../../store/wizardSlice';
const UsersStep = () => {
const users = useAppSelector(selectUsers);
return (
<Form>
<Title headingLevel="h1" size="xl">
Users
</Title>
<Text>Add a user to your image.</Text>
<EmptyUserState />
{users.length !== 0 ? <UserInfo /> : <EmptyUserState />}
</Form>
);
};

View file

@ -34,6 +34,7 @@ import {
Services,
Subscription,
UploadTypes,
User,
} from '../../../store/imageBuilderApi';
import {
selectActivationKey,
@ -81,6 +82,7 @@ import {
selectLanguages,
selectKeyboard,
selectHostname,
selectUsers,
} from '../../../store/wizardSlice';
import { FileSystemConfigurationType } from '../steps/FileSystem';
import {
@ -206,6 +208,15 @@ function commonRequestToState(
blueprintName: request.name || '',
blueprintDescription: request.description || '',
},
users:
request.customizations.users?.map((user) => ({
name: user.name,
password: '', // The image-builder API does not return the password.
ssh_key: user.ssh_key || '',
confirmPassword: '',
groups: user.groups || [],
isAdministrator: user.groups?.includes('wheel') || false,
})) || [],
compliance:
compliancePolicyID !== undefined
? {
@ -502,7 +513,7 @@ const getCustomizations = (state: RootState, orgID: string): Customizations => {
custom_repositories: getCustomRepositories(state),
openscap: getOpenscap(state),
filesystem: getFileSystem(state),
users: undefined,
users: getUsers(state),
services: getServices(state),
hostname: selectHostname(state) || undefined,
kernel: selectKernel(state).append
@ -558,6 +569,24 @@ const getOpenscap = (state: RootState): OpenScap | undefined => {
return undefined;
};
const getUsers = (state: RootState): User[] | undefined => {
const users = selectUsers(state);
if (users.length === 0) {
return undefined;
}
return users.map((user) => {
const result: User = {
name: user.name,
};
if (user.password !== '') {
result.password = user.password;
}
return result as User;
});
};
const getFileSystem = (state: RootState): Filesystem[] | undefined => {
const mode = selectFileSystemConfigurationType(state);

View file

@ -10,6 +10,7 @@ import type {
Locale,
Repository,
Timezone,
User,
} from './imageBuilderApi';
import type { ActivationKeys } from './rhsmApi';
@ -43,6 +44,20 @@ export type RegistrationType =
export type ComplianceType = 'openscap' | 'compliance';
export type UserWithAdditionalInfo = {
[K in keyof User]-?: NonNullable<User[K]>;
};
type UserPayload = {
index: number;
name: string;
};
type UserPasswordPayload = {
index: number;
password: string;
};
export type wizardState = {
env: {
serverUrl: string;
@ -90,6 +105,7 @@ export type wizardState = {
useLatest: boolean;
snapshotDate: string;
};
users: UserWithAdditionalInfo[];
firstBoot: {
script: string;
};
@ -196,6 +212,7 @@ export const initialState: wizardState = {
},
hostname: '',
firstBoot: { script: '' },
users: [],
};
export const selectServerUrl = (state: RootState) => {
@ -337,6 +354,20 @@ export const selectServices = (state: RootState) => {
return state.wizard.services;
};
export const selectUsers = (state: RootState) => {
return state.wizard.users;
};
export const selectUserNameByIndex =
(userIndex: number) => (state: RootState) => {
return state.wizard.users[userIndex]?.name;
};
export const selectUserPasswordByIndex =
(userIndex: number) => (state: RootState) => {
return state.wizard.users[userIndex]?.password;
};
export const selectKernel = (state: RootState) => {
return state.wizard.kernel;
};
@ -758,6 +789,27 @@ export const wizardSlice = createSlice({
changeHostname: (state, action: PayloadAction<string>) => {
state.hostname = action.payload;
},
addUser: (state) => {
const newUser = {
name: '',
password: '',
confirmPassword: '',
ssh_key: '',
groups: [],
isAdministrator: false,
};
state.users.push(newUser);
},
setUserNameByIndex: (state, action: PayloadAction<UserPayload>) => {
state.users[action.payload.index].name = action.payload.name;
},
setUserPasswordByIndex: (
state,
action: PayloadAction<UserPasswordPayload>
) => {
state.users[action.payload.index].password = action.payload.password;
},
},
});
@ -825,5 +877,8 @@ export const {
addNtpServer,
removeNtpServer,
changeHostname,
addUser,
setUserNameByIndex,
setUserPasswordByIndex,
} = wizardSlice.actions;
export default wizardSlice.reducer;

View file

@ -0,0 +1,142 @@
import type { Router as RemixRouter } from '@remix-run/router';
import { screen, waitFor } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { CREATE_BLUEPRINT, EDIT_BLUEPRINT } from '../../../../../constants';
import { mockBlueprintIds } from '../../../../fixtures/blueprints';
import { usersCreateBlueprintRequest } from '../../../../fixtures/editMode';
import {
blueprintRequest,
clickBack,
clickNext,
enterBlueprintName,
getNextButton,
interceptBlueprintRequest,
interceptEditBlueprintRequest,
openAndDismissSaveAndBuildModal,
renderEditMode,
verifyCancelButton,
} from '../../wizardTestUtils';
import {
clickRegisterLater,
goToRegistrationStep,
renderCreateMode,
} from '../../wizardTestUtils';
let router: RemixRouter | undefined = undefined;
const goToUsersStep = async () => {
await clickNext();
await clickNext();
await clickNext();
await clickNext();
await clickNext();
await clickNext();
};
const goToReviewStep = async () => {
await clickNext(); // Timezone
await clickNext(); // Locale
await clickNext(); // Hostname
await clickNext(); // Kernel
await clickNext(); // First boot
await clickNext(); // Details
await enterBlueprintName();
await clickNext(); // Review
};
const addValidUser = async () => {
const user = userEvent.setup();
const addUser = await screen.findByRole('button', { name: /add a user/i });
expect(addUser).toBeEnabled();
await waitFor(() => user.click(addUser));
const enterUserName = screen.getByRole('textbox', {
name: /blueprint user name/i,
});
const nextButton = await getNextButton();
await waitFor(() => user.type(enterUserName, 'best'));
await waitFor(() => expect(enterUserName).toHaveValue('best'));
await waitFor(() => expect(nextButton).toBeEnabled());
};
describe('Step Users', () => {
beforeEach(async () => {
vi.clearAllMocks();
router = undefined;
});
test('without adding user loads timezone', async () => {
const user = userEvent.setup();
await renderCreateMode();
await goToRegistrationStep();
await clickRegisterLater();
await goToUsersStep();
const nextButton = await getNextButton();
expect(nextButton).toBeEnabled();
await waitFor(() => user.click(nextButton));
await screen.findByText('Select a timezone for your image.');
});
test('clicking Back loads Additional packages', async () => {
await renderCreateMode();
await goToRegistrationStep();
await clickRegisterLater();
await goToUsersStep();
await clickBack();
await screen.findByRole('heading', { name: 'Additional packages' });
});
test('clicking Cancel loads landing page', async () => {
await renderCreateMode();
await goToUsersStep();
await verifyCancelButton(router);
});
describe('User request generated correctly', () => {
test('with valid name and password', async () => {
await renderCreateMode();
await goToRegistrationStep();
await clickRegisterLater();
await goToUsersStep();
await addValidUser();
await goToReviewStep();
// informational modal pops up in the first test only as it's tied
// to a 'imageBuilder.saveAndBuildModalSeen' variable in localStorage
await openAndDismissSaveAndBuildModal();
const receivedRequest = await interceptBlueprintRequest(CREATE_BLUEPRINT);
const expectedRequest = {
...blueprintRequest,
customizations: {
users: [
{
name: 'best',
},
],
},
};
await waitFor(() => {
expect(receivedRequest).toEqual(expectedRequest);
});
});
});
describe('Users edit mode', () => {
beforeEach(() => {
vi.clearAllMocks();
});
test('edit mode works', async () => {
const id = mockBlueprintIds['users'];
await renderEditMode(id);
// starts on review step
const receivedRequest = await interceptEditBlueprintRequest(
`${EDIT_BLUEPRINT}/${id}`
);
const expectedRequest = usersCreateBlueprintRequest;
expect(receivedRequest).toEqual(expectedRequest);
});
});
});

View file

@ -33,6 +33,7 @@ export const mockBlueprintIds = {
snapshot: '5dafa0fc-a5c8-4dc3-8a03-ceeb3677b28a',
repositories: '6f20ab62-37ba-4afd-9945-734919e9307b',
packages: 'b3437c4e-f6f8-4270-8d32-323ac60bc929',
users: '87610289-96e5-4fb6-a359-0e56269ff6de',
timezone: 'c535dc6e-93b0-4592-ad29-fe46ba7dac73',
locale: '6e982b49-cd2e-4ad0-9962-39315a0ed9d1',
hostname: '05677f58-56c5-4c1e-953b-c8a93da70cc5',
@ -57,6 +58,7 @@ export const mockBlueprintNames = {
snapshot: 'snapshot',
repositories: 'repositories',
packages: 'packages',
users: 'users',
timezone: 'timezone',
locale: 'locale',
hostname: 'hostname',
@ -81,6 +83,7 @@ export const mockBlueprintDescriptions = {
snapshot: '',
repositories: '',
packages: '',
users: '',
timezone: '',
locale: '',
hostname: '',
@ -275,6 +278,13 @@ export const mockGetBlueprints: GetBlueprintsApiResponse = {
version: 1,
last_modified_at: '2021-09-08T21:00:00.000Z',
},
{
id: mockBlueprintIds['users'],
name: mockBlueprintNames['users'],
description: mockBlueprintDescriptions['users'],
version: 1,
last_modified_at: '2021-09-08T21:00:00.000Z',
},
{
id: mockBlueprintIds['timezone'],
name: mockBlueprintNames['timezone'],

View file

@ -439,6 +439,25 @@ export const timezoneBlueprintResponse: BlueprintResponse = {
description: mockBlueprintDescriptions['timezone'],
};
export const usersCreateBlueprintRequest: CreateBlueprintRequest = {
...baseCreateBlueprintRequest,
name: mockBlueprintNames['users'],
description: mockBlueprintDescriptions['users'],
customizations: {
users: [
{
name: 'best',
},
],
},
};
export const usersBlueprintResponse: BlueprintResponse = {
...usersCreateBlueprintRequest,
id: mockBlueprintIds['users'],
description: mockBlueprintDescriptions['users'],
};
export const localeCreateBlueprintRequest: CreateBlueprintRequest = {
...baseCreateBlueprintRequest,
name: mockBlueprintNames['locale'],
@ -556,6 +575,8 @@ export const getMockBlueprintResponse = (id: string) => {
return repositoriesBlueprintResponse;
case mockBlueprintIds['packages']:
return packagesBlueprintResponse;
case mockBlueprintIds['users']:
return usersBlueprintResponse;
case mockBlueprintIds['timezone']:
return timezoneBlueprintResponse;
case mockBlueprintIds['locale']: