<commit_before>import { Button, Flex, Box, Text, Spacer, ModalDialog } from "@artsy/palette"
import { useState } from "react"
import * as React from "react"
import { RelayRefetchProp, graphql, createRefetchContainer } from "react-relay"
// eslint-disable-next-line no-restricted-imports
import request from "superagent"
import { useSystemContext } from "v2/System"
import { AppSecondFactorModal, OnCompleteRedirectModal } from "./Modal"
import { ApiError } from "../../ApiError"
import { ApiErrorModal } from "../ApiErrorModal"
import { CreateAppSecondFactor } from "./Mutation/CreateAppSecondFactor"
import { DisableFactorConfirmation } from "../DisableFactorConfirmation"
import { AppSecondFactor_me } from "v2/__generated__/AppSecondFactor_me.graphql"
import { ConfirmPasswordModal } from "v2/Components/ConfirmPasswordModal"
import { CreateAppSecondFactorInput } from "v2/__generated__/CreateAppSecondFactorMutation.graphql"

import { afterUpdateRedirect } from "v2/Apps/Settings/Routes/EditSettings/Components/SettingsEditSettingsTwoFactor/TwoFactorAuthentication/helpers"

interface AppSecondFactorProps {
  me: AppSecondFactor_me
  relay: RelayRefetchProp
}

