Skip to content

feat: Add update user roles action #1361

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
May 10, 2022
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
Add UI for update user roles
  • Loading branch information
BrunoQuaresma committed May 9, 2022
commit 1e99a0406d3b32b7a6c21897bbef35bf7e4e480c
5 changes: 5 additions & 0 deletions site/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,8 @@ export const getSiteRoles = async (): Promise<Array<TypesGen.Role>> => {
const response = await axios.get<Array<TypesGen.Role>>(`/api/v2/users/roles`)
return response.data
}

export const updateUserRoles = async (
roles: TypesGen.Role["name"][],
userId: TypesGen.User["id"],
): Promise<TypesGen.User> => axios.put(`/api/v2/users/${userId}/roles`, { roles })
49 changes: 49 additions & 0 deletions site/src/components/UsersTable/RoleSelect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import Checkbox from "@material-ui/core/Checkbox"
import MenuItem from "@material-ui/core/MenuItem"
import Select from "@material-ui/core/Select"
import makeStyles from "@material-ui/styles/makeStyles"
import React from "react"
import { Role } from "../../api/typesGenerated"

export interface RoleSelectProps {
roles: Role[]
selectedRoles: Role[]
onChange: (roles: Role["name"][]) => void
loading?: boolean
}

export const RoleSelect: React.FC<RoleSelectProps> = ({ roles, selectedRoles, loading, onChange }) => {
const styles = useStyles()
const value = selectedRoles.map((r) => r.name)
const renderValue = () => selectedRoles.map((r) => r.display_name).join(", ")

return (
<Select
multiple
value={value}
renderValue={renderValue}
variant="outlined"
className={styles.select}
onChange={(e) => {
const { value } = e.currentTarget
onChange(value as string[])
}}
>
{roles.map((r) => {
const isChecked = selectedRoles.some((selectedRole) => selectedRole.name === r.name)

return (
<MenuItem key={r.name} value={r.name} disabled={loading}>
<Checkbox color="primary" checked={isChecked} /> {r.display_name}
</MenuItem>
)
})}
</Select>
)
}

const useStyles = makeStyles(() => ({
select: {
margin: 0,
},
}))
27 changes: 17 additions & 10 deletions site/src/components/UsersTable/UsersTable.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import Box from "@material-ui/core/Box"
import MenuItem from "@material-ui/core/MenuItem"
import Select from "@material-ui/core/Select"
import Table from "@material-ui/core/Table"
import TableBody from "@material-ui/core/TableBody"
import TableCell from "@material-ui/core/TableCell"
Expand All @@ -14,6 +12,7 @@ import { TableHeaderRow } from "../TableHeaders/TableHeaders"
import { TableRowMenu } from "../TableRowMenu/TableRowMenu"
import { TableTitle } from "../TableTitle/TableTitle"
import { UserCell } from "../UserCell/UserCell"
import { RoleSelect } from "./RoleSelect"

