All files / modules/20-rbac/pages/Users/views ActiveUsersListView.tsx

86.29% Statements 107/124
59.51% Branches 122/205
77.42% Functions 24/31
86.89% Lines 106/122

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483              11x 11x                         11x   11x 11x 11x 11x                   11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x                         11x 24x 24x   24x                                                                 11x 24x 24x   24x 2x 2x     24x                                       11x 24x   24x                     11x 36x 36x 36x 36x 36x 36x 36x 36x   36x             36x                 36x 36x 33x   3x       3x             36x               1x 1x 1x 1x 1x               36x             1x 1x 1x 1x 1x               36x 1x 1x               1x 1x       1x             36x                         36x         4x                     2x 2x                 1x 1x 1x                                                                         1x 1x 1x                     11x           15x 15x 15x 15x 15x 15x   15x                         15x 12x     15x       15x 6x     15x 6x           15x 15x       18x             18x               18x             18x                   15x               30x                                                                                                         11x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useState, useMemo, useEffect } from 'react'
import {
  Text,
  Layout,
  Button,
  Popover,
  Avatar,
  Icon,
  ButtonVariation,
  useConfirmationDialog,
  useToaster,
  Page,
  TableV2
} from '@wings-software/uicore'
import { Color, FontVariation } from '@harness/design-system'
import type { CellProps, Renderer, Column } from 'react-table'
import { Classes, Position, Menu, Intent, PopoverInteractionKind, MenuItem } from '@blueprintjs/core'
import { useHistory, useParams } from 'react-router-dom'
import { defaultTo, noop } from 'lodash-es'
import {
  UserAggregate,
  useRemoveUser,
  useGetAggregatedUsers,
  UserGroupDTO,
  UserMetadataDTO,
  RoleAssignmentMetadataDTO,
  useUnlockUser,
  checkIfLastAdminPromise
} from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import RoleBindingsList from '@rbac/components/RoleBindingsList/RoleBindingsList'
import { useRoleAssignmentModal } from '@rbac/modals/RoleAssignmentModal/useRoleAssignmentModal'
import { getUserName, PrincipalType } from '@rbac/utils/utils'
import { useMutateAsGet } from '@common/hooks'
import type { PipelineType, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import routes from '@common/RouteDefinitions'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import ManagePrincipalButton from '@rbac/components/ManagePrincipalButton/ManagePrincipalButton'
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import RbacButton from '@rbac/components/Button/Button'
import { setPageNumber } from '@common/utils/utils'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import { Scope } from '@common/interfaces/SecretsInterface'
import { isCDCommunity, useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import css from './UserListView.module.scss'
 
interface ActiveUserListViewProps {
  searchTerm?: string
  shouldReload?: boolean
  onRefetch?: () => void
  openRoleAssignmentModal: (
    type?: PrincipalType,
    principalInfo?: UserGroupDTO | UserMetadataDTO,
    roleBindings?: RoleAssignmentMetadataDTO[]
  ) => void
}
 
const RenderColumnUser: Renderer<CellProps<UserAggregate>> = ({ row }) => {
  const data = row.original.user
  const { getString } = useStrings()
 
  return (
    <Layout.Horizontal
      spacing="small"
      className={css.overflow}
      flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
      padding={{ right: 'small' }}
    >
      {data.locked ? (
        <Icon
          name="lock"
          border
          className={css.lockIcon}
          width={32}
          height={32}
          color={Color.WHITE}
          background={Color.GREY_300}
          flex={{ align: 'center-center' }}
          margin={{ left: 'xsmall', right: 'xsmall' }}
        />
      ) : (
        <Avatar name={data.name || data.email} email={data.email} hoverCard={false} />
      )}
      <Layout.Vertical width={'100%'}>
        <Text lineClamp={1}>{data.name}</Text>
        {data.locked ? (
          <Text font={'small'} color={Color.GREY_400}>
            {getString('rbac.usersPage.lockedOutLabel')}
          </Text>
        ) : null}
      </Layout.Vertical>
    </Layout.Horizontal>
  )
}
const RenderColumnRoleAssignments: Renderer<CellProps<UserAggregate>> = ({ row, column }) => {
  const data = row.original.roleAssignmentMetadata
  const { getString } = useStrings()
 
  const handleAddRole = (e: React.MouseEvent<Element, MouseEvent>): void => {
    e.stopPropagation()
    ;(column as any).openRoleAssignmentModal(PrincipalType.USER, row.original.user, row.original.roleAssignmentMetadata)
  }
 
  return (
    <Layout.Horizontal
      spacing="small"
      flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
      padding={{ right: 'small' }}
    >
      <RoleBindingsList data={data} length={2} />
      <ManagePrincipalButton
        text={getString('common.plusNumber', { number: getString('common.role') })}
        variation={ButtonVariation.LINK}
        className={css.roleButton}
        data-testid={`addRole-${row.original.user.uuid}`}
        onClick={handleAddRole}
        resourceIdentifier={row.original.user.uuid}
        resourceType={ResourceType.USER}
      />
    </Layout.Horizontal>
  )
}
 
const RenderColumnEmail: Renderer<CellProps<UserAggregate>> = ({ row }) => {
  const data = row.original
 
  return (
    <Layout.Horizontal
      className={css.overflow}
      flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
      padding={{ right: 'small' }}
    >
      <Text>{data.user?.email}</Text>
    </Layout.Horizontal>
  )
}
 
const RenderColumnMenu: Renderer<CellProps<UserAggregate>> = ({ row, column }) => {
  const data = row.original.user
  const name = getUserName(data)
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
  const scope = getScopeFromDTO({ accountIdentifier: accountId, projectIdentifier, orgIdentifier })
  const [menuOpen, setMenuOpen] = useState(false)
  const [isLastAdmin, setIsLastAdmin] = useState(false)
  const { showSuccess, showError } = useToaster()
  const { getString } = useStrings()
 
  const { mutate: deleteUser } = useRemoveUser({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
  const { mutate: unlockUser } = useUnlockUser({
    userId: data.uuid,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
 
  const getContentText = (): string => {
    if (!isLastAdmin) {
      return getString('rbac.usersPage.deleteConfirmation', { name })
    }
    switch (scope) {
      case Scope.PROJECT:
        return getString('rbac.usersPage.deleteLastAdminProjectConfirmation', { name })
      case Scope.ORG:
        return getString('rbac.usersPage.deleteLastAdminOrgConfirmation', { name })
      default: {
        return getString('rbac.usersPage.deleteConfirmation', { name })
      }
    }
  }
 
  const { openDialog: openDeleteDialog } = useConfirmationDialog({
    contentText: getContentText(),
    titleText: getString('rbac.usersPage.deleteTitle'),
    confirmButtonText: getString('delete'),
    cancelButtonText: getString('cancel'),
    intent: Intent.DANGER,
    buttonIntent: Intent.DANGER,
    onCloseDialog: async didConfirm => {
      Eif (didConfirm && data) {
        try {
          const deleted = await deleteUser(data.uuid)
          deleted && showSuccess(getString('rbac.usersPage.deleteSuccessMessage', { name }))
          ;(column as any).refetchActiveUsers?.()
        } catch (err) {
          showError(defaultTo(err?.data?.message, err?.message))
        }
      }
    }
  })
 
  const { openDialog: openUnlockDialog } = useConfirmationDialog({
    contentText: getString('rbac.usersPage.unlockConfirmation', { name }),
    titleText: getString('rbac.usersPage.unlockTitle'),
    confirmButtonText: getString('confirm'),
    cancelButtonText: getString('cancel'),
    intent: Intent.WARNING,
    onCloseDialog: async didConfirm => {
      Eif (didConfirm && data) {
        try {
          const unlocked = await unlockUser()
          unlocked && showSuccess(getString('rbac.usersPage.unlockSuccessMessage', { name }))
          ;(column as any).refetchActiveUsers?.()
        } catch (err) {
          showError(defaultTo(err?.data?.message, err?.message))
        }
      }
    }
  })
 
  const handleDelete = async (): Promise<void> => {
    try {
      const response = await checkIfLastAdminPromise({
        queryParams: {
          accountIdentifier: accountId,
          orgIdentifier,
          projectIdentifier,
          userId: data.uuid
        }
      })
      setIsLastAdmin(_oldval => defaultTo(response.data, false))
      Iif (response.data && scope === Scope.ACCOUNT) {
        showError(getString('rbac.usersPage.deleteLastAdminError', { name }))
        return
      } else {
        openDeleteDialog()
      }
    } catch (err) {
      showError(defaultTo(err?.data?.message, err?.message))
    }
  }
 
  const permissionRequest = {
    resourceScope: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    },
    resource: {
      resourceType: ResourceType.USER,
      resourceIdentifier: data.uuid
    },
    permission: PermissionIdentifier.MANAGE_USER
  }
 
  return (
    <Layout.Horizontal flex={{ justifyContent: 'flex-end' }}>
      <Popover
        isOpen={menuOpen}
        onInteraction={nextOpenState => {
          setMenuOpen(nextOpenState)
        }}
        className={Classes.DARK}
        position={Position.BOTTOM_RIGHT}
      >
        <Button
          minimal
          icon="Options"
          withoutBoxShadow
          data-testid={`menu-${data.uuid}`}
          onClick={e => {
            e.stopPropagation()
            setMenuOpen(true)
          }}
        />
        <Menu>
          {data.locked ? (
            <RbacMenuItem
              icon="unlock"
              text={getString('rbac.usersPage.unlockTitle')}
              onClick={e => {
                e.stopPropagation()
                setMenuOpen(false)
                openUnlockDialog()
              }}
              permission={permissionRequest}
            />
          ) : null}
          {data.externallyManaged ? (
            <Popover
              position={Position.TOP}
              fill
              usePortal
              inheritDarkTheme={false}
              interactionKind={PopoverInteractionKind.HOVER}
              hoverCloseDelay={50}
              content={
                <div className={css.popover}>
                  <Text font={{ variation: FontVariation.SMALL }}>
                    {getString('rbac.manageSCIMText', {
                      action: getString('delete').toLowerCase(),
                      target: getString('common.userLabel').toLowerCase()
                    })}
                  </Text>
                </div>
              }
            >
              <div
                onClick={(event: React.MouseEvent<HTMLElement, MouseEvent>) => {
                  event.stopPropagation()
                }}
              >
                <MenuItem icon="trash" text={getString('delete')} disabled />
              </div>
            </Popover>
          ) : (
            <RbacMenuItem
              icon="trash"
              text={getString('delete')}
              onClick={e => {
                e.stopPropagation()
                setMenuOpen(false)
                handleDelete()
              }}
              permission={permissionRequest}
            />
          )}
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
const ActiveUserListView: React.FC<ActiveUserListViewProps> = ({
  searchTerm,
  openRoleAssignmentModal,
  shouldReload,
  onRefetch
}) => {
  const { getString } = useStrings()
  const history = useHistory()
  const { accountId, orgIdentifier, projectIdentifier, module } = useParams<PipelineType<ProjectPathProps>>()
  const [page, setPage] = useState(0)
  const { licenseInformation } = useLicenseStore()
  const isCommunity = isCDCommunity(licenseInformation)
 
  const { data, loading, error, refetch } = useMutateAsGet(useGetAggregatedUsers, {
    body: {},
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      pageIndex: page,
      pageSize: 10,
      searchTerm: searchTerm
    },
    debounce: 300
  })
 
  useEffect(() => {
    setPageNumber({ setPage, page, pageItemsCount: data?.data?.pageItemCount })
  }, [data?.data])
 
  const { openRoleAssignmentModal: addRole } = useRoleAssignmentModal({
    onSuccess: refetch
  })
 
  useEffect(() => {
    Iif (searchTerm) setPage(0)
  }, [searchTerm])
 
  useEffect(() => {
    Iif (shouldReload) {
      refetch()
      onRefetch?.()
    }
  }, [shouldReload])
 
  const columns: Column<UserAggregate>[] = useMemo(
    () => [
      {
        Header: getString('users'),
        id: 'user',
        accessor: row => row.user?.name,
        width: '30%',
        Cell: RenderColumnUser
      },
      {
        Header: isCommunity ? '' : getString('rbac.usersPage.roleBinding'),
        id: 'roleBinding',
        accessor: row => row.roleAssignmentMetadata,
        width: '45%',
        Cell: isCommunity ? () => noop : RenderColumnRoleAssignments,
        openRoleAssignmentModal: addRole
      },
      {
        Header: getString('email'),
        id: 'email',
        accessor: row => row.user?.email,
        width: '20%',
        Cell: RenderColumnEmail
      },
      {
        Header: '',
        id: 'menu',
        accessor: row => row.user?.uuid,
        width: '5%',
        Cell: RenderColumnMenu,
        refetchActiveUsers: refetch,
        disableSortBy: true
      }
    ],
    [openRoleAssignmentModal, refetch]
  )
 
  return (
    <Page.Body
      loading={loading}
      error={(error as any)?.data?.message || error?.message}
      retryOnError={() => refetch()}
      noData={
        !searchTerm
          ? {
              when: () => !data?.data?.content?.length,
              icon: 'nav-project',
              message: getString('rbac.usersPage.noDataDescription'),
              button: (
                <RbacButton
                  text={getString('newUser')}
                  variation={ButtonVariation.PRIMARY}
                  icon="plus"
                  onClick={() => openRoleAssignmentModal()}
                  permission={{
                    resource: {
                      resourceType: ResourceType.USER
                    },
                    permission: PermissionIdentifier.INVITE_USER
                  }}
                />
              )
            }
          : {
              when: () => !data?.data?.content?.length,
              icon: 'nav-project',
              message: getString('rbac.usersPage.noUsersFound')
            }
      }
    >
      <TableV2<UserAggregate>
        className={css.table}
        columns={columns}
        data={data?.data?.content || []}
        name="ActiveUsersListView"
        pagination={{
          itemCount: data?.data?.totalItems || 0,
          pageSize: data?.data?.pageSize || 10,
          pageCount: data?.data?.totalPages || 0,
          pageIndex: data?.data?.pageIndex || 0,
          gotoPage: (pageNumber: number) => setPage(pageNumber)
        }}
        onRowClick={user => {
          history.push(
            routes.toUserDetails({
              accountId,
              orgIdentifier,
              projectIdentifier,
              module,
              userIdentifier: user.user.uuid
            })
          )
        }}
      />
    </Page.Body>
  )
}
 
export default ActiveUserListView