All files / modules/35-connectors/components/CreateConnector/CreateAzureKeyConnector/views SetupVault.tsx

53.33% Statements 32/60
10.1% Branches 10/99
36.36% Functions 4/11
53.33% Lines 32/60

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              219x 219x 219x                             219x 219x 219x 219x                   219x 219x       219x           219x       219x                 2x 2x 2x 2x 2x 2x 2x   2x     2x     2x       2x 1x               2x                                                               2x 1x         2x 1x         2x                                               2x                                                                                                                     219x  
/*
 * 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, useEffect } from 'react'
import * as Yup from 'yup'
import {
  Container,
  Text,
  Formik,
  FormikForm,
  Layout,
  FormInput,
  Button,
  StepProps,
  SelectOption,
  ModalErrorHandlerBinding,
  ModalErrorHandler,
  ButtonVariation,
  shouldShowError
} from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import { useStrings } from 'framework/strings'
import { useToaster } from '@common/exports'
import {
  ConnectorConfigDTO,
  useGetMetadata,
  AzureKeyVaultMetadataRequestSpecDTO,
  AzureKeyVaultMetadataSpecDTO,
  useCreateConnector,
  useUpdateConnector,
  ConnectorRequestBody
} from 'services/cd-ng'
import type { StepDetailsProps, ConnectorDetailsProps } from '@connectors/interfaces/ConnectorInterface'
import { PageSpinner } from '@common/components'
import {
  buildAzureKeyVaultPayload,
  setupAzureKeyVaultNameFormData
} from '@connectors/pages/connectors/utils/ConnectorUtils'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
 
export interface SetupVaultFormData {
  vaultName?: string
}
 
const defaultInitialFormData: SetupVaultFormData = {
  vaultName: undefined
}
 
const SetupVault: React.FC<StepProps<StepDetailsProps> & ConnectorDetailsProps> = ({
  isEditMode,
  accountId,
  connectorInfo,
  prevStepData,
  previousStep,
  nextStep,
  onConnectorCreated
}) => {
  const { getString } = useStrings()
  const { getRBACErrorMessage } = useRBACError()
  const { showSuccess } = useToaster()
  const [initialValues, setInitialValues] = useState(defaultInitialFormData)
  const [vaultNameOptions, setVaultNameOptions] = useState<SelectOption[]>([])
  const [loadingFormData, setLoadingFormData] = useState(isEditMode)
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
 
  const { mutate: getMetadata, loading } = useGetMetadata({
    queryParams: { accountIdentifier: accountId }
  })
  const { mutate: createConnector, loading: creating } = useCreateConnector({
    queryParams: { accountIdentifier: accountId }
  })
  const { mutate: updateConnector, loading: updating } = useUpdateConnector({
    queryParams: { accountIdentifier: accountId }
  })
 
  useEffect(() => {
    Iif (isEditMode && connectorInfo) {
      setupAzureKeyVaultNameFormData(connectorInfo).then(data => {
        setInitialValues(data as SetupVaultFormData)
        setLoadingFormData(false)
      })
    }
  }, [isEditMode, connectorInfo])
 
  const handleFetchEngines = async (formData: ConnectorConfigDTO): Promise<void> => {
    modalErrorHandler?.hide()
    try {
      const { data } = await getMetadata({
        identifier: formData.identifier,
        encryptionType: 'AZURE_VAULT',
        orgIdentifier: formData.orgIdentifier,
        projectIdentifier: formData.projectIdentifier,
        spec: {
          clientId: formData.clientId?.trim(),
          tenantId: formData.tenantId?.trim(),
          subscription: formData.subscription?.trim(),
          secretKey: (connectorInfo as any)?.spec?.secretKey || formData.secretKey?.referenceString,
          delegateSelectors: formData.delegateSelectors
        } as AzureKeyVaultMetadataRequestSpecDTO
      })
 
      setVaultNameOptions(
        (data?.spec as AzureKeyVaultMetadataSpecDTO)?.vaultNames?.map(vaultName => {
          return {
            label: vaultName,
            value: vaultName
          }
        }) || []
      )
    } catch (err) {
      if (shouldShowError(err)) {
        modalErrorHandler?.showDanger(getRBACErrorMessage(err))
      }
    }
  }
 
  useEffect(() => {
    Iif (isEditMode && !loadingFormData && prevStepData) {
      handleFetchEngines(prevStepData as ConnectorConfigDTO)
    }
  }, [isEditMode, loadingFormData, prevStepData])
 
  useEffect(() => {
    Iif (isEditMode && !loadingFormData && loading && connectorInfo) {
      setVaultNameOptions([{ label: connectorInfo.spec.vaultName, value: connectorInfo.spec.vaultName }])
    }
  }, [isEditMode, loadingFormData, loading, connectorInfo])
 
  const handleCreateOrEdit = async (formData: SetupVaultFormData): Promise<void> => {
    modalErrorHandler?.hide()
    if (prevStepData) {
      const data: ConnectorRequestBody = buildAzureKeyVaultPayload({ ...prevStepData, ...formData })
 
      try {
        if (isEditMode) {
          const response = await updateConnector(data)
          nextStep?.({ ...prevStepData, ...formData })
          onConnectorCreated?.(response.data)
          showSuccess(getString('secretManager.editmessageSuccess'))
        } else {
          const response = await createConnector(data)
          nextStep?.({ ...prevStepData, ...formData })
          onConnectorCreated?.(response.data)
          showSuccess(getString('secretManager.createmessageSuccess'))
        }
      } catch (err) {
        /* istanbul ignore next */
        modalErrorHandler?.showDanger(err?.data?.message)
      }
    }
  }
 
  return loadingFormData ? (
    <PageSpinner />
  ) : (
    <Container padding={{ top: 'medium' }} width="64%">
      <Text font={{ variation: FontVariation.H3 }}>{getString('connectors.azureKeyVault.labels.setupVault')}</Text>
      <Container margin={{ bottom: 'xlarge' }}>
        <ModalErrorHandler bind={setModalErrorHandler} />
      </Container>
      <Formik
        formName="azureKeyVaultForm"
        enableReinitialize
        initialValues={initialValues}
        validationSchema={Yup.object().shape({
          vaultName: Yup.string().required(getString('connectors.azureKeyVault.validation.vaultName'))
        })}
        onSubmit={formData => {
          handleCreateOrEdit(formData)
        }}
      >
        <FormikForm>
          <Container height={490}>
            <Layout.Horizontal spacing="medium" flex={{ alignItems: 'flex-start', justifyContent: 'flex-start' }}>
              <FormInput.Select
                name="vaultName"
                label={getString('connectors.azureKeyVault.labels.vaultName')}
                items={vaultNameOptions}
                disabled={vaultNameOptions.length === 0 || loading}
              />
              <Button
                margin={{ top: 'large' }}
                intent="primary"
                text={getString('connectors.azureKeyVault.labels.fetchVault')}
                onClick={() => handleFetchEngines(prevStepData as ConnectorConfigDTO)}
                disabled={loading}
                loading={loading}
              />
            </Layout.Horizontal>
          </Container>
          <Layout.Horizontal spacing="medium">
            <Button
              variation={ButtonVariation.SECONDARY}
              text={getString('back')}
              icon="chevron-left"
              onClick={() => previousStep?.(prevStepData)}
            />
            <Button
              type="submit"
              intent="primary"
              rightIcon="chevron-right"
              text={getString('saveAndContinue')}
              disabled={creating || updating}
            />
          </Layout.Horizontal>
        </FormikForm>
      </Formik>
    </Container>
  )
}
 
export default SetupVault