All files / modules/20-rbac/components/TokenList TokenList.tsx

86.05% Statements 74/86
57.14% Branches 24/42
82.61% Functions 19/23
86.05% Lines 74/86

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              11x 11x 11x 11x 11x   11x 11x 11x 11x   11x 11x 11x 11x 11x 11x                       11x 38x 38x 38x                             11x 38x 38x     11x 38x 38x     11x 38x 38x   38x             11x 38x 38x 38x                           11x 44x                 44x 44x 44x 44x 44x                   44x                     44x                                                     44x           44x 1x 1x 1x     44x 1x 1x 1x     44x         4x                   2x 2x                                           11x                 19x     19x 19x                     19x 12x 4x 4x       19x         19x 4x     8x             8x             8x             8x             8x             8x                       19x                         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, { useMemo, useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { Layout, Text, Button, Table, ButtonVariation, useConfirmationDialog } from '@wings-software/uicore'
import { Color, Intent } from '@harness/design-system'
import { Classes, Menu, Popover, Position } from '@blueprintjs/core'
import type { CellProps, Column, Renderer } from 'react-table'
import ReactTimeago from 'react-timeago'
import moment from 'moment'
import { String, useStrings } from 'framework/strings'
import { TokenAggregateDTO, TokenDTO, useDeleteToken, useListAggregatedTokens } from 'services/cd-ng'
import type { ProjectPathProps, ServiceAccountPathProps } from '@common/interfaces/RouteInterfaces'
import { PageSpinner, TagsPopover, useToaster } from '@common/components'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import { hasNoExpiryDate } from '@rbac/modals/TokenModal/views/utils'
import css from './TokenList.module.scss'
 
interface TokenListProps {
  apiKeyIdentifier: string
  openTokenModal: (apiKeyIdentifier: string, token?: TokenDTO) => void
  refetchTokens: boolean
  reloadApiKey: () => void
  onRefetchComplete: () => void
  apiKeyType: TokenDTO['apiKeyType']
  parentIdentifier?: string
}
 
const RenderColumnDetails: Renderer<CellProps<TokenAggregateDTO>> = ({ row }) => {
  const data = row.original.token
  const { getString } = useStrings()
  return (
    <div>
      <Layout.Horizontal spacing="small">
        <Text color={Color.BLACK} lineClamp={1} className={css.wordBreak}>
          {data.name}
        </Text>
        {data.tags && Object.keys(data.tags).length ? <TagsPopover tags={data.tags} /> : null}
      </Layout.Horizontal>
      <Text color={Color.GREY_400} lineClamp={1} font={{ size: 'small' }} className={css.wordBreak}>
        {getString('idLabel', { id: data.identifier })}
      </Text>
    </div>
  )
}
 
const RenderColumnUpdatedAt: Renderer<CellProps<TokenAggregateDTO>> = ({ row }) => {
  const data = row.original
  return <ReactTimeago date={data.createdAt} minPeriod={60} />
}
 
const RenderColumnLastUpdated: Renderer<CellProps<TokenAggregateDTO>> = ({ row }) => {
  const data = row.original
  return <ReactTimeago date={data.lastModifiedAt} minPeriod={60} />
}
 
const RenderColumnExpiryDate: Renderer<CellProps<TokenAggregateDTO>> = ({ row }) => {
  const data = row.original.token.scheduledExpireTime || row.original.expiryAt
  const { getString } = useStrings()
 
  return (
    <Text>
      {hasNoExpiryDate(data) ? getString('common.noexpiration') : moment(data).format('MM/DD/YYYY hh:mm:ss a')}
    </Text>
  )
}
 
const RenderColumnStatus: Renderer<CellProps<TokenAggregateDTO>> = ({ row }) => {
  const data = row.original
  const isRotated = data.token.scheduledExpireTime
  return (
    <Text
      inline
      icon={isRotated ? 'warning-sign' : 'full-circle'}
      iconProps={{
        size: isRotated ? 12 : 6,
        color: isRotated ? Color.RED_500 : Color.GREEN_500
      }}
    >
      {isRotated ? <String stringID="rbac.token.scheduledToExpire" /> : <String stringID="active" />}
    </Text>
  )
}
 
const RenderColumnMenu: Renderer<CellProps<TokenAggregateDTO>> = ({ row, column }) => {
  const data = row.original.token
  const {
    identifier,
    apiKeyIdentifier,
    accountIdentifier,
    orgIdentifier,
    projectIdentifier,
    parentIdentifier,
    apiKeyType
  } = data
  const [menuOpen, setMenuOpen] = useState(false)
  const { getString } = useStrings()
  const { showSuccess, showError } = useToaster()
  const { mutate: deleteToken } = useDeleteToken({
    queryParams: {
      accountIdentifier,
      orgIdentifier,
      projectIdentifier,
      parentIdentifier,
      apiKeyIdentifier,
      apiKeyType
    }
  })
  const permission = {
    permission: PermissionIdentifier.MANAGE_SERVICEACCOUNT,
    resource: {
      resourceType: ResourceType.SERVICEACCOUNT,
      resourceIdentifier: parentIdentifier
    },
    options: {
      skipCondition: () => apiKeyType === 'USER'
    }
  }
 
  const { openDialog: openDeleteDialog } = useConfirmationDialog({
    contentText: getString('rbac.token.confirmDelete', { name: data.name }),
    titleText: getString('rbac.token.confirmDeleteTitle'),
    confirmButtonText: getString('delete'),
    cancelButtonText: getString('cancel'),
    intent: Intent.DANGER,
    buttonIntent: Intent.DANGER,
    onCloseDialog: async (isConfirmed: boolean) => {
      /* istanbul ignore else */ Iif (isConfirmed) {
        try {
          const deleted = await deleteToken(identifier || '', {
            headers: { 'content-type': 'application/json' }
          })
          /* istanbul ignore else */ Iif (deleted) {
            showSuccess(getString('rbac.token.successMessage', { name: data.name }))
            ;(column as any).reload()
          } else {
            showError(getString('deleteError'))
          }
        } catch (err) {
          /* istanbul ignore next */
          showError(err?.data?.message || err?.message)
        }
      }
    }
  })
 
  const handleDelete = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    openDeleteDialog()
  }
 
  const handleEdit = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    ;(column as any).openTokenModal(apiKeyIdentifier || '', data)
  }
 
  const handleRotate = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    ;(column as any).openTokenModal(apiKeyIdentifier || '', data, true)
  }
 
  return (
    <Layout.Horizontal flex={{ justifyContent: 'flex-end' }}>
      <Popover
        isOpen={menuOpen}
        onInteraction={nextOpenState => {
          setMenuOpen(nextOpenState)
        }}
        className={Classes.DARK}
        position={Position.BOTTOM_RIGHT}
      >
        <Button
          variation={ButtonVariation.ICON}
          icon="Options"
          data-testid={`menu-${data.identifier}`}
          onClick={e => {
            e.stopPropagation()
            setMenuOpen(true)
          }}
        />
        <Menu>
          {data.scheduledExpireTime ? null : (
            <div>
              <RbacMenuItem icon="edit" text={getString('edit')} onClick={handleEdit} permission={permission} />
              <RbacMenuItem
                icon="rotate-page"
                text={getString('rbac.token.rotateLabel')}
                onClick={handleRotate}
                permission={permission}
              />
            </div>
          )}
          <RbacMenuItem icon="trash" text={getString('delete')} onClick={handleDelete} permission={permission} />
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
const TokenList: React.FC<TokenListProps> = ({
  apiKeyIdentifier,
  openTokenModal,
  refetchTokens,
  onRefetchComplete,
  reloadApiKey,
  apiKeyType,
  parentIdentifier
}) => {
  const { accountId, projectIdentifier, orgIdentifier, serviceAccountIdentifier } = useParams<
    ProjectPathProps & ServiceAccountPathProps
  >()
  const { getString } = useStrings()
  const { data, refetch, loading } = useListAggregatedTokens({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      apiKeyType,
      parentIdentifier: parentIdentifier || serviceAccountIdentifier,
      apiKeyIdentifier
    }
  })
 
  useEffect(() => {
    if (refetchTokens) {
      refetch()
      onRefetchComplete()
    }
  }, [refetchTokens])
 
  const onDeleteToken = (): void => {
    reloadApiKey()
    refetch()
  }
 
  const columns: Column<TokenAggregateDTO>[] = useMemo(
    () => [
      {
        Header: getString('token'),
        accessor: row => row.token.name,
        id: 'name',
        width: '20%',
        Cell: RenderColumnDetails
      },
      {
        Header: getString('status'),
        accessor: row => row.token.scheduledExpireTime,
        id: 'status',
        width: '15%',
        Cell: RenderColumnStatus
      },
      {
        Header: getString('common.expiryDate'),
        accessor: row => row.expiryAt,
        id: 'expiryDate',
        width: '30%',
        Cell: RenderColumnExpiryDate
      },
      {
        Header: getString('created'),
        accessor: row => row.createdAt,
        id: 'createdAt',
        width: '15%',
        Cell: RenderColumnUpdatedAt
      },
      {
        Header: getString('lastUpdated'),
        accessor: row => row.lastModifiedAt,
        id: 'lastUpdated',
        width: '15%',
        Cell: RenderColumnLastUpdated
      },
      {
        Header: '',
        accessor: row => row.token.identifier,
        width: '5%',
        id: 'action',
        Cell: RenderColumnMenu,
        disableSortBy: true,
        reload: onDeleteToken,
        openTokenModal
      }
    ],
    [data]
  )
 
  return (
    <>
      <Table<TokenAggregateDTO>
        columns={columns}
        data={data?.data?.content || []}
        bpTableProps={{ bordered: false }}
        className={css.tableList}
      />
      {loading ? <PageSpinner /> : null}
    </>
  )
}
 
export default TokenList