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.

10.5 KB
Raw Blame
'use client'

import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
  RiAccountCircleLine,
  RiGlobalLine,
  RiInfoCardLine,
  RiMailLine,
  RiTranslate2,
} from '@remixicon/react'
import { skipToken, useMutation, useQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { toast } from '@/app/notifications'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import useDocumentTitle from '@/hooks/use-document-title'
import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { isUnauthorizedError } from '@/service/http-error'
import { useLogout } from '@/service/use-common'
import { getAvatarInitial } from '@/utils/avatar'
import { buildOAuthCallbackUrl, buildReturnUrl, useSilentAuthorize } from './use-silent-authorize'

export default function OAuthAuthorize() {
  const { t } = useTranslation(['common', 'oauth'])

  const SCOPE_INFO_MAP: Record<
    string,
    { icon: React.ComponentType<{ className?: string }>; label: string }
  > = {
    'read:name': {
      icon: RiInfoCardLine,
      label: t(($) => $['scopes.name'], { ns: 'oauth' }),
    },
    'read:email': {
      icon: RiMailLine,
      label: t(($) => $['scopes.email'], { ns: 'oauth' }),
    },
    'read:avatar': {
      icon: RiAccountCircleLine,
      label: t(($) => $['scopes.avatar'], { ns: 'oauth' }),
    },
    'read:interface_language': {
      icon: RiTranslate2,
      label: t(($) => $['scopes.languagePreference'], { ns: 'oauth' }),
    },
    'read:timezone': {
      icon: RiGlobalLine,
      label: t(($) => $['scopes.timezone'], { ns: 'oauth' }),
    },
  }

  const router = useRouter()
  const language = useLanguage()
  const searchParams = useSearchParams()
  const clientId = searchParams.get('client_id') || ''
  const redirectUri = searchParams.get('redirect_uri') || ''
  const state = searchParams.get('state')
  const hasOAuthParams = Boolean(clientId && redirectUri)
  // Probe user profile. 401 stays as `error` (legitimate "not logged in" state),
  // other errors throw to the nearest error.tsx; jumpTo same-pathname guard in
  // service/base.ts prevents a redirect loop here.
  const {
    data: userProfileResp,
    isPending: isProfileLoading,
    error: profileError,
  } = useQuery({
    ...userProfileQueryOptions(),
    throwOnError: (err) => !isUnauthorizedError(err),
  })
  const isLoggedIn = !!userProfileResp && !profileError
  const userProfile = userProfileResp?.profile
  const {
    data: authAppInfo,
    isLoading: isOAuthLoading,
    isFetching: isOAuthFetching,
    isError: isOAuthError,
    refetch: refetchOAuthApp,
  } = useQuery(
    consoleQuery.oauth.provider.post.queryOptions({
      input: hasOAuthParams
        ? { body: { client_id: clientId, redirect_uri: redirectUri } }
        : skipToken,
      context: { silent: true },
    }),
  )
  const { mutateAsync: authorize, isPending: authorizing } = useMutation(
    consoleQuery.oauth.provider.authorize.post.mutationOptions({ context: { silent: true } }),
  )
  const returnUrl = buildReturnUrl('/account/oauth/authorize', `?${searchParams.toString()}`)
  const signInUrl = `/signin?redirect_url=${encodeURIComponent(returnUrl)}`
  const { mutateAsync: logout } = useLogout({ redirectTo: signInUrl })
  const { isAutoAuthorizing } = useSilentAuthorize({
    authAppInfo,
    authorize,
    clientId,
    hasOAuthParams,
    isLoggedIn,
    isProfileLoading,
    redirectUri,
    searchParams,
    state,
  })
  const localizedAppLabel =
    authAppInfo?.app_label[language] ?? authAppInfo?.app_label[language.replace('_', '-')]
  const englishAppLabel = authAppInfo?.app_label.en_US ?? authAppInfo?.app_label['en-US']
  const appLabel =
    (typeof localizedAppLabel === 'string' && localizedAppLabel) ||
    (typeof englishAppLabel === 'string' && englishAppLabel) ||
    t(($) => $.unknownApp, { ns: 'oauth' })
  useDocumentTitle(
    authAppInfo
      ? `${t(($) => $.connect, { ns: 'oauth' })} ${appLabel}`
      : t(($) => $.connect, { ns: 'oauth' }),
  )

  const onLoginSwitchClick = async () => {
    try {
      if (isLoggedIn) await logout()
      else router.push(signInUrl)
    } catch {
      // The request layer reports logout failures; keep the current session on this page.
    }
  }

  const onAuthorize = async () => {
    if (!clientId || !redirectUri) return
    try {
      const { code } = await authorize({ body: { client_id: clientId } })
      globalThis.location.href = buildOAuthCallbackUrl(redirectUri, code, state)
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : String(error)
      toast.error(`${t(($) => $['error.authorizeFailed'], { ns: 'oauth' })}: ${message}`)
    }
  }

  if (!hasOAuthParams || isOAuthError) {
    return (
      <div className="flex flex-col gap-4 bg-background-default-subtle text-text-secondary">
        <div className="body-md-regular">
          {t(($) => $[hasOAuthParams ? 'error.authAppInfoFetchFailed' : 'error.invalidParams'], {
            ns: 'oauth',
          })}
        </div>
        {isOAuthError && (
          <Button
            variant="secondary"
            size="large"
            onClick={() => void refetchOAuthApp()}
            loading={isOAuthFetching}
          >
            {t(($) => $['operation.retry'], { ns: 'common' })}
          </Button>
        )}
      </div>
    )
  }

  if (isProfileLoading || isOAuthLoading || isAutoAuthorizing) {
    return (
      <div className="bg-background-default-subtle">
        <LoadingPlaceholder className="h-full" />
      </div>
    )
  }

  return (
    <div className="bg-background-default-subtle">
      {authAppInfo?.app_icon && (
        <div className="w-max rounded-2xl border-[0.5px] border-components-panel-border bg-text-primary-on-surface p-3 shadow-lg">
          <img src={authAppInfo.app_icon} alt="app icon" className="size-10 rounded-sm" />
        </div>
      )}

      <div className={`mt-5 mb-4 flex flex-col gap-2 ${isLoggedIn ? 'pb-2' : ''}`}>
        <div className="title-4xl-semi-bold">
          {isLoggedIn && (
            <div className="text-text-primary">{t(($) => $.connect, { ns: 'oauth' })}</div>
          )}
          <div className="text-saas-dify-blue-inverted">{appLabel}</div>
          {!isLoggedIn && (
            <div className="text-text-primary">
              {t(($) => $['tips.notLoggedIn'], { ns: 'oauth' })}
            </div>
          )}
        </div>
        <div className="body-md-regular text-text-secondary">
          {isLoggedIn
            ? `${appLabel} ${t(($) => $['tips.loggedIn'], { ns: 'oauth' })}`
            : t(($) => $['tips.needLogin'], { ns: 'oauth' })}
        </div>
      </div>

      {isLoggedIn && userProfile && (
        <div className="flex items-center justify-between rounded-xl bg-background-section-burn-inverted p-3">
          <div className="flex items-center gap-2.5">
            <Avatar size="lg" aria-hidden="true">
              <AvatarFallback>{getAvatarInitial(userProfile.name)}</AvatarFallback>
              <AvatarImage src={userProfile.avatar_url || undefined} alt="" />
            </Avatar>
            <div>
              <div className="text-text-secondary">{userProfile.name}</div>
              <div className="system-xs-regular text-text-tertiary">{userProfile.email}</div>
            </div>
          </div>
          <Button variant="tertiary" size="small" onClick={onLoginSwitchClick}>
            {t(($) => $.switchAccount, { ns: 'oauth' })}
          </Button>
        </div>
      )}

      {isLoggedIn && Boolean(authAppInfo?.scope) && (
        <div className="mt-2 flex flex-col gap-2.5 rounded-xl bg-background-section-burn-inverted px-5.5 py-5 text-text-secondary">
          {authAppInfo!.scope
            .split(/\s+/)
            .filter(Boolean)
            .map((scope: string) => {
              const scopeInfo = SCOPE_INFO_MAP[scope]
              const ScopeIcon = scopeInfo?.icon ?? RiAccountCircleLine
              return (
                <div
                  key={scope}
                  className="flex items-center gap-2 body-sm-medium text-text-secondary"
                >
                  <ScopeIcon className="size-4" />
                  {scopeInfo?.label ?? scope}
                </div>
              )
            })}
        </div>
      )}

      <div className="flex flex-col items-center gap-2 pt-4">
        {!isLoggedIn ? (
          <Link
            href={`/signin?redirect_url=${encodeURIComponent(
              buildReturnUrl('/account/oauth/authorize', `?${searchParams.toString()}`),
            )}`}
            className={cn(buttonVariants({ variant: 'primary', size: 'large' }), 'w-full')}
          >
            {t(($) => $.login, { ns: 'oauth' })}
          </Link>
        ) : (
          <>
            <Button
              variant="primary"
              size="large"
              className="w-full"
              onClick={onAuthorize}
              disabled={!clientId || !redirectUri || isOAuthError}
              loading={authorizing}
            >
              {t(($) => $.continue, { ns: 'oauth' })}
            </Button>
            <Link href="/apps" className={cn(buttonVariants({ size: 'large' }), 'w-full')}>
              {t(($) => $['operation.cancel'], { ns: 'common' })}
            </Link>
          </>
        )}
      </div>
      <div className="mt-4 py-2">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="400"
          height="1"
          viewBox="0 0 400 1"
          fill="none"
        >
          <path d="M0 0.5H400" stroke="url(#paint0_linear_2_5904)" />
          <defs>
            <linearGradient
              id="paint0_linear_2_5904"
              x1="400"
              y1="9.49584"
              x2="0.000228929"
              y2="9.17666"
              gradientUnits="userSpaceOnUse"
            >
              <stop stop-color="white" stop-opacity="0.01" />
              <stop offset="0.505" stop-color="#101828" stop-opacity="0.08" />
              <stop offset="1" stop-color="white" stop-opacity="0.01" />
            </linearGradient>
          </defs>
        </svg>
      </div>
      <div className="mt-3 system-xs-regular text-text-tertiary">
        {t(($) => $['tips.common'], { ns: 'oauth' })}
      </div>
    </div>
  )
}