All files / modules/33-auth-settings/pages/Configuration/AccountAndOAuth/OAuthProviders PublicOAuthProviders.tsx

97.4% Statements 75/77
85.54% Branches 71/83
100% Functions 11/11
97.37% Lines 74/76

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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236              3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x                 3x 8x 8x 8x 8x   8x         8x   14x     8x 14x       8x         8x           8x           8x   8x 5x     8x           1x 1x 1x             1x 1x 1x   1x 1x 1x                         8x 2x   2x         2x 1x 1x 6x     1x 1x 1x             1x 1x 1x                 1x 1x       8x 3x   3x 1x 1x         2x 5x   1x     2x 2x         2x 2x 2x             8x   8x                                                     45x 42x                                               3x  
/*
 * Copyright 2022 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, { Dispatch, SetStateAction } from 'react'
import { useParams } from 'react-router-dom'
import { Collapse, Text, Container, Card, Switch, useConfirmationDialog } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useToaster } from '@common/components'
import { useStrings } from 'framework/strings'
import type { AuthenticationSettingsResponse, OAuthSettings } from 'services/cd-ng'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useUpdateOauthProviders, useUpdateAuthMechanism, useRemoveOauthMechanism } from 'services/cd-ng'
import { AuthenticationMechanisms } from '@auth-settings/constants/utils'
import { OAuthProviders, Providers } from '@common/constants/OAuthProviders'
import { useFeature } from '@common/hooks/useFeatures'
import { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import FeatureSwitch from '@rbac/components/Switch/Switch'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from './PublicOAuthProviders.module.scss'
import cssConfiguration from '@auth-settings/pages/Configuration/Configuration.module.scss'
 
interface Props {
  authSettings: AuthenticationSettingsResponse
  refetchAuthSettings: () => void
  canEdit: boolean
  setUpdating: Dispatch<SetStateAction<boolean>>
}
 
const PublicOAuthProviders: React.FC<Props> = ({ authSettings, refetchAuthSettings, canEdit, setUpdating }) => {
  const { accountId } = useParams<AccountPathProps>()
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
  const { showError, showSuccess, showWarning } = useToaster()
 
  const { enabled: featureEnabled } = useFeature({
    featureRequest: {
      featureName: FeatureIdentifier.OAUTH_SUPPORT
    }
  })
  const samlOrLdapSettings = authSettings.ngAuthSettings?.find(
    settings =>
      settings.settingsType === AuthenticationMechanisms.SAML || settings.settingsType === AuthenticationMechanisms.LDAP
  )
 
  const oauthSettings: OAuthSettings | undefined = authSettings.ngAuthSettings?.find(
    settings => settings.settingsType === AuthenticationMechanisms.OAUTH
  )
 
  const oauthEnabled =
    !!oauthSettings &&
    (authSettings.authenticationMechanism === AuthenticationMechanisms.USER_PASSWORD ||
      authSettings.authenticationMechanism === AuthenticationMechanisms.OAUTH) &&
    !samlOrLdapSettings
 
  const { mutate: updateOAuthProviders, loading: updatingOauthProviders } = useUpdateOauthProviders({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: deleteOAuthProviders, loading: deletingOauthProviders } = useRemoveOauthMechanism({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: updateAuthMechanism, loading: updatingAuthMechanism } = useUpdateAuthMechanism({})
 
  React.useEffect(() => {
    setUpdating(updatingOauthProviders || deletingOauthProviders || updatingAuthMechanism)
  }, [updatingOauthProviders, deletingOauthProviders, updatingAuthMechanism, setUpdating])
 
  const { openDialog: confirmOAuthDisable } = useConfirmationDialog({
    titleText: getString('authSettings.disableOAuthLogin'),
    contentText: getString('authSettings.confirmDisableOAuthLogin'),
    confirmButtonText: getString('confirm'),
    cancelButtonText: getString('cancel'),
    onCloseDialog: async isConfirmed => {
      /* istanbul ignore else */ if (isConfirmed) {
        try {
          const response = await updateAuthMechanism(undefined, {
            queryParams: {
              accountIdentifier: accountId,
              authenticationMechanism: AuthenticationMechanisms.USER_PASSWORD
            }
          })
 
          /* istanbul ignore else */ if (response) {
            try {
              const deleted = await deleteOAuthProviders('' as any)
 
              /* istanbul ignore else */ if (deleted) {
                refetchAuthSettings()
                showSuccess(getString('authSettings.publicOAuthLoginDisabled'), 5000)
              }
            } catch (e) {
              /* istanbul ignore next */ showError(getRBACErrorMessage(e), 5000)
            }
          }
        } catch (e) {
          /* istanbul ignore next */ showError(getRBACErrorMessage(e), 5000)
        }
      }
    }
  })
 
  const toggleOAuthProviders = async (e: React.FormEvent<HTMLInputElement>): Promise<void> => {
    const enable = e.currentTarget.checked
 
    Iif (samlOrLdapSettings) {
      showWarning(getString('authSettings.pleaseRemoveSAMLOrLDAPToEnableOauth'))
      return
    }
 
    if (!oauthEnabled && enable) {
      try {
        const response = await updateOAuthProviders({
          allowedProviders: OAuthProviders.map(provider => provider.type) as Providers[],
          settingsType: AuthenticationMechanisms.OAUTH
        })
        /* istanbul ignore else */ if (response) {
          try {
            const authMechanismUpdated = await updateAuthMechanism(undefined, {
              queryParams: {
                accountIdentifier: accountId,
                authenticationMechanism: AuthenticationMechanisms.OAUTH
              }
            })
 
            /* istanbul ignore else */ if (authMechanismUpdated) {
              refetchAuthSettings()
              showSuccess(getString('authSettings.publicOAuthLoginEnabled'), 5000)
            }
          } catch (err) {
            /* istanbul ignore next */ showError(getRBACErrorMessage(err), 5000)
          }
        }
      } catch (err) {
        /* istanbul ignore next */ showError(getRBACErrorMessage(err), 5000)
      }
    } /* istanbul ignore else */ else Eif (oauthEnabled && !enable) {
      confirmOAuthDisable()
    }
  }
 
  const handleOAuthChange = async (e: React.FormEvent<HTMLInputElement>): Promise<void> => {
    const { value, checked } = e.currentTarget
 
    if (oauthSettings?.allowedProviders?.length === 1 && !checked) {
      showWarning(getString('authSettings.keepAtLeastOneProviderEnabled'))
      return
    }
 
    let allowedProviders: Providers[]
 
    if (oauthSettings?.allowedProviders?.includes(value as Providers)) {
      allowedProviders = oauthSettings.allowedProviders.filter(provider => provider !== value)
    } else {
      allowedProviders = [...(oauthSettings?.allowedProviders || []), value as Providers]
    }
 
    try {
      const response = await updateOAuthProviders({
        allowedProviders,
        settingsType: AuthenticationMechanisms.OAUTH
      })
 
      /* istanbul ignore else */ if (response) {
        refetchAuthSettings()
        showSuccess(getString('authSettings.oauthSettingsHaveBeenUpdated'), 5000)
      }
    } catch (err) {
      /* istanbul ignore next */ showError(getRBACErrorMessage(err), 5000)
    }
  }
 
  const loading = updatingOauthProviders || updatingAuthMechanism || deletingOauthProviders
 
  return (
    <Collapse
      isOpen={oauthEnabled && featureEnabled}
      collapseHeaderClassName={cssConfiguration.collapseHeaderClassName}
      collapseClassName={cssConfiguration.collapseClassName}
      collapsedIcon="main-chevron-down"
      expandedIcon="main-chevron-up"
      heading={
        <FeatureSwitch
          featureProps={{ featureRequest: { featureName: FeatureIdentifier.OAUTH_SUPPORT } }}
          label={getString('authSettings.usePublicOAuth')}
          font={{ weight: 'semi-bold', size: 'normal' }}
          color={Color.GREY_800}
          checked={oauthEnabled}
          onChange={toggleOAuthProviders}
          disabled={
            !featureEnabled ||
            !canEdit ||
            loading ||
            authSettings.authenticationMechanism === AuthenticationMechanisms.SAML
          }
          data-testid="toggle-oauth-providers"
        />
      }
    >
      {oauthSettings && (
        <Container className={css.container} margin={{ bottom: 'large' }}>
          {OAuthProviders.sort((a, b) => a.name.localeCompare(b.name)).map(provider => {
            return (
              <Card key={provider.type} className={css.card}>
                <Switch
                  labelElement={
                    <Text icon={provider.iconName} iconProps={{ size: 25 }} color={Color.BLACK}>
                      {provider.name}
                    </Text>
                  }
                  value={provider.type}
                  checked={oauthSettings?.allowedProviders?.includes(provider.type as Providers)}
                  onChange={handleOAuthChange}
                  disabled={!featureEnabled || !canEdit || loading}
                  className={css.switch}
                  data-testid={`toggle-oauth-${provider.type.toLowerCase()}`}
                />
              </Card>
            )
          })}
        </Container>
      )}
    </Collapse>
  )
}
 
export default PublicOAuthProviders