File size: 2,334 Bytes
388ac76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16601c5
 
 
 
 
 
 
 
 
 
 
 
388ac76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b4cf0b
388ac76
 
16601c5
 
 
 
 
 
 
 
 
 
388ac76
16601c5
388ac76
 
 
16601c5
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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,
				cookies: {
					sessionToken: {
						name: "session_token",
						options: {
							httpOnly: true,
							sameSite: "lax",
							secure: true,
							path: "/",
							maxAge: 3600, // The OAuth token's lifetime is 3600 seconds
						},
					},
				},
				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 Inference Endpoints
				 */
				callbacks: {
					jwt({ token, account, profile }) {
						return {
							...token,
							/**
							 * account & profile are undefined beyond the first login, in those
							 * cases `token.access_token` and `token.username` are defined
							 */
							...(account && { access_token: account.access_token }),
							...(profile && { username: profile.preferred_username }),
						};
					},
					session({ session, token }) {
						return {
							...session,
							access_token: token.access_token,
							user: Object.assign({}, session.user, {
								username: token.username,
							}),
						};
					},
				},
		  })
		: null;

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

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