File size: 1,785 Bytes
388ac76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { env } from "$env/dynamic/private";
import { skipCSRFCheck } from "@auth/core";
import { SvelteKitAuth } from "@auth/sveltekit";
import type { Handle } from "@sveltejs/kit";
import { sequence } from "@sveltejs/kit/hooks";

const handleSSO =
	env.OAUTH_CLIENT_ID && env.OAUTH_CLIENT_SECRET
		? SvelteKitAuth({
				// Should be fine as long as your reverse proxy is configured to only accept traffic with the correct host header
				trustHost: true,
				/**
				 * SvelteKit has built-in CSRF protection, so we can skip the check
				 */
				skipCSRFCheck: skipCSRFCheck,
				providers: [
					{
						name: "Hugging Face",
						id: "huggingface",
						type: "oidc",
						clientId: env.OAUTH_CLIENT_ID,
						clientSecret: env.OAUTH_CLIENT_SECRET,
						issuer: "https://huggingface.co",
						wellKnown: "https://huggingface.co/.well-known/openid-configuration",
						/** Add "inference-api" scope and remove "email" scope */
						authorization: { params: { scope: "openid profile inference-api" } },
						checks: ["state" as never, "pkce" as never],
					},
				],
				secret: env.OAUTH_CLIENT_SECRET,
				/**
				 * Get the access_token without an account in DB, to make calls to the inference API
				 */
				callbacks: {
					async jwt({ token, account }) {
						if (account) {
							return {
								...token,
								access_token: account.access_token,
							};
						}
						return token;
					},
					async session({ session, token }) {
						return {
							...session,
							access_token: token.access_token,
						};
					},
				},
		  })
		: null;

const handleGlobal: Handle = async ({ event, resolve }) => {
	const response = await resolve(event);
	return response;
};

export const handle = handleSSO ? sequence(handleSSO, handleGlobal) : handleGlobal;