generated from vercel/ai-chatbot
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathopenrouter-auth-provider.tsx
157 lines (143 loc) · 3.86 KB
/
openrouter-auth-provider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
'use client'
import React, {
createContext,
useContext,
useEffect,
useRef,
useState
} from 'react'
import { useQueryState } from 'nuqs'
import { toast } from 'sonner'
import { useLocalStorage } from '@uidotdev/usehooks'
import { getCodeChallenge, getCodeVerifier } from '@/lib/auth'
import { codeChallengeMethod, getSiteURL, openRouterWebUrl } from '@/lib/utils'
interface OpenRouterAuthContextType {
openRouterKey: string | null
isLoading: boolean
codeChallenge: string
isDialogOpen: boolean
signIn: () => void
signOut: () => void
setIsDialogOpen: (isOpen: boolean) => void
}
const OpenRouterAuthContext = createContext<
OpenRouterAuthContextType | undefined
>(undefined)
const oauthBaseUrl = `${openRouterWebUrl}/auth`
export function OpenRouterAuthProvider({
children
}: {
children: React.ReactNode
}) {
const [openRouterKey, setOpenRouterKey] = useLocalStorage<string | null>(
'openRouterKey',
null
)
const [codeVerifier, setCodeVerifier] = useLocalStorage<string>(
'codeVerifier',
''
)
const [codeChallenge, setCodeChallenge] = useLocalStorage<string>(
'codeChallenge',
''
)
const [isLoading, setIsLoading] = useState(false)
const [code, setCode] = useQueryState('code')
const [isDialogOpen, setIsDialogOpen] = useState(false)
const hasRunEffect = useRef(false)
const [callbackUrl, setCallbackUrl] = useState(getSiteURL())
useEffect(() => {
setCallbackUrl(globalThis.window.location.origin)
}, [globalThis.window])
useEffect(() => {
async function initializeValues() {
const verifier = await getCodeVerifier()
const challenge = await getCodeChallenge()
setCodeVerifier(verifier)
setCodeChallenge(challenge)
}
if (!codeVerifier || !codeChallenge) {
initializeValues()
}
}, [codeVerifier, codeChallenge, setCodeVerifier, setCodeChallenge])
useEffect(() => {
if (
code &&
codeVerifier &&
!openRouterKey &&
!isLoading &&
!hasRunEffect.current
) {
hasRunEffect.current = true
setIsLoading(true)
fetch('/api/auth', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
code,
codeVerifier
})
})
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch OpenRouter key')
}
return response.json()
})
.then(data => {
if (data.key) {
setOpenRouterKey(data.key)
toast.success('Successfully authenticated with OpenRouter')
}
})
.catch(error => {
toast.error('Failed to authenticate with OpenRouter')
})
.finally(() => {
setIsLoading(false)
setCode(null)
hasRunEffect.current = false
})
}
}, [code, setCode, codeVerifier, setOpenRouterKey, openRouterKey, isLoading])
const signIn = () => {
const authUrl = new URL(oauthBaseUrl)
const searchParams = new URLSearchParams({
callback_url: callbackUrl,
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod
})
authUrl.search = searchParams.toString()
window.location.href = authUrl.toString()
}
const signOut = () => {
setOpenRouterKey(null)
toast.success('Signed out successfully')
}
return (
<OpenRouterAuthContext.Provider
value={{
openRouterKey,
isLoading,
codeChallenge,
isDialogOpen,
signIn,
signOut,
setIsDialogOpen
}}
>
{children}
</OpenRouterAuthContext.Provider>
)
}
export function useOpenRouterAuth() {
const context = useContext(OpenRouterAuthContext)
if (context === undefined) {
throw new Error(
'useOpenRouterAuth must be used within an OpenRouterAuthProvider'
)
}
return context
}