aboutsummaryrefslogtreecommitdiff
path: root/src/lib/oauth.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/oauth.ts')
-rw-r--r--src/lib/oauth.ts48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/lib/oauth.ts b/src/lib/oauth.ts
new file mode 100644
index 00000000..53764fad
--- /dev/null
+++ b/src/lib/oauth.ts
@@ -0,0 +1,48 @@
+import { dev } from '$app/environment';
+import { redirect, type Cookies } from '@sveltejs/kit';
+
+export interface ClientOptions {
+ id: string;
+ secret: string;
+ redirectURI: string;
+}
+
+export interface CallbackOptions {
+ url: URL;
+ cookies: Cookies;
+ cookie: string;
+ authorise: string;
+ redirect?: string;
+ client: ClientOptions;
+}
+
+export const callback = async (options: CallbackOptions) => {
+ const { url, cookies, cookie, authorise, client } = options;
+ const formData = new FormData();
+
+ formData.append('grant_type', 'authorization_code');
+ formData.append('client_id', client.id);
+ formData.append('client_secret', client.secret);
+ formData.append('redirect_uri', client.redirectURI);
+ formData.append('code', url.searchParams.get('code') || 'null');
+ cookies.set(
+ cookie,
+ JSON.stringify(
+ await (
+ await fetch(authorise, {
+ method: 'POST',
+ body: formData
+ })
+ ).json()
+ ),
+ {
+ path: '/',
+ maxAge: 60 * 60 * 24 * 7,
+ httpOnly: true,
+ sameSite: 'lax',
+ secure: !dev
+ }
+ );
+
+ throw redirect(303, options.redirect ?? '/');
+};