File size: 1,314 Bytes
04ec17f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { redirect, type RequestHandler } from '@sveltejs/kit';
import { randomBytes } from 'crypto';

export const GET: RequestHandler = async ({ url, cookies }) => {
    // Generate a random state parameter for CSRF protection
    const state = randomBytes(32).toString('hex');

    // Store the state in a cookie to verify later
    cookies.set('oauth_state', state, {
        path: '/',
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 60 * 10, // 10 minutes
    });

    // Build the OAuth authorization URL
    const clientId = process.env.OAUTH_CLIENT_ID;
    const redirectUri = process.env.OAUTH_REDIRECT_URI || `${url.origin}/oauth/callback`;
    const scope = 'openid profile email'; // Adjust scopes as needed

    if (!clientId) {
        throw new Error('OAUTH_CLIENT_ID environment variable is not set');
    }

    const authUrl = new URL('https://huggingface.co/oauth/authorize');
    authUrl.searchParams.set('client_id', clientId);
    authUrl.searchParams.set('redirect_uri', redirectUri);
    authUrl.searchParams.set('scope', scope);
    authUrl.searchParams.set('state', state);
    authUrl.searchParams.set('response_type', 'code');

    // Redirect to the OAuth provider
    throw redirect(303, authUrl.toString());
};