Spaces:
Running
Running
| import { redirect, type RequestEvent } from '@sveltejs/kit'; | |
| import { env } from '$env/dynamic/private'; | |
| export async function GET({ url }: RequestEvent) { | |
| const code = url.searchParams.get('code'); | |
| if (!code) { | |
| return new Response('Missing authorization code', { status: 400 }); | |
| } | |
| const clientId = env.HF_CLIENT_ID; | |
| const clientSecret = env.HF_CLIENT_SECRET; | |
| const redirectUri = env.HF_REDIRECT_URI; | |
| if (!clientId || !clientSecret || !redirectUri) { | |
| return new Response('Missing OAuth configuration', { status: 500 }); | |
| } | |
| // Exchange code for access token | |
| const tokenResponse = await fetch('https://huggingface.co/oauth/token', { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/x-www-form-urlencoded' | |
| }, | |
| body: new URLSearchParams({ | |
| client_id: clientId, | |
| client_secret: clientSecret, | |
| code, | |
| grant_type: 'authorization_code', | |
| redirect_uri: redirectUri | |
| }) | |
| }); | |
| if (!tokenResponse.ok) { | |
| const error = await tokenResponse.text(); | |
| console.error('Token exchange failed:', error); | |
| return new Response('Authentication failed', { status: 401 }); | |
| } | |
| const tokenData = await tokenResponse.json(); | |
| const accessToken = tokenData.access_token; | |
| // Fetch user info from HF | |
| const userResponse = await fetch('https://huggingface.co/oauth/userinfo', { | |
| headers: { | |
| Authorization: `Bearer ${accessToken}` | |
| } | |
| }); | |
| if (!userResponse.ok) { | |
| console.error('Failed to fetch user info'); | |
| return new Response('Failed to fetch user info', { status: 500 }); | |
| } | |
| const userInfo = await userResponse.json(); | |
| // Encode auth data to pass to the client via query params | |
| const authData = encodeURIComponent( | |
| JSON.stringify({ | |
| token: accessToken, | |
| user: { | |
| id: userInfo.sub, | |
| name: userInfo.name || userInfo.preferred_username, | |
| username: userInfo.preferred_username, | |
| avatarUrl: userInfo.picture, | |
| email: userInfo.email | |
| } | |
| }) | |
| ); | |
| throw redirect(302, `/?auth_callback=${authData}`); | |
| } | |