From dddef149aea597a145e3717b2c461b251e0f6a8d Mon Sep 17 00:00:00 2001 From: memdmp Date: Wed, 20 Aug 2025 13:39:01 +0200 Subject: feat: oidc attempt 82845345 --- src/lib/auth.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/lib/auth.ts (limited to 'src/lib/auth.ts') 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; +}; -- cgit v1.2.3