All files / modules/30-secrets/components/TextReference TextReference.tsx

90.74% Statements 49/54
71.43% Branches 55/77
90% Functions 9/10
90.74% Lines 49/54

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              273x 273x 273x 273x 273x 273x 273x     273x 273x 273x 273x     273x 273x   273x 273x 273x                                             273x 177x       273x 193x 177x 177x   177x 177x   177x 50x 43x   7x       177x 49x               177x   1x 1x                 1x                 1x     1x   177x 49x 49x 26x 23x 1x 1x         177x   177x   177x                                                                   2x     2x                                   273x  
/*
 * 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, { useEffect } from 'react'
import { useParams } from 'react-router-dom'
import cx from 'classnames'
import { get, isPlainObject } from 'lodash-es'
import { FormikContext, connect } from 'formik'
import { Classes, FormGroup, Intent } from '@blueprintjs/core'
import { FormInput, Layout, Container, FormikTooltipContext, DataTooltipInterface } from '@wings-software/uicore'
import type { StringsMap } from 'stringTypes'
 
import { useStrings } from 'framework/strings'
import StringWithTooltip from '@common/components/StringWithTooltip/StringWithTooltip'
import { useToaster } from '@common/exports'
import SecretInput from '@secrets/components/SecretInput/SecretInput'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
 
import { getSecretV2Promise } from 'services/cd-ng'
import css from './TextReference.module.scss'
 
export enum ValueType {
  TEXT = 'TEXT',
  ENCRYPTED = 'ENCRYPTED'
}
 
export interface TextReferenceInterface {
  value: string
  type: ValueType
}
interface TextReferenceProps {
  name: string
  label?: string
  className?: string
  type?: string
  allowSelection?: boolean
  privateSecret?: boolean
  placeHolder?: string
  stringId?: keyof StringsMap
}
 
interface FormikTextReference extends TextReferenceProps {
  formik: FormikContext<any>
  tooltipProps?: DataTooltipInterface
}
 
const errorCheck = (name: string, formik?: FormikContext<any>) =>
  (get(formik?.touched, name) || (formik?.submitCount && formik?.submitCount > 0)) &&
  get(formik?.errors, name) &&
  !isPlainObject(get(formik?.errors, name))
 
const TextReference: React.FC<FormikTextReference> = props => {
  const { getString } = useStrings()
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
  const { showError } = useToaster()
 
  const { formik, name, allowSelection, privateSecret } = props
  const hasError = errorCheck(props.name, formik)
 
  useEffect(() => {
    if (props.type) {
      formik.setFieldValue(`${name}fieldType`, props.type)
    } else {
      formik.setFieldValue(`${name}fieldType`, ValueType.TEXT)
    }
  }, [props.type])
 
  useEffect(() => {
    Iif (formik.values[`${name}secretField`]) {
      formik.setFieldValue(props.name, {
        value: formik.values[`${name}secretField`].referenceString,
        type: ValueType.ENCRYPTED
      })
    }
  }, [formik.values[`${name}secretField`]])
 
  const getSecretInfo = async (secretString: string) => {
    let val
    try {
      const response = await getSecretV2Promise({
        identifier: secretString.indexOf('.') < 0 ? secretString : secretString.split('.')[1],
        queryParams: {
          accountIdentifier: accountId,
          orgIdentifier: orgIdentifier,
          projectIdentifier: projectIdentifier
        }
      })
 
      val = {
        identifier: response.data?.secret.identifier,
        name: response.data?.secret.name || secretString.split('.')[1],
        referenceString: secretString,
        accountIdentifier: accountId,
        orgIdentifier: orgIdentifier,
        projectIdentifier: projectIdentifier
      }
    } catch (e) {
      showError(e.message)
    }
 
    return val
  }
  useEffect(() => {
    const type = get(formik.values, `${props.name}.type`)
    if (type === ValueType.TEXT) {
      formik.setFieldValue(`${name}textField`, get(formik.values, `${props.name}.value`))
    } else if (type === ValueType.ENCRYPTED) {
      getSecretInfo(get(formik.values, `${props.name}.value`)).then(data => {
        formik.setFieldValue(`${name}secretField`, data)
      })
    }
  }, [])
 
  const tooltipContext = React.useContext(FormikTooltipContext)
  const dataTooltipId =
    props.tooltipProps?.dataTooltipId || (tooltipContext?.formName ? `${tooltipContext?.formName}_${name}` : '')
 
  return (
    <FormGroup helperText={hasError ? get(formik?.errors, name) : null} intent={hasError ? Intent.DANGER : Intent.NONE}>
      <Layout.Vertical className={props.className}>
        <div className={css.label}>
          {props.stringId && (
            <StringWithTooltip
              tooltipId={dataTooltipId}
              stringId={props.stringId}
              className={cx(Classes.LABEL, css.stringWithTooltipLabel)}
            />
          )}
          <FormInput.DropDown
            name={`${name}fieldType`}
            items={[
              { label: getString('plaintext'), value: ValueType.TEXT },
              { label: getString('encrypted'), value: ValueType.ENCRYPTED }
            ]}
            onChange={() => {
              formik.setFieldValue(props.name, undefined)
              formik.setFieldValue(`${name}textField`, undefined)
              formik.setFieldValue(`${name}secretField`, undefined)
            }}
            dropDownProps={{
              isLabel: true,
              filterable: false,
              minWidth: 'unset'
            }}
          />
        </div>
        {get(formik.values, `${name}fieldType`) === ValueType.TEXT ? (
          <FormInput.Text
            name={`${name}textField`}
            placeholder={props.placeHolder}
            onChange={e => {
              Iif ((e.target as any).value === '') {
                formik.setFieldValue(props.name, undefined)
              } else {
                formik.setFieldValue(props.name, {
                  value: (e.target as any).value,
                  type: ValueType.TEXT
                })
              }
            }}
            className={css.textCss}
          />
        ) : (
          <Container className={css.secretField}>
            <SecretInput name={`${name}secretField`} allowSelection={allowSelection} privateSecret={privateSecret} />
          </Container>
        )}
      </Layout.Vertical>
    </FormGroup>
  )
}
 
export default connect<Omit<FormikTextReference, 'formik'>>(TextReference)