export const AppSecondFactor: React.FC<AppSecondFactorProps> = ({
  me,
  relay,
}) => {
  const [apiErrors, setApiErrors] = useState<ApiError[]>([])
  const [showConfirmDisable, setShowConfirmDisable] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [showSetupModal, setShowSetupModal] = useState(false)
  const [showCompleteModal, setShowCompleteModal] = useState(false)
  const [showCompleteRedirectModal, setShowCompleteRedirectModal] = useState(
    false
  )
  const [stagedSecondFactor, setStagedSecondFactor] = useState(null)
  const [isDisabling] = useState(false)
  const [isCreating, setCreating] = useState(false)

  const { relayEnvironment } = useSystemContext()

  const redirectTo = afterUpdateRedirect()

  const enabledSecondFactorLabel =
    me.appSecondFactors?.length &&
    me.appSecondFactors[0]?.__typename === "AppSecondFactor"
      ? me.appSecondFactors[0].name
      : null

  const isEnabled = !!enabledSecondFactorLabel

  function onComplete() {
    const showCompleteModalCallback = () => {
      setShowSetupModal(false)
      setShowCompleteModal(true)
    }

    const showCompleteRedirectModalCallback = () => {
      setShowSetupModal(false)
      setShowCompleteRedirectModal(true)
    }

    if (me.hasSecondFactorEnabled) {
      relay.refetch({}, {}, showCompleteModalCallback)
    } else {
      if (redirectTo) {
        showCompleteRedirectModalCallback()
      } else {
        showCompleteModalCallback()
      }
    }
  }

  async function onCompleteConfirmed() {
    if (me.hasSecondFactorEnabled) {
      setShowCompleteModal(false)
    } else {
      await request
        .delete("/users/sign_out")
        .set("X-Requested-With", "XMLHttpRequest")

      location.reload()
    }
  }

  function onCompleteRedirect() {
    if (me.hasSecondFactorEnabled) {
      setShowCompleteModal(false)
    } else {
      window.location.assign(redirectTo)
    }
  }

  function handleMutationError(errors: ApiError[]) {
    if (!Array.isArray(errors)) {
      throw errors
    }

    setApiErrors(errors)
  }

  async function createSecondFactor(
    password: <PASSWORD>["password"]
  ) {
    setCreating(true)

    try {
      // @ts-expect-error PLEASE_FIX_ME_STRICT_NULL_CHECK_MIGRATION
      const response = await CreateAppSecondFactor(relayEnvironment, {
        attributes: {},
        password,
      })
      // @ts-expect-error PLEASE_FIX_ME_STRICT_NULL_CHECK_MIGRATION
      setStagedSecondFactor(response.createAppSecondFactor.secondFactorOrErrors)
      setShowConfirmPassword(false)
      setShowSetupModal(true)
    } catch (error) {
      handleMutationError(error)
    }

    setCreating(false)
  }

  function onDisableSecondFactor() {
    relay.refetch({}, {}, () => {
      setShowConfirmDisable(false)
    })
  }

  return (
    <>
      <Flex
        p={2}
        border="1px solid"
        borderColor="black10"
        flexDirection={["column", "row"]}
      >
        <Box flexBasis="50%">
          <Text variant="lg">App Authenticator</Text>

          {enabledSecondFactorLabel && (
            <Text variant="lg" color="black60">
              {enabledSecondFactorLabel}
            </Text>
          )}

          <Spacer mt={2} />

          <Text variant="sm" color="black60">
            Generate secure authentication codes using an application such as{" "}
            <a
              href="https://support.1password.com/one-time-passwords"
              target="_blank"
              rel="noopener noreferrer"
            >
              1Password
            </a>{" "}
            or{" "}
            <a
              href="https://authy.com/features"
              target="_blank"
              rel="noopener noreferrer"
            >
              Authy
            </a>
            .
          </Text>
        </Box>

        <Spacer ml={[0, 2]} mt={[2, 0]} />

        <Flex flexBasis="50%" alignItems="center" justifyContent="flex-end">
          {isEnabled ? (
            <>
              <Button
                variant="secondaryOutline"
                width={["100%", "auto"]}
                onClick={() => setShowConfirmDisable(true)}
                loading={isDisabling}
                disabled={isDisabling}
              >
                Disable
              </Button>

              <Spacer ml={1} />

              <Button
                width={["100%", "auto"]}<commit_msg>fix: remove Authy reference in favour of Google Authenticator (#9806)<commit_after>import { Button, Flex, Box, Text, Spacer, ModalDialog } from "@artsy/palette"
import { useState } from "react"
import * as React from "react"
import { RelayRefetchProp, graphql, createRefetchContainer } from "react-relay"
// eslint-disable-next-line no-restricted-imports
import request from "superagent"
import { useSystemContext } from "v2/System"
import { AppSecondFactorModal, OnCompleteRedirectModal } from "./Modal"
import { ApiError } from "../../ApiError"
import { ApiErrorModal } from "../ApiErrorModal"
import { CreateAppSecondFactor } from "./Mutation/CreateAppSecondFactor"
import { DisableFactorConfirmation } from "../DisableFactorConfirmation"
import { AppSecondFactor_me } from "v2/__generated__/AppSecondFactor_me.graphql"
import { ConfirmPasswordModal } from "v2/Components/ConfirmPasswordModal"
import { CreateAppSecondFactorInput } from "v2/__generated__/CreateAppSecondFactorMutation.graphql"

import { afterUpdateRedirect } from "v2/Apps/Settings/Routes/EditSettings/Components/SettingsEditSettingsTwoFactor/TwoFactorAuthentication/helpers"

interface AppSecondFactorProps {
  me: AppSecondFactor_me
  relay: RelayRefetchProp
}

export const AppSecondFactor: React.FC<AppSecondFactorProps> = ({
  me,
  relay,
}) => {
  const [apiErrors, setApiErrors] = useState<ApiError[]>([])
  const [showConfirmDisable, setShowConfirmDisable] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [showSetupModal, setShowSetupModal] = useState(false)
  const [showCompleteModal, setShowCompleteModal] = useState(false)
  const [showCompleteRedirectModal, setShowCompleteRedirectModal] = useState(
    false
  )
  const [stagedSecondFactor, setStagedSecondFactor] = useState(null)
  const [isDisabling] = useState(false)
  const [isCreating, setCreating] = useState(false)

  const { relayEnvironment } = useSystemContext()

  const redirectTo = afterUpdateRedirect()

  const enabledSecondFactorLabel =
    me.appSecondFactors?.length &&
    me.appSecondFactors[0]?.__typename === "AppSecondFactor"
      ? me.appSecondFactors[0].name
      : null

  const isEnabled = !!enabledSecondFactorLabel

  function onComplete() {
    const showCompleteModalCallback = () => {
      setShowSetupModal(false)
      setShowCompleteModal(true)
    }

    const showCompleteRedirectModalCallback = () => {
      setShowSetupModal(false)
      setShowCompleteRedirectModal(true)
    }

    if (me.hasSecondFactorEnabled) {
      relay.refetch({}, {}, showCompleteModalCallback)
    } else {
      if (redirectTo) {
        showCompleteRedirectModalCallback()
      } else {
        showCompleteModalCallback()
      }
    }
  }

  async function onCompleteConfirmed() {
    if (me.hasSecondFactorEnabled) {
      setShowCompleteModal(false)
    } else {
      await request
        .delete("/users/sign_out")
        .set("X-Requested-With", "XMLHttpRequest")

      location.reload()
    }
  }

  function onCompleteRedirect() {
    if (me.hasSecondFactorEnabled) {
      setShowCompleteModal(false)
    } else {
      window.location.assign(redirectTo)
    }
  }

  function handleMutationError(errors: ApiError[]) {
    if (!Array.isArray(errors)) {
      throw errors
    }

    setApiErrors(errors)
  }

  async function createSecondFactor(
    password: <PASSWORD>["password"]
  ) {
    setCreating(true)

    try {
      // @ts-expect-error PLEASE_FIX_ME_STRICT_NULL_CHECK_MIGRATION
      const response = await CreateAppSecondFactor(relayEnvironment, {
        attributes: {},
        password,
      })
      // @ts-expect-error PLEASE_FIX_ME_STRICT_NULL_CHECK_MIGRATION
      setStagedSecondFactor(response.createAppSecondFactor.secondFactorOrErrors)
      setShowConfirmPassword(false)
      setShowSetupModal(true)
    } catch (error) {
      handleMutationError(error)
    }

    setCreating(false)
  }

  function onDisableSecondFactor() {
    relay.refetch({}, {}, () => {
      setShowConfirmDisable(false)
    })
  }

  return (
    <>
      <Flex
        p={2}
        border="1px solid"
        borderColor="black10"
        flexDirection={["column", "row"]}
      >
        <Box flexBasis="50%">
          <Text variant="lg">App Authenticator</Text>

          {enabledSecondFactorLabel && (
            <Text variant="lg" color="black60">
              {enabledSecondFactorLabel}
            </Text>
          )}

          <Spacer mt={2} />

          <Text variant="sm" color="black60">
            Generate secure authentication codes using an application such as{" "}
            <a
              href="https://support.1password.com/one-time-passwords"
              target="_blank"
              rel="noopener noreferrer"
            >
              1Password
            </a>{" "}
            or{" "}
            <a
              href="https://support.google.com/accounts/answer/1066447"
              target="_blank"
              rel="noopener noreferrer"
            >
              Google Authenticator
            </a>
            .
          </Text>
        </Box>

        <Spacer ml={[0, 2]} mt={[2, 0]} />

        <Flex flexBasis="50%" alignItems="center" justifyContent="flex-end">
          {isEnabled ? (
            <>
              <Button
                variant="secondaryOutline"
                width={["100%", "auto"]}
                onClick={() => setShowConfirmDisable(true)}
                loading={isDisabling}
                disabled={isDisabling}
              >
                Disable
              </Button>

              <Spacer ml={1} />

              <Button
                width={["100%", "auto"]}
{'fraction_non_alphanumeric': 0.11233265360404292, 'fraction_numerical': 0.006826846351626917, 'mean_word_length': 2.7080867850098618, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 61, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5942309', 'n_tokens_mistral': 3264, 'n_tokens_neox': 3184, 'n_words': 581}