All files / modules/75-cf/components/AddKeyDialog AddKeyDialog.tsx

92.11% Statements 35/38
60% Branches 6/10
76.92% Functions 10/13
91.67% Lines 33/36

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              4x 4x 4x 4x                     4x 4x 4x 4x 4x 4x   4x 4x 4x 4x                               4x 12x 12x 12x                 12x                 24x   12x         26x   12x 1x         1x       12x             12x 2x                                                         13x                           26x                 1x                           12x                               4x  
/*
 * 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 from 'react'
import { Dialog, Spinner } from '@blueprintjs/core'
import * as yup from 'yup'
import {
  Button,
  ButtonProps,
  CardSelect,
  Container,
  Formik,
  FormInput,
  Label,
  Layout,
  Text
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { AddAPIKeyQueryParams, ApiKey, useAddAPIKey } from 'services/cf/index'
import { useEnvStrings } from '@cf/hooks/environment'
import { useToaster } from '@common/exports'
import { getIdentifierFromName } from '@common/utils/StringUtils'
import { EnvironmentSDKKeyType, getErrorMessage } from '@cf/utils/CFUtils'
import type { EnvironmentResponseDTO } from 'services/cd-ng'
import RbacButton from '@rbac/components/Button/Button'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import css from './AddKeyDialog.module.scss'
 
interface Props {
  disabled?: boolean
  primary?: boolean
  environment: EnvironmentResponseDTO
  onCreate: (newKey: ApiKey, hideModal: () => void) => void
  buttonProps?: ButtonProps
  keyType?: EnvironmentSDKKeyType
}
 
interface KeyValues {
  name: string
  type: EnvironmentSDKKeyType
}
 
const AddKeyDialog: React.FC<Props> = ({ disabled, primary, environment, onCreate, buttonProps, keyType }) => {
  const { showError } = useToaster()
  const { getString, getEnvString } = useEnvStrings()
  const { mutate: createKey, loading } = useAddAPIKey({
    queryParams: {
      accountIdentifier: environment.accountId as string,
      environmentIdentifier: environment.identifier as string,
      orgIdentifier: environment.orgIdentifier as string,
      projectIdentifier: environment.projectIdentifier as string
    } as AddAPIKeyQueryParams
  })
 
  const keyTypes = [
    {
      text: getEnvString('apiKeys.clientType'),
      value: EnvironmentSDKKeyType.CLIENT
    },
    {
      text: getEnvString('apiKeys.serverType'),
      value: EnvironmentSDKKeyType.SERVER
    }
  ].filter(type => !keyType || keyType === type.value)
 
  const initialValues: KeyValues = {
    name: '',
    type: keyType || EnvironmentSDKKeyType.SERVER
  }
 
  const getTypeOption = (value: string) => keyTypes.find(k => k.value === value) || keyTypes[0]
 
  const handleSubmit = (values: KeyValues): void => {
    createKey({
      identifier: getIdentifierFromName(values.name),
      name: values.name,
      type: values.type === 'server' ? 'Server' : 'Client'
    })
      .then((created: ApiKey) => onCreate(created, hideModal))
      .catch(error => showError(getErrorMessage(error), undefined, 'cf.create.key.error'))
  }
 
  const labelStyle = {
    color: '#627386',
    fontWeight: 500,
    fontSize: '12px',
    lineHeight: '16px'
  }
 
  const [openModal, hideModal] = useModalHook(() => {
    return (
      <Dialog
        isOpen
        enforceFocus={false}
        onClose={hideModal}
        title={
          <Text
            style={{
              fontWeight: 600,
              fontSize: '14px',
              color: 'var(--black)',
              lineHeight: '20px',
              padding: 'var(--spacing-large) 0 0 var(--spacing-small)'
            }}
          >
            {getEnvString('apiKeys.addKeyTitle')}
          </Text>
        }
      >
        <Formik
          initialValues={initialValues}
          formName="addKeyDialog"
          validationSchema={yup.object().shape({
            name: yup.string().trim().required(getEnvString('apiKeys.emptyName'))
          })}
          onSubmit={handleSubmit}
          onReset={hideModal}
        >
          {formikProps => (
            <Layout.Vertical spacing="large" padding="xxlarge">
              <Layout.Vertical spacing="small">
                <Label style={labelStyle}>{getString('name')}</Label>
                <FormInput.Text name="name" inputGroup={{ autoFocus: true }} />
              </Layout.Vertical>
              <Layout.Vertical spacing="small">
                <Label style={labelStyle}>{getEnvString('apiKeys.keyType')}</Label>
                <CardSelect
                  cornerSelected
                  data={keyTypes}
                  selected={getTypeOption(formikProps.values.type)}
                  className={css.cardSelect}
                  onChange={nextValue => formikProps.setFieldValue('type', nextValue.value)}
                  renderItem={cardData => (
                    <Container flex={{ align: 'center-center', distribution: 'space-between' }} className="cardBody">
                      {cardData.text}
                    </Container>
                  )}
                />
              </Layout.Vertical>
              <Layout.Horizontal padding={{ top: 'xxxlarge' }}>
                <Button
                  text={getString('createSecretYAML.create')}
                  onClick={() => formikProps.handleSubmit()}
                  intent="primary"
                  disabled={loading}
                />
                <Button text={getString('cancel')} onClick={() => formikProps.handleReset()} minimal />
                {loading && <Spinner size={16} />}
              </Layout.Horizontal>
            </Layout.Vertical>
          )}
        </Formik>
      </Dialog>
    )
  }, [loading, keyType])
 
  return (
    <RbacButton
      disabled={disabled}
      onClick={openModal}
      text={getString('cf.environments.apiKeys.addKey')}
      minimal={!primary}
      intent="primary"
      permission={{
        resource: { resourceType: ResourceType.ENVIRONMENT, resourceIdentifier: environment.identifier },
        permission: PermissionIdentifier.EDIT_ENVIRONMENT
      }}
      {...buttonProps}
    />
  )
}
 
export default AddKeyDialog