export const Language = {
pageTitle: "Users",
Expand All @@ -29,10 +28,19 @@ export interface UsersTableProps {
users: UserResponse[]
onSuspendUser: (user: UserResponse) => void
onResetUserPassword: (user: UserResponse) => void
onUpdateUserRoles: (user: UserResponse, roles: TypesGen.Role["name"][]) => void
roles: TypesGen.Role[]
isUpdatingUserRoles?: boolean
}

export const UsersTable: React.FC<UsersTableProps> = ({ users, roles, onSuspendUser, onResetUserPassword }) => {
export const UsersTable: React.FC<UsersTableProps> = ({
users,
roles,
onSuspendUser,
onResetUserPassword,
onUpdateUserRoles,
isUpdatingUserRoles,
}) => {
return (
<Table>
<TableHead>
Expand All @@ -51,13 +59,12 @@ export const UsersTable: React.FC<UsersTableProps> = ({ users, roles, onSuspendU
<UserCell Avatar={{ username: u.username }} primaryText={u.username} caption={u.email} />{" "}
</TableCell>
<TableCell>
<Select multiple value={[]}>
{roles.map((r) => (
<MenuItem key={r.name} value={r.name}>
{r.display_name}
</MenuItem>
))}
</Select>
<RoleSelect
roles={roles}
selectedRoles={u.roles}
loading={isUpdatingUserRoles}
onChange={(roles) => onUpdateUserRoles(u, roles)}
/>
</TableCell>
<TableCell>
<TableRowMenu
Expand Down
8 changes: 8 additions & 0 deletions site/src/pages/UsersPage/UsersPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,15 @@ export const UsersPage: React.FC = () => {
onResetUserPassword={(user) => {
usersSend({ type: "RESET_USER_PASSWORD", userId: user.id })
}}
onUpdateUserRoles={(user, roles) => {
usersSend({
type: "UPDATE_USER_ROLES",
userId: user.id,
roles,
})
}}
error={getUsersError}
isUpdatingUserRoles={usersState.matches("updatingUserRoles")}
/>

<ConfirmDialog
Expand Down
6 changes: 6 additions & 0 deletions site/src/pages/UsersPage/UsersPageView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ export interface UsersPageViewProps {
openUserCreationDialog: () => void
onSuspendUser: (user: UserResponse) => void
onResetUserPassword: (user: UserResponse) => void
onUpdateUserRoles: (user: UserResponse, roles: TypesGen.Role["name"][]) => void
roles: TypesGen.Role[]
error?: unknown
isUpdatingUserRoles?: boolean
}

export const UsersPageView: React.FC<UsersPageViewProps> = ({
Expand All @@ -27,7 +29,9 @@ export const UsersPageView: React.FC<UsersPageViewProps> = ({
openUserCreationDialog,
onSuspendUser,
onResetUserPassword,
onUpdateUserRoles,
error,
isUpdatingUserRoles,
}) => {
return (
<Stack spacing={4}>
Expand All @@ -40,7 +44,9 @@ export const UsersPageView: React.FC<UsersPageViewProps> = ({
users={users}
onSuspendUser={onSuspendUser}
onResetUserPassword={onResetUserPassword}
onUpdateUserRoles={onUpdateUserRoles}
roles={roles}
isUpdatingUserRoles={isUpdatingUserRoles}
/>
)}
</Margins>
Expand Down
61 changes: 61 additions & 0 deletions site/src/xServices/users/usersXService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export const Language = {
suspendUserError: "Error on suspend the user.",
resetUserPasswordSuccess: "Successfully updated the user password.",
resetUserPasswordError: "Error on reset the user password.",
updateUserRolesSuccess: "Successfully updated the user roles.",
updateUserRolesError: "Error on update the user roles.",
}

export interface UsersContext {
Expand All @@ -27,6 +29,9 @@ export interface UsersContext {
userIdToResetPassword?: TypesGen.User["id"]
resetUserPasswordError?: Error | unknown
newUserPassword?: string
// Update user roles
userIdToUpdateRoles?: TypesGen.User["id"]
updateUserRolesError?: Error | unknown
}

export type UsersEvent =
Expand All @@ -40,6 +45,8 @@ export type UsersEvent =
| { 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"][] }

export const usersMachine = createMachine(
{
Expand All @@ -60,6 +67,9 @@ export const usersMachine = createMachine(
updateUserPassword: {
data: undefined
}
updateUserRoles: {
data: TypesGen.User
}
},
},
id: "usersState",
Expand All @@ -80,6 +90,10 @@ export const usersMachine = createMachine(
target: "confirmUserPasswordReset",
actions: ["assignUserIdToResetPassword", "generateRandomPassword"],
},
UPDATE_USER_ROLES: {
target: "updatingUserRoles",
actions: ["assignUserIdToUpdateRoles"],
},
},
},
gettingUsers: {
Expand Down Expand Up @@ -166,6 +180,21 @@ export const usersMachine = createMachine(
},
},
},
updatingUserRoles: {
entry: "clearUpdateUserRolesError",
invoke: {
src: "updateUserRoles",
id: "updateUserRoles",
onDone: {
target: "idle",
actions: ["displayUpdateRolesSuccess", "updateUserRolesInTheList"],
},
onError: {
target: "idle",
actions: ["assignUpdateRolesError", "displayUpdateRolesErrorMessage"],
},
},
},
error: {
on: {
GET_USERS: "gettingUsers",
Expand Down Expand Up @@ -198,6 +227,13 @@ export const usersMachine = createMachine(

return API.updateUserPassword(context.newUserPassword, context.userIdToResetPassword)
},
updateUserRoles: (context, event) => {
if (!context.userIdToUpdateRoles) {
throw new Error("userIdToUpdateRoles is undefined")
}

return API.updateUserRoles(event.roles, context.userIdToUpdateRoles)
},
},
guards: {
isFormError: (_, event) => isApiError(event.data),
Expand All @@ -215,6 +251,9 @@ export const usersMachine = createMachine(
assignUserIdToResetPassword: assign({
userIdToResetPassword: (_, event) => event.userId,
}),
assignUserIdToUpdateRoles: assign({
userIdToUpdateRoles: (_, event) => event.userId,
}),
clearGetUsersError: assign((context: UsersContext) => ({
...context,
getUsersError: undefined,
Expand All @@ -232,6 +271,9 @@ export const usersMachine = createMachine(
assignResetUserPasswordError: assign({
resetUserPasswordError: (_, event) => event.data,
}),
assignUpdateRolesError: assign({
updateUserRolesError: (_, event) => event.data,
}),
clearCreateUserError: assign((context: UsersContext) => ({
...context,
createUserError: undefined,
Expand All @@ -242,6 +284,9 @@ export const usersMachine = createMachine(
clearResetUserPasswordError: assign({
resetUserPasswordError: (_) => undefined,
}),
clearUpdateUserRolesError: assign({
updateUserRolesError: (_) => undefined,
}),
displayCreateUserSuccess: () => {
displaySuccess(Language.createUserSuccess)
},
Expand All @@ -257,9 +302,25 @@ export const usersMachine = createMachine(
displayResetPasswordErrorMessage: () => {
displayError(Language.resetUserPasswordError)
},
displayUpdateRolesSuccess: () => {
displayError(Language.updateUserRolesSuccess)
},
displayUpdateRolesErrorMessage: () => {
displayError(Language.updateUserRolesError)
},
generateRandomPassword: assign({
newUserPassword: (_) => generateRandomString(12),
}),
updateUserRolesInTheList: assign({
users: ({ users }, event) => {
if (!users) {
return users
}

const updatedUser = event.data
return users.map((u) => (u.id === updatedUser.id ? updatedUser : u))
},
}),
},
},
)