Skip to content

chore(site): remove users and pagination services #9932

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Move reset password to react-query
  • Loading branch information
BrunoQuaresma committed Sep 29, 2023
commit 44d8de64af67217fe3e6659061f243f51a1d328c
4 changes: 2 additions & 2 deletions site/src/pages/UsersPage/UsersPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ describe("UsersPage", () => {
});

// Check if the success message is displayed
await screen.findByText(usersXServiceLanguage.resetUserPasswordSuccess);
await screen.findByText("Password reset");

// Check if the API was called correctly
expect(API.updateUserPassword).toBeCalledTimes(1);
Expand All @@ -357,7 +357,7 @@ describe("UsersPage", () => {
});

// Check if the error message is displayed
await screen.findByText(usersXServiceLanguage.resetUserPasswordError);
await screen.findByText("Error resetting password");

// Check if the API was called correctly
expect(API.updateUserPassword).toBeCalledTimes(1);
Expand Down
55 changes: 34 additions & 21 deletions site/src/pages/UsersPage/UsersPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ import {
suspendUser,
activateUser,
deleteUser,
updatePassword,
} from "api/queries/users";
import { displayError, displaySuccess } from "components/GlobalSnackbar/utils";
import { getErrorMessage } from "api/errors";
import { generateRandomString } from "utils/random";

