import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import { useSearchParams } from "next/navigation"; import { useState, useEffect } from "react"; import { APP_NAME } from "@calcom/lib/constants"; import { useLocale } from "@calcom/lib/hooks/useLocale"; import { trpc } from "@calcom/trpc/react"; import { Avatar, Button, Select } from "@calcom/ui"; import { Plus, Info } from "@calcom/ui/components/icon"; import PageWrapper from "@components/PageWrapper"; export default function Authorize() { const { t } = useLocale(); const { status } = useSession(); const router = useRouter(); const searchParams = useSearchParams(); const client_id = searchParams?.get("client_id") as string; const state = searchParams?.get("state") as string; const scope = searchParams?.get("scope") as string; const queryString = searchParams?.toString(); const [selectedAccount, setSelectedAccount] = useState<{ value: string; label: string } | null>(); const scopes = scope ? scope.toString().split(",") : []; const { data: client, isLoading: isLoadingGetClient } = trpc.viewer.oAuth.getClient.useQuery( { clientId: client_id as string, }, { enabled: status !== "loading", } ); const { data, isLoading: isLoadingProfiles } = trpc.viewer.teamsAndUserProfilesQuery.useQuery(); const generateAuthCodeMutation = trpc.viewer.oAuth.generateAuthCode.useMutation({ onSuccess: (data) => { window.location.href = `${client?.redirectUri}?code=${data.authorizationCode}&state=${state}`; }, }); const mappedProfiles = data ? data .filter((profile) => !profile.readOnly) .map((profile) => ({ label: profile.name || profile.slug || "", value: profile.slug || "", })) : []; useEffect(() => { if (mappedProfiles.length > 0) { setSelectedAccount(mappedProfiles[0]); } }, [isLoadingProfiles]); useEffect(() => { if (status === "unauthenticated") { const urlSearchParams = new URLSearchParams({ callbackUrl: `auth/oauth2/authorize?${queryString}`, }); router.replace(`/auth/login?${urlSearchParams.toString()}`); } }, [status]); const isLoading = isLoadingGetClient || isLoadingProfiles || status !== "authenticated"; if (isLoading) { return <>>; } if (!client) { return