import { r as reactExports, j as jsxRuntimeExports } from "./vendor-react-DYNCg6N5.js";
import { u as useStyles } from "./styles-CGXtrnyw.js";
import { g as getValidateErrors } from "./validation-Ds00Zghx.js";
import { C as CommonSectionTemplate } from "./index-BRmgVx8q.js";
import { ah as _pe, ai as Efe } from "./vendor-icons-xWhXK_Ui.js";
import { aU as axiosInstance, m as universalNotification } from "./index-DfebxkL9.js";
import { u as useTranslation } from "./vendor-i18n-wisIXUFi.js";
import { W as useMediaQuery, z as useForm, b as Box, a0 as SimpleGrid, E as TextInput, T as Text, aG as FileButton, B as Button, F as Flex, k as Tooltip, J as PasswordInput, a4 as Select, d as Checkbox } from "./vendor-mantine-h0WlM2Mj.js";
import { o as objectType, s as stringType, Z as ZodIssueCode } from "./types-espwwxTQ.js";
class SsoSettingsService {
  async GetSsoSettings() {
    const {
      data
    } = await axiosInstance.get("v1/SsoSettings");
    return data;
  }
  async SaveSsoSettings(params) {
    const {
      data
    } = await axiosInstance.post("v1/SsoSettings", params);
    return data;
  }
  async UploadCertificate(params) {
    const formData = new FormData();
    formData.append("File", params.File);
    if (params.Password) {
      formData.append("Password", params.Password);
    }
    const {
      data
    } = await axiosInstance.post("v1/SsoSettings/Upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    });
    return data;
  }
}
const ssoSettingsApiArea = () => new SsoSettingsService();
const SsoSettingsPage = () => {
  const {
    classes
  } = useStyles();
  const {
    t
  } = useTranslation();
  const isMobile = useMediaQuery("(max-width: 576px)");
  const [isLoading, setIsLoading] = reactExports.useState(false);
  const [certificate, setCertificate] = reactExports.useState(null);
  const getValidationScheme = () => objectType({
    IdPMetadata: stringType().transform((val) => val.trim()).pipe(stringType().min(1, {
      message: t("validation.emptyInput")
    }).max(2e3, {
      message: t("validation.maxLength", {
        max: 2e3
      })
    }).url({
      message: t("validation.invalidUrl")
    }).refine((val_0) => {
      return !/\s/.test(val_0);
    }, {
      message: t("validation.invalidUrl")
    }).refine((val_1) => {
      const multipleSchemes = /(https?:\/\/.*?)(https?:\/\/)/i;
      return !multipleSchemes.test(val_1);
    }, {
      message: t("validation.invalidUrl")
    })),
    Issuer: stringType().transform((val_2) => val_2.trim()).pipe(stringType().min(1, {
      message: t("validation.emptyInput")
    }).max(2e3, {
      message: t("validation.maxLength", {
        max: 2e3
      })
    }).url({
      message: t("validation.invalidUrl")
    }).refine((val_3) => {
      return !/\s/.test(val_3);
    }, {
      message: t("validation.invalidUrl")
    }).refine((val_4) => {
      const multipleSchemes_0 = /(https?:\/\/.*?)(https?:\/\/)/i;
      return !multipleSchemes_0.test(val_4);
    }, {
      message: t("validation.invalidUrl")
    })),
    SignatureAlgorithm: stringType().trim().min(1, {
      message: t("validation.emptyInput")
    }).max(500, {
      message: t("validation.maxLength", {
        max: 500
      })
    }).refine((val_5) => {
      try {
        new URL(val_5);
        return true;
      } catch {
        return val_5.startsWith("urn:");
      }
    }, {
      message: t("validation.invalidUrlOrUrn")
    }),
    SigningCertificatePassword: stringType().refine((val_6) => {
      if (certificate) {
        return val_6.trim().length > 0;
      }
      return true;
    }, {
      message: t("validation.certificatePasswordRequired")
    }),
    CertificateValidationMode: stringType().nullable().transform((val_7) => val_7 || "None"),
    RevocationMode: stringType().nullable().transform((val_8) => val_8 || "NoCheck"),
    AuthnContextClassRef: stringType().trim().min(1, {
      message: t("validation.emptyInput")
    }).max(500, {
      message: t("validation.maxLength", {
        max: 500
      })
    }).refine((val_9) => {
      try {
        new URL(val_9);
        return true;
      } catch {
        return val_9.startsWith("urn:");
      }
    }, {
      message: t("validation.invalidUrlOrUrn")
    })
  }).superRefine((data, ctx) => {
    var _a, _b, _c, _d;
    const fields = {
      IdPMetadata: (_a = data.IdPMetadata) == null ? void 0 : _a.trim(),
      Issuer: (_b = data.Issuer) == null ? void 0 : _b.trim(),
      SignatureAlgorithm: (_c = data.SignatureAlgorithm) == null ? void 0 : _c.trim(),
      AuthnContextClassRef: (_d = data.AuthnContextClassRef) == null ? void 0 : _d.trim()
    };
    const valueToFields = /* @__PURE__ */ new Map();
    Object.entries(fields).forEach(([fieldName, value]) => {
      if (value && value.length > 0) {
        if (!valueToFields.has(value)) {
          valueToFields.set(value, []);
        }
        const fieldsList = valueToFields.get(value);
        if (fieldsList) {
          fieldsList.push(fieldName);
        }
      }
    });
    valueToFields.forEach((fieldNames) => {
      if (fieldNames.length > 1) {
        fieldNames.forEach((fieldName_0) => {
          ctx.addIssue({
            code: ZodIssueCode.custom,
            message: t("validation.duplicateValues"),
            path: [fieldName_0]
          });
        });
      }
    });
  });
  const form = useForm({
    initialValues: {
      IdPMetadata: "",
      Issuer: "",
      SignatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
      SigningCertificateFile: "",
      SigningCertificatePassword: "",
      CertificateValidationMode: "None",
      RevocationMode: "NoCheck",
      IsSignAuthnRequest: false,
      AuthnContextClassRef: "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
      CreateUser: false
    },
    validateInputOnChange: true,
    validate: (values) => getValidateErrors(getValidationScheme(), values)
  });
  const errors = form.errors;
  const isDirtyForm = form.isDirty();
  const isDisabled = Object.keys(errors || {}).length !== 0 || !isDirtyForm && !certificate;
  reactExports.useEffect(() => {
    void loadSettings();
  }, []);
  reactExports.useEffect(() => {
    if (form.values.SigningCertificatePassword !== void 0) {
      form.validateField("SigningCertificatePassword");
    }
  }, [certificate]);
  const loadSettings = async () => {
    try {
      setIsLoading(true);
      const service = ssoSettingsApiArea();
      const data_0 = await service.GetSsoSettings();
      const formData = {
        IdPMetadata: data_0.IdPMetadata || "",
        Issuer: data_0.Issuer || "",
        SignatureAlgorithm: data_0.SignatureAlgorithm || "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
        SigningCertificateFile: data_0.SigningCertificateFile || "",
        SigningCertificatePassword: data_0.SigningCertificatePassword || "",
        CertificateValidationMode: data_0.CertificateValidationMode || "None",
        RevocationMode: data_0.RevocationMode || "NoCheck",
        IsSignAuthnRequest: data_0.IsSignAuthnRequest || false,
        AuthnContextClassRef: data_0.AuthnContextClassRef || "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
        CreateUser: data_0.CreateUser || false
      };
      form.setValues(formData);
      form.resetDirty(formData);
    } catch (error) {
      universalNotification({
        isError: true,
        error,
        isSuccess: false,
        errorTitle: t("sso.loadError")
      });
    } finally {
      setIsLoading(false);
    }
  };
  const handleSubmit = async (values_0) => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    try {
      setIsLoading(true);
      const service_0 = ssoSettingsApiArea();
      const trimmedValues = {
        ...values_0,
        IdPMetadata: (_a = values_0.IdPMetadata) == null ? void 0 : _a.trim(),
        Issuer: (_b = values_0.Issuer) == null ? void 0 : _b.trim(),
        SignatureAlgorithm: (_c = values_0.SignatureAlgorithm) == null ? void 0 : _c.trim(),
        AuthnContextClassRef: (_d = values_0.AuthnContextClassRef) == null ? void 0 : _d.trim(),
        SigningCertificatePassword: (_e = values_0.SigningCertificatePassword) == null ? void 0 : _e.trim()
      };
      let newCertificateName;
      if (certificate) {
        const uploadResult = await service_0.UploadCertificate({
          File: certificate,
          Password: trimmedValues.SigningCertificatePassword
        });
        if (uploadResult) {
          newCertificateName = certificate.name;
          trimmedValues.SigningCertificateFile = certificate.name;
        }
      } else {
        if (!((_f = trimmedValues.SigningCertificatePassword) == null ? void 0 : _f.trim())) {
          delete trimmedValues.SigningCertificatePassword;
        }
      }
      await service_0.SaveSsoSettings(trimmedValues);
      universalNotification({
        isError: false,
        error: null,
        isSuccess: true,
        successTitle: t("saved")
      });
      if (newCertificateName) {
        form.setFieldValue("SigningCertificateFile", newCertificateName);
      }
      form.resetDirty();
      setCertificate(null);
    } catch (error_0) {
      const errorMessage = ((_h = (_g = error_0 == null ? void 0 : error_0.response) == null ? void 0 : _g.data) == null ? void 0 : _h.Message) || (error_0 == null ? void 0 : error_0.message);
      if (errorMessage) {
        const fieldMapping = {
          IdPMetadata: "IdPMetadata",
          Issuer: "Issuer",
          SignatureAlgorithm: "SignatureAlgorithm",
          AuthnContextClassRef: "AuthnContextClassRef",
          SigningCertificatePassword: "SigningCertificatePassword"
        };
        let fieldErrorSet = false;
        for (const [fieldKey, fieldName_1] of Object.entries(fieldMapping)) {
          if (errorMessage.includes(fieldKey)) {
            form.setFieldError(fieldName_1, errorMessage);
            fieldErrorSet = true;
            break;
          }
        }
        if (!fieldErrorSet) {
          universalNotification({
            isError: true,
            error: error_0,
            isSuccess: false,
            errorTitle: t("sso.saveError"),
            errorMessage
          });
        }
      } else {
        universalNotification({
          isError: true,
          error: error_0,
          isSuccess: false,
          errorTitle: t("sso.saveError")
        });
      }
    } finally {
      setIsLoading(false);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(CommonSectionTemplate, { title: t("sso.authMethod"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { sx: {
    width: "100%"
  }, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { onSubmit: form.onSubmit(handleSubmit), children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: isMobile ? 1 : 2, w: "100%", className: classes.clientContainer, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(TextInput, { className: classes.textFieldInput, label: t("sso.metadataIdP"), withAsterisk: true, placeholder: "https://blitz.devr7.ru/blitz/saml/profile/Metadata", ...form.getInputProps("IdPMetadata") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TextInput, { className: classes.textFieldInput, label: t("sso.issuer"), withAsterisk: true, placeholder: "https://cddisk.devr7.ru/saml2/Metadata", ...form.getInputProps("Issuer") })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleGrid, { cols: 1, w: "100%", className: classes.clientContainer, children: /* @__PURE__ */ jsxRuntimeExports.jsx(TextInput, { className: classes.textFieldInput, label: t("sso.signatureAlgorithm"), withAsterisk: true, placeholder: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", ...form.getInputProps("SignatureAlgorithm") }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleGrid, { cols: 1, w: "100%", className: classes.clientContainer, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Text, { size: "sm", fw: 500, mb: 4, children: [
        t("sso.certificateFile"),
        " ",
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style: {
          color: "red"
        }, children: "*" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(FileButton, { onChange: setCertificate, accept: ".pfx,.p12", children: (props) => /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { ...props, variant: "outline", leftSection: /* @__PURE__ */ jsxRuntimeExports.jsx(_pe, { size: 16 }), size: "sm", children: t("sso.attachFile") }) }),
      certificate ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Text, { size: "xs", c: "blue", mt: 4, children: [
        t("sso.selectedFile"),
        ": ",
        certificate.name
      ] }) : form.values.SigningCertificateFile ? /* @__PURE__ */ jsxRuntimeExports.jsxs(Text, { size: "xs", c: "dimmed", mt: 4, children: [
        t("sso.currentFile"),
        ": ",
        form.values.SigningCertificateFile
      ] }) : null
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: isMobile ? 1 : 2, w: "100%", className: classes.clientContainer, style: {
      alignItems: "flex-start"
    }, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Flex, { align: "center", gap: 4, mb: "10px", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Text, { size: "sm", fw: 500, children: t("sso.certificatePassword") }),
          certificate && /* @__PURE__ */ jsxRuntimeExports.jsx(Text, { size: "sm", c: "red", fw: 500, children: "*" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { label: t("sso.certificatePasswordTooltip"), multiline: true, w: 300, withArrow: true, position: "top", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { style: {
            display: "flex",
            alignItems: "center",
            cursor: "help"
          }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Efe, { size: 14, style: {
            opacity: 0.6
          } }) }) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(PasswordInput, { className: classes.textFieldInput, styles: {
          label: {
            display: "none"
          }
        }, ...form.getInputProps("SigningCertificatePassword") }),
        certificate && /* @__PURE__ */ jsxRuntimeExports.jsx(Text, { size: "xs", c: "orange", mt: 4, children: t("sso.certificatePasswordRequiredForNewCert") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Select, { className: classes.textFieldInput, label: t("sso.certificateValidationMode"), withAsterisk: true, data: [{
        value: "None",
        label: t("sso.validationModeNone")
      }, {
        value: "PeerTrust",
        label: t("sso.validationModePeerTrust")
      }, {
        value: "ChainTrust",
        label: t("sso.validationModeChainTrust")
      }, {
        value: "PeerOrChainTrust",
        label: t("sso.validationModePeerOrChainTrust")
      }, {
        value: "Custom",
        label: t("sso.validationModeCustom")
      }], ...form.getInputProps("CertificateValidationMode") })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(SimpleGrid, { cols: isMobile ? 1 : 2, w: "100%", className: classes.clientContainer, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Select, { className: classes.textFieldInput, label: t("sso.revocationMode"), withAsterisk: true, data: [{
        value: "NoCheck",
        label: t("sso.revocationModeNoCheck")
      }, {
        value: "Online",
        label: t("sso.revocationModeOnline")
      }, {
        value: "Offline",
        label: t("sso.revocationModeOffline")
      }], ...form.getInputProps("RevocationMode") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(TextInput, { className: classes.textFieldInput, label: t("sso.authnContext"), withAsterisk: true, ...form.getInputProps("AuthnContextClassRef") })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Flex, { direction: "column", gap: "sm", mt: "md", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Checkbox, { label: t("sso.createUserOnFirstLogin"), ...form.getInputProps("CreateUser", {
        type: "checkbox"
      }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Checkbox, { label: t("sso.signAuthnRequest"), ...form.getInputProps("IsSignAuthnRequest", {
        type: "checkbox"
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Flex, { className: classes.sectionControls, w: "100%", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { disabled: isDisabled || isLoading, className: classes.submitButton, size: "sm", radius: 8, type: "submit", mt: "md", loading: isLoading, children: t("save") }) })
  ] }) }) });
};
export {
  SsoSettingsPage as default
};
//# sourceMappingURL=index-CtVsydR1.js.map