export const Language = {
suspendDialogTitle: "Suspend user",
Expand All @@ -39,9 +41,6 @@ export const Language = {
activateDialogMessagePrefix: "Do you want to activate the user",
};

const getSelectedUser = (id: string, users?: User[]) =>
users?.find((u) => u.id === id);

export const UsersPage: FC<{ children?: ReactNode }> = () => {
const queryClient = useQueryClient();
const navigate = useNavigate();
Expand All @@ -60,7 +59,6 @@ export const UsersPage: FC<{ children?: ReactNode }> = () => {
offset: pagination.offset,
}),
);
const { userIdToResetPassword, newUserPassword } = usersState.context;
const { updateUsers: canEditUsers, viewDeploymentValues } = usePermissions();
const rolesQuery = useQuery({ ...roles(), enabled: canEditUsers });
const { data: deploymentValues } = useQuery({
Expand Down Expand Up @@ -104,6 +102,12 @@ export const UsersPage: FC<{ children?: ReactNode }> = () => {
// Delete
const [confirmDeleteUser, setConfirmDeleteUser] = useState<User>();
const deleteUserMutation = useMutation(deleteUser(queryClient));
// Reset password
const [confirmResetPassword, setConfirmResetPassword] = useState<{
user: User;
newPassword: string;
}>();
const updatePasswordMutation = useMutation(updatePassword());

return (
<>
Expand All @@ -130,7 +134,10 @@ export const UsersPage: FC<{ children?: ReactNode }> = () => {
onSuspendUser={setConfirmSuspendUser}
onActivateUser={setConfirmActivateUser}
onResetUserPassword={(user) => {
usersSend({ type: "RESET_USER_PASSWORD", userId: user.id });
setConfirmResetPassword({
user,
newPassword: generateRandomString(12),
});
}}
onUpdateUserRoles={(user, roles) => {
usersSend({
Expand Down Expand Up @@ -232,23 +239,29 @@ export const UsersPage: FC<{ children?: ReactNode }> = () => {
}
/>

{userIdToResetPassword && (
<ResetPasswordDialog
open={
usersState.matches("confirmUserPasswordReset") ||
usersState.matches("resettingUserPassword")
<ResetPasswordDialog
key={confirmResetPassword?.user.username}
open={confirmResetPassword !== undefined}
loading={updatePasswordMutation.isLoading}
user={confirmResetPassword?.user}
newPassword={confirmResetPassword?.newPassword}
onClose={() => {
setConfirmResetPassword(undefined);
}}
onConfirm={async () => {
try {
await updatePasswordMutation.mutateAsync({
userId: confirmResetPassword!.user.id,
password: confirmResetPassword!.newPassword,
old_password: "",
});
setConfirmResetPassword(undefined);
displaySuccess("Password reset");
} catch (e) {
displayError(getErrorMessage(e, "Error resetting password"));
}
loading={usersState.matches("resettingUserPassword")}
user={getSelectedUser(userIdToResetPassword, usersQuery.data?.users)}
newPassword={newUserPassword}
onClose={() => {
usersSend("CANCEL_USER_PASSWORD_RESET");
}}
onConfirm={() => {
usersSend("CONFIRM_USER_PASSWORD_RESET");
}}
/>
)}
}}
/>
</>
);
};
Expand Down
115 changes: 6 additions & 109 deletions site/src/xServices/users/usersXService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,26 @@ import { assign, createMachine } from "xstate";
import * as API from "api/api";
import { getErrorMessage } from "api/errors";
import * as TypesGen from "api/typesGenerated";
import { displayError, displaySuccess } from "components/GlobalSnackbar/utils";
import { generateRandomString } from "utils/random";
import { displayError } from "components/GlobalSnackbar/utils";

export const Language = {
resetUserPasswordSuccess: "Successfully updated the user password.",
resetUserPasswordError: "Error on resetting the user password.",
updateUserRolesSuccess: "Successfully updated the user roles.",
updateUserRolesError: "Error on updating the user roles.",
};

export interface UsersContext {
// Reset user password
userIdToResetPassword?: TypesGen.User["id"];
resetUserPasswordError?: unknown;
newUserPassword?: string;
// Update user roles
userIdToUpdateRoles?: TypesGen.User["id"];
updateUserRolesError?: unknown;
}

export type UsersEvent =
// Reset password events
| { type: "RESET_USER_PASSWORD"; userId: TypesGen.User["id"] }
| { type: "CONFIRM_USER_PASSWORD_RESET" }
| { type: "CANCEL_USER_PASSWORD_RESET" }
// Update roles events
| {
type: "UPDATE_USER_ROLES";
userId: TypesGen.User["id"];
roles: TypesGen.Role["name"][];
};
{
type: "UPDATE_USER_ROLES";
userId: TypesGen.User["id"];
roles: TypesGen.Role["name"][];
};

export const usersMachine =
/** @xstate-layout N4IgpgJg5mDOIC5QFdZgE6wMoBcCGOYAdLPujgJYB2UACnlNQRQPZUDEA2gAwC6ioAA4tYFSmwEgAHogC0ARgBMigBxEAnCoCsAdhWrdK9QBYdAGhABPRPO7ruRAMzdj3HYuNbFANm5b1AL4BFqgY2PiERDA4lDQAqmiY7BBsxNQAbiwA1sTRCWE8-EggwqLiVJIyCArc8upOxt6K-o7qjloq3ioW1ghKPkQu6m2KOraaw0EhieEEuWAx1FD5SRjoLO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URRdcRY7BbEL9dO+WpVo2lSjQKEUjJ2hM25KtNoisvaHXNJHetZtW7oFTdAhAbxmF2HjKCIwIl1b+SZGJES75RimIBGvZu3qMA-oFQKO0edxJVW8kYXazI7ToT9nTAUrph3yWoSixIyHBxlQkrYaDnwOqaFBn0N4c5bGsm0MdcYPNR1jImT4gplGZ0SXpKaAdYJQRtHNFYjwThWoLg8JVESwy-GIeKUsyZgnnIMjcuGuVEIl2mCsamJwXsBR2BeOKuuu6PXEHxV+ol6rSZ+qqCKQYyYMNoRBsKVBvR-j-ITHPcS7DXhWc1XMTT-qATGa4jxDoK5kxWjeL0mqIJ5NczwUEIAA */
Expand All @@ -43,21 +32,6 @@ export const usersMachine =
context: {} as UsersContext,
events: {} as UsersEvent,
services: {} as {
createUser: {
data: TypesGen.User;
};
suspendUser: {
data: TypesGen.User;
};
deleteUser: {
data: undefined;
};
activateUser: {
data: TypesGen.User;
};
updateUserPassword: {
data: undefined;
};
updateUserRoles: {
data: TypesGen.User;
};
Expand All @@ -70,51 +44,12 @@ export const usersMachine =
idle: {
entry: "clearSelectedUser",
on: {
RESET_USER_PASSWORD: {
target: "confirmUserPasswordReset",
actions: [
"assignUserIdToResetPassword",
"generateRandomPassword",
],
},
UPDATE_USER_ROLES: {
target: "updatingUserRoles",
actions: "assignUserIdToUpdateRoles",
},
},
},
confirmUserPasswordReset: {
on: {
CONFIRM_USER_PASSWORD_RESET: {
target: "resettingUserPassword",
},
CANCEL_USER_PASSWORD_RESET: {
target: "idle",
},
},
},
resettingUserPassword: {
entry: "clearResetUserPasswordError",
invoke: {
src: "resetUserPassword",
id: "resetUserPassword",
onDone: [
{
target: "idle",
actions: "displayResetPasswordSuccess",
},
],
onError: [
{
target: "idle",
actions: [
"assignResetUserPasswordError",
"displayResetPasswordErrorMessage",
],
},
],
},
},
updatingUserRoles: {
entry: "clearUpdateUserRolesError",
invoke: {
Expand All @@ -141,20 +76,6 @@ export const usersMachine =
},
{
services: {
resetUserPassword: (context) => {
if (!context.userIdToResetPassword) {
throw new Error("userIdToResetPassword is undefined");
}

if (!context.newUserPassword) {
throw new Error("newUserPassword not generated");
}

return API.updateUserPassword(context.userIdToResetPassword, {
password: context.newUserPassword,
old_password: "",
});
},
updateUserRoles: (context, event) => {
if (!context.userIdToUpdateRoles) {
throw new Error("userIdToUpdateRoles is undefined");
Expand All @@ -166,51 +87,27 @@ export const usersMachine =

actions: {
clearSelectedUser: assign({
userIdToResetPassword: (_) => undefined,
userIdToUpdateRoles: (_) => undefined,
}),

assignUserIdToResetPassword: assign({
userIdToResetPassword: (_, event) => event.userId,
}),
assignUserIdToUpdateRoles: assign({
userIdToUpdateRoles: (_, event) => event.userId,
}),

assignResetUserPasswordError: assign({
resetUserPasswordError: (_, event) => event.data,
}),
assignUpdateRolesError: assign({
updateUserRolesError: (_, event) => event.data,
}),

clearResetUserPasswordError: assign({
resetUserPasswordError: (_) => undefined,
}),
clearUpdateUserRolesError: assign({
updateUserRolesError: (_) => undefined,
}),

displayResetPasswordSuccess: () => {
displaySuccess(Language.resetUserPasswordSuccess);
},
displayResetPasswordErrorMessage: (context) => {
const message = getErrorMessage(
context.resetUserPasswordError,
Language.resetUserPasswordError,
);
displayError(message);
},
displayUpdateRolesErrorMessage: (context) => {
const message = getErrorMessage(
context.updateUserRolesError,
Language.updateUserRolesError,
);
displayError(message);
},
generateRandomPassword: assign({
newUserPassword: (_) => generateRandomString(12),
}),
updateUserRolesInTheList: assign({
// users: ({ users }, event) => {
// if (!users) {
Expand Down