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.

5.9 KB
Raw Blame
'use client'
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import {
  PasswordField,
  PasswordFieldInput,
  PasswordFieldToggle,
} from '@langgenius/dify-ui/password-field'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
  navigateAfterWebAppLogin,
  resolveWebAppLoginRedirect,
} from '@/app/(shareLayout)/webapp-signin/login-redirect'
import { toast } from '@/app/notifications'
import { emailRegex } from '@/config'
import { useWebAppStore } from '@/context/web-app-context'
import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { webAppLogin } from '@/service/common'
import { fetchAccessToken } from '@/service/share'
import { setWebAppAccessToken, setWebAppPassport } from '@/service/webapp-auth'
import { encryptPassword } from '@/utils/encryption'
import { getClientLoginFallback } from '@/utils/login-redirect'
import { replaceLoginRedirect } from '@/utils/login-redirect.client'
import { basePath } from '@/utils/var'

type MailAndPasswordAuthProps = {
  isEmailSetup: boolean
}

export default function MailAndPasswordAuth({ isEmailSetup }: MailAndPasswordAuthProps) {
  const { t } = useTranslation(['login'])
  const router = useRouter()
  const searchParams = useSearchParams()
  const emailFromLink = decodeURIComponent(searchParams.get('email') || '')
  const [isLoading, setIsLoading] = useState(false)
  const redirectUrl = searchParams.get('redirect_url')
  const embeddedUserId = useWebAppStore((s) => s.embeddedUserId)

  useEffect(() => {
    if (!resolveWebAppLoginRedirect(redirectUrl, window.location.origin))
      replaceLoginRedirect(getClientLoginFallback(), router.replace, basePath)
  }, [redirectUrl, router])

  const handleEmailPasswordLogin = async (email: string, password: string) => {
    if (isLoading) return
    const loginRedirect = resolveWebAppLoginRedirect(redirectUrl, window.location.origin)
    if (!loginRedirect) {
      replaceLoginRedirect(getClientLoginFallback(), router.replace, basePath)
      return
    }
    try {
      setIsLoading(true)
      const loginData = {
        email,
        password: encryptPassword(password),
        remember_me: true,
      }

      const res = await webAppLogin({
        url: '/login',
        body: loginData,
      })
      if (res.result === 'success') {
        if (res?.data?.access_token) {
          setWebAppAccessToken(res.data.access_token)
        }

        const { access_token } = await fetchAccessToken({
          appCode: loginRedirect.appCode,
          userId: embeddedUserId || undefined,
        })
        setWebAppPassport(loginRedirect.address, access_token)
        navigateAfterWebAppLogin(loginRedirect, router.replace, basePath)
      } else {
        toast.error(res.data)
      }
    } catch (error: unknown) {
      const authenticationError = error as { code?: unknown; message?: unknown }
      if (
        authenticationError.code === 'authentication_failed' &&
        typeof authenticationError.message === 'string'
      )
        toast.error(authenticationError.message)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Form<{ email: string; password: string }>
      onFormSubmit={({ email, password }) => {
        void handleEmailPasswordLogin(email, password)
      }}
    >
      <Field
        name="email"
        className="mb-3 block"
        validate={(value) => {
          if (typeof value !== 'string' || !value)
            return t(($) => $['error.emailEmpty'], { ns: 'login' })
          if (!emailRegex.test(value)) return t(($) => $['error.emailInValid'], { ns: 'login' })
          return null
        }}
      >
        <FieldLabel className="my-2 py-0 text-sm leading-5 font-semibold text-text-secondary">
          {t(($) => $.email, { ns: 'login' })}
        </FieldLabel>
        <div className="mt-1">
          <Input
            defaultValue={emailFromLink}
            id="email"
            type="text"
            inputMode="email"
            autoComplete="email"
            spellCheck={false}
            placeholder={t(($) => $.emailPlaceholder, { ns: 'login' })}
          />
        </div>
        <FieldError />
      </Field>

      <Field
        name="password"
        className="mb-3 block"
        validate={(value) => {
          if (typeof value !== 'string' || !value.trim())
            return t(($) => $['error.passwordEmpty'], { ns: 'login' })
          return null
        }}
      >
        <div className="my-2 flex items-center justify-between">
          <FieldLabel className="py-0 text-sm leading-5 font-semibold text-text-secondary">
            {t(($) => $.password, { ns: 'login' })}
          </FieldLabel>
          {isEmailSetup ? (
            <Link
              href={`/webapp-reset-password?${searchParams.toString()}`}
              className="system-xs-regular text-text-accent hover:underline"
            >
              {t(($) => $.forget, { ns: 'login' })}
            </Link>
          ) : (
            <span className="system-xs-regular text-components-button-secondary-accent-text-disabled">
              {t(($) => $.forget, { ns: 'login' })}
            </span>
          )}
        </div>
        <PasswordField className="mt-1">
          <PasswordFieldInput
            id="password"
            autoComplete="current-password"
            placeholder={t(($) => $.passwordPlaceholder, { ns: 'login' })}
          />
          <PasswordFieldToggle aria-label={t(($) => $.showPassword, { ns: 'login' })} />
        </PasswordField>
        <FieldError />
      </Field>

      <div className="mb-2">
        <Button type="submit" variant="primary" loading={isLoading} className="w-full">
          {t(($) => $.signBtn, { ns: 'login' })}
        </Button>
      </div>
    </Form>
  )
}