File size: 1,074 Bytes
7bb6a57
 
 
 
9fceaf0
 
7bb6a57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/** @type {import('./$types').RequestHandler} */

import { json } from '@sveltejs/kit';

export async function POST({ request }) {
  const { code } = await request.json()

  if (!code) {
    return json({
      message: `No code provided`,
    }, {
      status: 400
    })
  }

  const REDIRECT_URI = `https://${process.env.SPACE_HOST}/login/callback`;
  const Authorization = `Basic ${Buffer.from(
    `${process.env.OAUTH_CLIENT_ID}:${process.env.OAUTH_CLIENT_SECRET}`
  ).toString("base64")}`;

  const request_auth = await fetch("https://huggingface.co/oauth/token", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization,
    },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code: code,
      redirect_uri: REDIRECT_URI,
    }),
  });

  const { access_token } = await request_auth.json();

  if (!access_token) {
    return json({
      message: `No access token provided`,
    }, {
      status: 400
    })
  }

  return json({
    ok: true,
    token: access_token
  })
}