Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

auth.callback.tsx

76 lines2.4 KB

1import { useEffect, useRef, useState } from 'react'
2import { createFileRoute, useNavigate } from '@tanstack/react-router'
3import {
4 completeChatGptSignIn,
5 saveChatGptSignIn,
6} from '@tanstack/ai-openai/siwc'
7import type { ChatGptSignIn } from '@tanstack/ai-openai/siwc'
8import { byok } from '@/lib/byok'
9​
10export const Route = createFileRoute('/auth/callback')({
11 component: ChatGptCallback,
12})
13​
14/**
15 * Sign in with ChatGPT lands here. The code exchange runs on load. Saving
16 * needs a click, because the passkey keyring asks for a WebAuthn prompt.
17 */
18function ChatGptCallback() {
19 const navigate = useNavigate()
20 const started = useRef(false)
21 const [signIn, setSignIn] = useState<ChatGptSignIn | null>(null)
22 const [error, setError] = useState('')
23​
24 useEffect(() => {
25 // The code is single-use. Strict Mode runs effects twice.
26 if (started.current) return
27 started.current = true
28 completeChatGptSignIn().then(
29 (result) => {
30 if (result) setSignIn(result)
31 else void navigate({ to: '/' })
32 },
33 (caught: unknown) =>
34 setError(caught instanceof Error ? caught.message : 'Sign-in failed'),
35 )
36 }, [navigate])
37​
38 return (
39 <div className="flex min-h-[calc(100vh-72px)] items-center justify-center bg-gray-900 p-4">
40 <div className="w-full max-w-sm rounded-lg border border-gray-700 bg-gray-800/50 p-6 text-center text-white">
41 {error ? (
42 <>
43 <p className="mb-4 text-sm text-red-400">{error}</p>
44 <button
45 type="button"
46 className="rounded-md border border-gray-600 bg-gray-800 px-3 py-2 text-sm"
47 onClick={() => void navigate({ to: '/' })}
48 >
49 Back to chat
50 </button>
51 </>
52 ) : signIn ? (
53 <button
54 type="button"
55 className="w-full rounded-md bg-orange-500 px-3 py-2 text-sm font-semibold"
56 onClick={() => {
57 saveChatGptSignIn(byok, signIn).then(
58 () => navigate({ to: '/' }),
59 (caught: unknown) =>
60 setError(
61 caught instanceof Error
62 ? caught.message
63 : 'Could not save sign-in',
64 ),
65 )
66 }}
67 >
68 Save ChatGPT sign-in
69 </button>
70 ) : (
71 <p className="text-sm text-gray-400">Finishing ChatGPT sign-in…</p>
72 )}
73 </div>
74 </div>
75 )