All files / modules/20-rbac/modals/RoleAssignmentModal/views RoleAssignment.tsx

74.29% Statements 26/35
42.86% Branches 6/14
33.33% Functions 2/6
74.29% Lines 26/35

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              16x 16x                   16x 16x 16x 16x 16x 16x     16x 16x 16x 16x                                 16x               4x 4x 4x 4x 4x 4x 4x 4x   4x       4x                                         4x                                         14x                                                                       16x  
/*
 * 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 } from 'react'
import {
  Button,
  Formik,
  FormikForm as Form,
  Layout,
  ModalErrorHandlerBinding,
  FormInput,
  ModalErrorHandler,
  ButtonVariation
} from '@wings-software/uicore'
import * as Yup from 'yup'
import { useParams } from 'react-router-dom'
import { defaultTo } from 'lodash-es'
import { useToaster } from '@common/components'
import { usePostRoleAssignments, RoleAssignment as RBACRoleAssignment } from 'services/rbac'
import { useStrings } from 'framework/strings'
import type { RoleAssignmentMetadataDTO, ServiceAccountDTO, UserGroupDTO } from 'services/cd-ng'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { getAssignments, isNewRoleAssignment, PrincipalType } from '@rbac/utils/utils'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { isCDCommunity, useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import RoleAssignmentForm from './RoleAssignmentForm'
import type { Assignment } from './UserRoleAssigment'
 
interface RoleAssignmentData {
  principalInfo: UserGroupDTO | ServiceAccountDTO
  type: PrincipalType
  roleBindings?: RoleAssignmentMetadataDTO[]
  onSubmit?: () => void
  onCancel?: () => void
  onSuccess?: () => void
}
 
export interface RoleAssignmentValues {
  name?: string
  assignments: Assignment[]
}
 
const RoleAssignment: React.FC<RoleAssignmentData> = ({
  principalInfo,
  roleBindings,
  onSubmit,
  onSuccess,
  onCancel,
  type
}) => {
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const { getRBACErrorMessage } = useRBACError()
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding>()
  const { getString } = useStrings()
  const { licenseInformation } = useLicenseStore()
  const isCommunity = isCDCommunity(licenseInformation)
  const { showSuccess } = useToaster()
  const assignments: Assignment[] = getAssignments(defaultTo(roleBindings, []))
 
  const { mutate: createRoleAssignment, loading: saving } = usePostRoleAssignments({
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier }
  })
 
  const handleRoleAssignment = async (values: RoleAssignmentValues): Promise<void> => {
    const dataToSubmit: RBACRoleAssignment[] = values.assignments
      .filter(value => isNewRoleAssignment(value))
      .map(value => {
        return {
          resourceGroupIdentifier: value.resourceGroup.value.toString(),
          roleIdentifier: value.role.value.toString(),
          principal: { identifier: principalInfo.identifier, type }
        }
      })
 
    try {
      await createRoleAssignment({ roleAssignments: dataToSubmit })
      showSuccess(getString('rbac.usersPage.roleAssignSuccess'))
      onSubmit?.()
    } catch (e) {
      /* istanbul ignore next */
      modalErrorHandler?.showDanger(getRBACErrorMessage(e))
    }
  }
 
  return (
    <Formik<RoleAssignmentValues>
      initialValues={{
        name: principalInfo.name,
        assignments: assignments
      }}
      formName={`${type}RoleAssignmentForm`}
      validationSchema={Yup.object().shape({
        assignments: Yup.array().of(
          Yup.object().shape({
            role: Yup.object().nullable().required(),
            resourceGroup: Yup.object().nullable().required()
          })
        )
      })}
      onSubmit={values => {
        modalErrorHandler?.hide()
        handleRoleAssignment(values)
      }}
    >
      {formik => {
        return (
          <Form>
            <ModalErrorHandler bind={setModalErrorHandler} />
            <FormInput.Text
              name="name"
              disabled={true}
              label={type === PrincipalType.USER_GROUP ? getString('common.userGroup') : getString('serviceAccount')}
            />
            {!isCommunity && (
              <RoleAssignmentForm
                noRoleAssignmentsText={
                  type === PrincipalType.USER_GROUP
                    ? getString('rbac.userGroupPage.noRoleAssignmentsText')
                    : getString('rbac.serviceAccounts.form.noDataText')
                }
                formik={formik}
                onSuccess={onSuccess}
              />
            )}
 
            <Layout.Horizontal spacing="small">
              <Button
                variation={ButtonVariation.PRIMARY}
                text={getString('common.apply')}
                type="submit"
                disabled={saving}
              />
              <Button text={getString('cancel')} variation={ButtonVariation.TERTIARY} onClick={onCancel} />
            </Layout.Horizontal>
          </Form>
        )
      }}
    </Formik>
  )
}
 
export default RoleAssignment