All files / modules/20-rbac/modals/LinkToSSOProviderModal/views LinkToSSOProviderForm.tsx

95.45% Statements 42/44
62.96% Branches 34/54
100% Functions 9/9
95.35% Lines 41/43

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              11x 11x                             11x 11x 11x   11x 11x   11x 11x 11x                     11x         9x     9x     11x 5x 5x 5x 5x 5x 5x 5x   5x           5x           5x   5x                   5x   5x   2x 1x               5x 1x 1x 1x 1x 1x 1x                 5x                                     1x         9x                               2x                                                           11x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Free Trial 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/05/PolyForm-Free-Trial-1.0.0.txt.
 */
 
import React, { useState, useMemo } from 'react'
import {
  Button,
  Container,
  Formik,
  FormikForm as Form,
  Layout,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  Text,
  SelectOption,
  ButtonVariation,
  FormInput,
  PageError,
  shouldShowError
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import * as Yup from 'yup'
import { useParams } from 'react-router-dom'
import type { StringsMap } from 'framework/strings/StringsContext'
import { useToaster } from '@common/components'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import { UserGroupDTO, SAMLSettings, useGetAuthenticationSettings, useLinkToSamlGroup } from 'services/cd-ng'
import css from '../useLinkToSSOProviderModal.module.scss'
interface LinkToSSOProviderModalData {
  userGroupData: UserGroupDTO
  onSubmit?: () => void
}
 
export interface LinkToSSOProviderFormData {
  groupName: string
  sso: string
}
 
const getSelectPlaceholder = (
  ssoSettings: SelectOption[],
  fetching: boolean,
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
): string => {
  const dataPlaceholder = !ssoSettings.length
    ? getString('noData')
    : getString('rbac.userDetails.linkToSSOProviderModal.selectSSOSetting')
  return fetching ? getString('loading') : dataPlaceholder
}
 
const LinkToSSOProviderForm: React.FC<LinkToSSOProviderModalData> = props => {
  const { onSubmit, userGroupData } = props
  const { getRBACErrorMessage } = useRBACError()
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const { getString } = useStrings()
  const { showSuccess } = useToaster()
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding>()
  const [selectedSso, setSelectedSso] = useState<SelectOption>()
 
  let fetching = false
  const {
    data: authDataResponse,
    loading: authLoading,
    error,
    refetch
  } = useGetAuthenticationSettings({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const authSettingsData = authDataResponse?.resource?.ngAuthSettings as SAMLSettings[]
 
  const { mutate: linkSsoGroup, loading: linking } = useLinkToSamlGroup({
    userGroupId: userGroupData.identifier,
    samlId: selectedSso?.value as string,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
 
  fetching = linking || authLoading
 
  const ssoSettings: SelectOption[] = useMemo(
    () =>
      ((authSettingsData || []).filter(el => el.settingsType === 'SAML' && el.authorizationEnabled) || []).map(data => {
        return {
          label: data.displayName || data.identifier,
          value: data.identifier
        }
      }) || [],
    [authSettingsData]
  )
 
  const handleOnSubmit = async (values: LinkToSSOProviderFormData): Promise<void> => {
    modalErrorHandler?.hide()
    try {
      const created = await linkSsoGroup({ samlGroupName: values.groupName })
      Eif (created) {
        showSuccess(getString('rbac.userGroupForm.createSuccess', { name: values.groupName }))
        onSubmit?.()
      }
    } catch (err) {
      if (shouldShowError(err)) {
        modalErrorHandler?.showDanger(getRBACErrorMessage(err))
      }
    }
  }
 
  return (
    <Layout.Vertical padding="xlarge">
      <Layout.Vertical spacing="large">
        <Text color={Color.BLACK} font="medium">
          {getString('rbac.userDetails.linkToSSOProviderModal.linkLabel')}
        </Text>
        {error ? (
          <PageError message={(error.data as any)?.message || error.message} onClick={refetch as any} />
        ) : (
          <Formik<LinkToSSOProviderFormData>
            formName="linkToSSOProviderForm"
            initialValues={{ groupName: '', sso: '' }}
            validationSchema={Yup.object().shape({
              groupName: Yup.string()
                .trim()
                .required(getString('rbac.userDetails.linkToSSOProviderModal.validation.groupNameRequired')),
              sso: Yup.string().required(getString('rbac.userDetails.linkToSSOProviderModal.validation.ssoIdRequired'))
            })}
            onSubmit={values => {
              handleOnSubmit(values)
            }}
            enableReinitialize
          >
            {() => {
              return (
                <Form>
                  <Container margin={{ bottom: 'medium' }}>
                    <Container padding={{ bottom: 'medium' }}>
                      <ModalErrorHandler bind={setModalErrorHandler} />
                    </Container>
                    <Layout.Vertical spacing="medium">
                      <Layout.Vertical flex={{ alignItems: 'end' }} spacing="xsmall">
                        <FormInput.Select
                          name="sso"
                          disabled={fetching}
                          className={css.select}
                          items={ssoSettings}
                          value={selectedSso}
                          placeholder={getSelectPlaceholder(ssoSettings, fetching, getString)}
                          onChange={value => {
                            setSelectedSso(value)
                          }}
                        />
                      </Layout.Vertical>
                      <FormInput.Text
                        disabled={!selectedSso || fetching}
                        name="groupName"
                        label={getString('rbac.userDetails.linkToSSOProviderModal.groupNameLabel')}
                      />
                    </Layout.Vertical>
                  </Container>
                  <Layout.Horizontal>
                    <Button
                      variation={ButtonVariation.PRIMARY}
                      data-testid="submitLinkSSOProvider"
                      text={getString('save')}
                      type="submit"
                      disabled={fetching}
                    />
                  </Layout.Horizontal>
                </Form>
              )
            }}
          </Formik>
        )}
      </Layout.Vertical>
    </Layout.Vertical>
  )
}
 
export default LinkToSSOProviderForm