All files / modules/35-connectors/components/CreateConnector/AWSCodeCommitConnector AWSCCAuthStep.tsx

84.62% Statements 44/52
30.65% Branches 19/62
85.71% Functions 6/7
84.62% Lines 44/52

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              219x 219x 219x                         219x 219x 219x 219x             219x 219x 219x 219x   219x 219x 219x 219x                 219x 4x 4x 3x 3x 3x 3x 3x 3x       3x 3x   3x 1x 1x                                         3x 1x 1x 1x   1x       1x 1x 1x   1x 1x       1x       3x       3x                         1x             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, useEffect } from 'react'
import cx from 'classnames'
import {
  StepProps,
  Formik,
  FormikForm,
  Layout,
  Text,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  Button,
  ButtonVariation,
  Container,
  PageSpinner
} from '@wings-software/uicore'
import * as Yup from 'yup'
import { FontVariation } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import {
  useCreateConnector,
  useUpdateConnector,
  ConnectorConfigDTO,
  ConnectorRequestBody,
  ConnectorInfoDTO
} from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import SecretInput from '@secrets/components/SecretInput/SecretInput'
import TextReference, { ValueType } from '@secrets/components/TextReference/TextReference'
import { buildAWSCodeCommitPayload } from '@connectors/pages/connectors/utils/ConnectorUtils'
import type { ProjectPathProps, AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useToaster } from '@common/exports'
import { setSecretField } from '@secrets/utils/SecretField'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from '../commonSteps/ConnectorCommonStyles.module.scss'
 
interface AWSCCAuthStepProps extends StepProps<ConnectorConfigDTO> {
  isEditMode: boolean
  connectorInfo?: ConnectorInfoDTO
  onSuccess?: (data?: ConnectorRequestBody) => void | Promise<void>
  setIsEditMode: (val: boolean) => void
}
 
export default function AWSCCAuthStep(props: AWSCCAuthStepProps) {
  const { showSuccess } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps & AccountPathProps>()
  const [loadingSecrets, setLoadingSecrets] = useState(props.isEditMode)
  const [isSaving, setIsSaving] = useState(false)
  const [initialValues, setInitialValues] = useState<ConnectorConfigDTO>({
    accessKey: undefined,
    secretKey: undefined
  })
  const { mutate: createConnector } = useCreateConnector({ queryParams: { accountIdentifier: accountId } })
  const { mutate: updateConnector } = useUpdateConnector({ queryParams: { accountIdentifier: accountId } })
 
  useEffect(() => {
    ;(async () => {
      Iif (props.isEditMode) {
        const { accessKey, accessKeyRef, secretKeyRef } = props.connectorInfo?.spec?.authentication?.spec?.spec ?? {}
        setInitialValues({
          accessKey:
            accessKey || accessKeyRef
              ? {
                  value: accessKeyRef || accessKey,
                  type: accessKeyRef ? ValueType.ENCRYPTED : ValueType.TEXT
                }
              : undefined,
          secretKey: await setSecretField(secretKeyRef, {
            accountIdentifier: accountId,
            projectIdentifier,
            orgIdentifier
          })
        })
        setLoadingSecrets(false)
      }
    })()
  }, [])
 
  const handleSubmit = async (formData: ConnectorConfigDTO) => {
    try {
      modalErrorHandler?.hide()
      setIsSaving(true)
      let response
      Iif (props.isEditMode) {
        response = await updateConnector(buildAWSCodeCommitPayload(formData))
        showSuccess(getString('connectors.successfullUpdate', { name: formData.name }))
      } else {
        response = await createConnector(buildAWSCodeCommitPayload(formData))
        props.setIsEditMode(true)
        showSuccess(getString('connectors.successfullCreate', { name: formData.name }))
      }
      props.onSuccess?.(response.data)
      props.nextStep?.({ ...props.prevStepData, ...formData })
    } catch (e) {
      modalErrorHandler?.showDanger(getRBACErrorMessage(e))
    } finally {
      setIsSaving(false)
    }
  }
 
  Iif (loadingSecrets) {
    return <PageSpinner />
  }
 
  return (
    <Layout.Vertical width="60%" style={{ minHeight: 460 }} className={css.stepContainer}>
      <ModalErrorHandler bind={setModalErrorHandler} />
      <Text font={{ variation: FontVariation.H3 }}>{getString('credentials')}</Text>
 
      <Formik
        initialValues={{ ...initialValues, ...props.prevStepData }}
        validationSchema={Yup.object().shape({
          accessKey: Yup.object().required(getString('connectors.aws.validation.accessKey')),
          secretKey: Yup.mixed().required(getString('connectors.aws.validation.secretKeyRef'))
        })}
        formName="awsCcAuthForm"
        onSubmit={formData => {
          handleSubmit({
            ...formData,
            projectIdentifier,
            orgIdentifier
          })
        }}
      >
        {formikPros => (
          <FormikForm className={cx(css.fullHeight, css.fullHeightDivsWithFlex)}>
            <Container className={css.paddingTop8}>
              <Text font={{ variation: FontVariation.H6 }}>{getString('authentication')}</Text>
              <TextReference
                name="accessKey"
                stringId="connectors.aws.accessKey"
                type={(formikPros.values as any)?.accessKey?.type}
              />
              <SecretInput name="secretKey" label={getString('connectors.aws.secretKey')} />
            </Container>
            <Layout.Horizontal spacing="medium">
              <Button
                icon="chevron-left"
                onClick={() => props.previousStep?.({ ...props.prevStepData })}
                text={getString('back')}
                variation={ButtonVariation.SECONDARY}
              />
              <Button
                type="submit"
                intent="primary"
                rightIcon="chevron-right"
                text={getString('saveAndContinue')}
                disabled={isSaving}
                variation={ButtonVariation.PRIMARY}
              />
            </Layout.Horizontal>
          </FormikForm>
        )}
      </Formik>
    </Layout.Vertical>
  )
}