Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

6.5 KB
Raw Blame
'use client'

import type { AccountPasswordPayload } from '@dify/contracts/api/console/account/types.gen'
import type { DialogActions } from '@langgenius/dify-ui/dialog'
import { Button } from '@langgenius/dify-ui/button'
import {
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import {
  PasswordField,
  PasswordFieldInput,
  PasswordFieldToggle,
} from '@langgenius/dify-ui/password-field'
import { ORPCError } from '@orpc/client'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { validPassword } from '@/config'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { consoleQuery } from '@/service/console'

type ChangePasswordFormValues = {
  'current-password'?: string
  'new-password': string
  'confirm-password': string
}

type ChangePasswordFieldProps = {
  name: keyof ChangePasswordFormValues
  label: string
  autoComplete: 'current-password' | 'new-password'
  readOnly: boolean
}

function ChangePasswordField({ name, label, autoComplete, readOnly }: ChangePasswordFieldProps) {
  const { t } = useTranslation(['login'])

  return (
    <Field name={name}>
      <FieldLabel className="system-sm-semibold">{label}</FieldLabel>
      <PasswordField>
        <PasswordFieldInput autoComplete={autoComplete} readOnly={readOnly} />
        <PasswordFieldToggle aria-label={t(($) => $.showPassword, { ns: 'login' })} />
      </PasswordField>
    </Field>
  )
}

type ChangePasswordFormProps = {
  isPasswordSet: boolean
  isPending: boolean
  onSave: (password: AccountPasswordPayload) => Promise<void>
}

function ChangePasswordForm({
  isPasswordSet: initialIsPasswordSet,
  isPending,
  onSave,
}: ChangePasswordFormProps) {
  const { t } = useTranslation(['common', 'login', 'accountSettings'])
  // A successful first save refreshes the profile while the popup is still exiting.
  // Keep the mode this session opened with instead of switching to the reset form.
  const [isPasswordSet] = useState(initialIsPasswordSet)

  const handleSubmit = (values: ChangePasswordFormValues) => {
    if (isPending) return
    const password = values['new-password']
    const confirmPassword = values['confirm-password']
    if (!password.trim()) {
      toast.error(t(($) => $['error.passwordEmpty'], { ns: 'login' }))
      return
    }
    if (!validPassword.test(password)) {
      toast.error(t(($) => $['error.passwordInvalid'], { ns: 'login' }))
      return
    }
    if (password !== confirmPassword) {
      toast.error(t(($) => $['account.notEqual'], { ns: 'accountSettings' }))
      return
    }
    void onSave({
      password: values['current-password'] ?? '',
      new_password: password,
      repeat_new_password: confirmPassword,
    })
  }

  return (
    <Form<ChangePasswordFormValues> className="contents" onFormSubmit={handleSubmit}>
      <DialogHeader>
        <DialogTitle>
          {isPasswordSet
            ? t(($) => $['account.resetPassword'], { ns: 'accountSettings' })
            : t(($) => $['account.setPassword'], { ns: 'accountSettings' })}
        </DialogTitle>
      </DialogHeader>
      <DialogBody className="space-y-8">
        {isPasswordSet && (
          <ChangePasswordField
            name="current-password"
            label={t(($) => $['account.currentPassword'], { ns: 'accountSettings' })}
            autoComplete="current-password"
            readOnly={isPending}
          />
        )}
        <ChangePasswordField
          name="new-password"
          label={
            isPasswordSet
              ? t(($) => $['account.newPassword'], { ns: 'accountSettings' })
              : t(($) => $['account.password'], { ns: 'accountSettings' })
          }
          autoComplete="new-password"
          readOnly={isPending}
        />
        <ChangePasswordField
          name="confirm-password"
          label={t(($) => $['account.confirmPassword'], { ns: 'accountSettings' })}
          autoComplete="new-password"
          readOnly={isPending}
        />
      </DialogBody>
      <DialogFooter>
        <DialogClose render={<Button disabled={isPending} />}>
          {t(($) => $['operation.cancel'], { ns: 'common' })}
        </DialogClose>
        <Button type="submit" loading={isPending} variant="primary">
          {isPasswordSet
            ? t(($) => $['operation.reset'], { ns: 'common' })
            : t(($) => $['operation.save'], { ns: 'common' })}
        </Button>
      </DialogFooter>
    </Form>
  )
}

export function ChangePasswordDialog({ isPasswordSet }: { isPasswordSet: boolean }) {
  const { t } = useTranslation(['common', 'accountSettings'])
  const actionsRef = useRef<DialogActions>(null)
  const queryClient = useQueryClient()
  const updatePassword = useMutation(
    consoleQuery.account.password.post.mutationOptions({
      onSuccess: () => {
        // The request alone decides success; a slow profile refresh must not keep the dialog locked.
        void queryClient.invalidateQueries({ queryKey: userProfileQueryOptions().queryKey })
      },
    }),
  )

  const handleSave = async (password: AccountPasswordPayload) => {
    try {
      await updatePassword.mutateAsync({ body: password })
      toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
      actionsRef.current?.close()
    } catch (error) {
      // HTTP error notifications are owned by the request layer.
      // Only report a failure that never produced a response.
      if (!(error instanceof ORPCError) && error instanceof Error && error.message)
        toast.error(error.message)
    }
  }

  return (
    <Dialog
      actionsRef={actionsRef}
      onOpenChange={(open, details) => {
        if (!open && updatePassword.isPending && details.reason !== 'imperative-action')
          details.cancel()
      }}
    >
      <DialogTrigger render={<Button />}>
        {isPasswordSet
          ? t(($) => $['account.resetPassword'], { ns: 'accountSettings' })
          : t(($) => $['account.setPassword'], { ns: 'accountSettings' })}
      </DialogTrigger>
      <DialogContent className="w-105">
        <ChangePasswordForm
          isPasswordSet={isPasswordSet}
          isPending={updatePassword.isPending}
          onSave={handleSave}
        />
      </DialogContent>
    </Dialog>
  )
}