aboutsummaryrefslogtreecommitdiff
path: root/src/lib
diff options
context:
space:
mode:
authorFuwn <[email protected]>2024-01-06 16:43:50 -0800
committerFuwn <[email protected]>2024-01-06 16:43:50 -0800
commit4353723e7e51d0c8f21f555ee713199c230b0a90 (patch)
tree3f9e7581489cd03d9a3ba590d4e410b282d7ffac /src/lib
parentfeat(static): privacy.txt (diff)
downloaddue.moe-4353723e7e51d0c8f21f555ee713199c230b0a90.tar.xz
due.moe-4353723e7e51d0c8f21f555ee713199c230b0a90.zip
refactor(api): simple oauth handler
Diffstat (limited to 'src/lib')
-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 ?? '/');
+};