aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/auth.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/auth.ts')
-rw-r--r--src/lib/auth.ts37
1 files changed, 37 insertions, 0 deletions
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
new file mode 100644
index 0000000..dd6b043
--- /dev/null
+++ b/src/lib/auth.ts
@@ -0,0 +1,37 @@
+import { browser } from '$app/environment';
+import { base } from '$app/paths';
+import { redirect } from '@sveltejs/kit';
+import type { ClientSession } from '../hooks.server';
+import { goto } from '$app/navigation';
+
+/**
+ * Returns `true` if scopes are all included in session, otherwise either attempts to re-login with the new scope added (unless `getScopeOnFail` is false) and returns false
+ *
+ * Check the return value of this, even if getScopeOnFail is true; navigating client-side may not stop thread immediately!
+ */
+export const checkScope = (
+ session: ClientSession,
+ /** The scopes we want */
+ neededScopes: string[],
+ /** Redirect to login page if the scopes aren't found */
+ getScopeOnFail = false,
+ /** The target URL if redirecting */
+ next?: string
+) => {
+ const scopes = session.tokens.scope?.split(' ') ?? [];
+ if (!neededScopes.find((v) => !scopes.includes(v))) return true;
+ else if (getScopeOnFail) {
+ const targetUrl = `${base}/login?${
+ next || browser
+ ? `next=${next ?? encodeURIComponent(location.href)}&`
+ : ''
+ }scope=${encodeURIComponent(
+ [...scopes, ...neededScopes]
+ .filter((v, i, a) => a.indexOf(v) === i)
+ .join(' ')
+ )}`;
+ if (browser) goto(targetUrl);
+ else throw redirect(307, targetUrl);
+ }
+ return false;
+};