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.

7.7 KB
Raw Blame
'use client'
import type { PropsWithChildren } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
  isWebAppSigninPath,
  navigateAfterWebAppLogin,
  resolveWebAppLoginRedirect,
} from '@/app/(shareLayout)/webapp-signin/login-redirect'
import AppUnavailable from '@/app/components/base/app-unavailable'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { useWebAppStore } from '@/context/web-app-context'
import {
  captureAppAccessScope,
  hasAppAccessError,
  isAppAccessError,
  isAppAccessScopeCurrent,
} from '@/features/app-access-error/state'
import { AccessMode } from '@/models/access-control'
import { usePathname, useRouter, useSearchParams } from '@/next/navigation'
import { getHttpErrorStatus } from '@/service/http-error'
import { fetchAccessToken } from '@/service/share'
import { resolveWebAppAddress } from '@/service/webapp-address'
import {
  setWebAppAccessToken,
  setWebAppPassport,
  webAppLoginStatus,
  webAppLogout,
} from '@/service/webapp-auth'
import { getClientLoginFallback } from '@/utils/login-redirect'
import { replaceLoginRedirect } from '@/utils/login-redirect.client'
import { basePath } from '@/utils/var'

function Splash({ children }: PropsWithChildren) {
  const { t } = useTranslation(['common', 'share'])
  const shareCode = useWebAppStore((s) => s.shareCode)
  const webAppAccessMode = useWebAppStore((s) => s.webAppAccessMode)
  const embeddedUserId = useWebAppStore((s) => s.embeddedUserId)
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()
  const redirectUrl = searchParams.get('redirect_url')
  const message = searchParams.get('message')
  const code = searchParams.get('code')
  const tokenFromUrl = searchParams.get('web_sso_token')
  const getSigninUrl = useCallback(() => {
    const params = new URLSearchParams(searchParams)
    params.delete('message')
    params.delete('code')
    const loginRedirect = resolveWebAppLoginRedirect(redirectUrl, window.location.origin)
    if (loginRedirect) params.set('redirect_url', loginRedirect.target.href)
    else params.delete('redirect_url')
    return `/webapp-signin?${params.toString()}`
  }, [redirectUrl, searchParams])

  const backToHome = useCallback(async () => {
    const loginRedirect = resolveWebAppLoginRedirect(redirectUrl, window.location.origin)
    const address = loginRedirect?.address || resolveWebAppAddress()
    if (!address || (isWebAppSigninPath(pathname) && !loginRedirect)) {
      replaceLoginRedirect(getClientLoginFallback(), router.replace, basePath)
      return
    }

    await webAppLogout(address)
    const url = getSigninUrl()
    router.replace(url)
  }, [getSigninUrl, pathname, redirectUrl, router])

  const [isLoading, setIsLoading] = useState(true)
  const [initializationError, setInitializationError] = useState<{
    shareCode: string
    status?: number
  }>()
  useEffect(() => {
    const scope = captureAppAccessScope()
    let cancelled = false
    const canContinue = () =>
      !cancelled && (scope === null || isAppAccessScopeCurrent(scope)) && !hasAppAccessError(scope)
    if (!canContinue()) return

    const loginRedirect = resolveWebAppLoginRedirect(redirectUrl, window.location.origin)
    const isSigninRoute = isWebAppSigninPath(pathname)
    if ((redirectUrl !== null && !loginRedirect) || (isSigninRoute && !loginRedirect)) {
      replaceLoginRedirect(getClientLoginFallback(), router.replace, basePath)
      return
    }

    const address = loginRedirect?.address || resolveWebAppAddress()
    if (!address) return
    const effectiveShareCode = address.code

    if (message) return

    if (tokenFromUrl) setWebAppAccessToken(tokenFromUrl)

    const redirectOrFinish = () => {
      if (!canContinue()) return
      if (loginRedirect) navigateAfterWebAppLogin(loginRedirect, router.replace, basePath)
      else setIsLoading(false)
    }

    const proceedToAuth = (authenticationRequired: boolean) => {
      if (!canContinue()) return
      if (
        authenticationRequired &&
        address.kind === 'environment' &&
        webAppAccessMode !== AccessMode.PUBLIC &&
        !isSigninRoute
      ) {
        const redirectSearchParams = new URLSearchParams(searchParams)
        redirectSearchParams.delete('web_sso_token')
        const redirectSearch = redirectSearchParams.toString()
        const redirectTarget = redirectSearch ? `${pathname}?${redirectSearch}` : pathname
        const signinSearchParams = new URLSearchParams({ redirect_url: redirectTarget })
        router.replace(`/webapp-signin?${signinSearchParams.toString()}`)
        return
      }
      setIsLoading(false)
    }

    const initialize = async () => {
      try {
        // Public apps still need a valid app passport even when user login is not required.
        const { userLoggedIn, appLoggedIn } = await webAppLoginStatus(
          effectiveShareCode,
          embeddedUserId || undefined,
        )
        if (!canContinue()) return

        if (appLoggedIn) {
          redirectOrFinish()
        } else if (!userLoggedIn) {
          proceedToAuth(true)
        } else {
          try {
            const { access_token } = await fetchAccessToken({
              appCode: effectiveShareCode,
              userId: embeddedUserId || undefined,
            })
            if (!canContinue()) return

            setWebAppPassport(address, access_token)
            redirectOrFinish()
          } catch (error) {
            if (!canContinue() || isAppAccessError(error)) return

            if ((getHttpErrorStatus(error) ?? 0) >= 500) {
              setInitializationError({
                shareCode: effectiveShareCode,
                status: getHttpErrorStatus(error),
              })
              return
            }
            if (getHttpErrorStatus(error) === 404) {
              setInitializationError({ shareCode: effectiveShareCode, status: 404 })
              return
            }
            await webAppLogout(address)
            proceedToAuth(getHttpErrorStatus(error) === 401)
          }
        }
      } catch (error) {
        if (!canContinue() || isAppAccessError(error)) return

        setInitializationError({
          shareCode: effectiveShareCode,
          status: getHttpErrorStatus(error),
        })
      }
    }

    void initialize()
    return () => {
      cancelled = true
    }
  }, [
    shareCode,
    redirectUrl,
    pathname,
    router,
    message,
    webAppAccessMode,
    tokenFromUrl,
    embeddedUserId,
    searchParams,
  ])

  if (message) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-y-4">
        <AppUnavailable
          className="size-auto"
          code={code || t(($) => $['common.appUnavailable'], { ns: 'share' })}
          unknownReason={message}
        />
        <button
          type="button"
          className="cursor-pointer system-sm-regular text-text-tertiary"
          onClick={backToHome}
        >
          {code === '403'
            ? t(($) => $['userProfile.logout'], { ns: 'common' })
            : t(($) => $['login.backToHome'], { ns: 'share' })}
        </button>
      </div>
    )
  }

  if (initializationError?.shareCode === shareCode) {
    return (
      <div className="flex h-full items-center justify-center">
        <AppUnavailable
          code={initializationError.status ?? t(($) => $['common.appUnavailable'], { ns: 'share' })}
          isUnknownReason={initializationError.status !== 404}
        />
      </div>
    )
  }

  if (!shareCode && redirectUrl === null && !isWebAppSigninPath(pathname)) return <>{children}</>

  if (isLoading) {
    return (
      <div className="flex h-full items-center justify-center">
        <LoadingPlaceholder />
      </div>
    )
  }
  return <>{children}</>
}

export default Splash